在单元测试中模拟对象时使用真实数据

问题描述

我在一些单元测试中进行了模拟,我想知道在模拟时是否可以使用真实数据(我正在处理非敏感数据)。

例如,我正在测试允许在应用程序中使用 azure 服务主体进行身份验证的用户成员:

def create_mock(status_code,data):
    def mocked_requests(*args,**kwargs):
        class MockResponse:
            def __init__(self,status_code,json_data):
                self.json_data = json_data
                self.status_code = status_code

            def json(self):
                return self.json_data

        return MockResponse(status_code,data)

    return mocked_requests

class RolesTestCase(unittest.TestCase):
    @mock.patch('requests.get',side_effect=create_mock(
                    200,# HERE MY OBJECT OR DATA MOCKED.
                    {
                        "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#servicePrincipals('99999')/appRoleAssignedTo","value": [{
                            "id": "99999","deletedDateTime": "null","appRoleId": "00000000-0000-0000-0000-000000000000","createdDateTime": "2021-03-21T17:15:40.516616Z","principalDisplayName": "Bernardo Garcia Loaiza","principalId": "99999","principalType": "User","resourceDisplayName": "my-service-principal-name","resourceId": "99999"
                        }]
                    }
                 )
                )
    @mock.patch('roles.get_sp_object_id')
    def test_get_user_role_assignments(self,get_sp_object_id,mock):
        token = "FOOBAR"
        get_user_role_assignments(token,{"id": "123","name": "group_name"})
        get_sp_object_id.assert_called_with(token,"name": "group_name"})

在上面的 @mock.patch('requests.get,...' 代码部分,如果不是 JSON 文档中的 99999 值,而是输入真实值可以吗?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)