获取传递给模拟对象构造函数的值

时间:2018-07-09 16:03:24

标签: python python-3.x mocking

假设这种情况:

import random
import string

class objectToMock:

    Arg1:list = []
    Arg2:list = None

    def __init__(self, arg1:list, arg2:str):
        self.Arg1 = arg1
        self.Arg2 = arg2
        return

def functionToTest():
    #Get list of random numbers.
    listArg = []
    for x in range(0,5):
         listArg.append(random.randint(1,1000))

    #Get a random string
    stringArg = \
        ''.join(random.choices(string.ascii_uppercase + string.digits, k=5))


    return objectToMock(listArg, stringArg)

如果我想测试functionToTest函数,我该如何模拟objectToMock以便可以将值传递给objectToMock的构造函数?

这是我到目前为止的去处:

import unittest.mock
import #Module with my test objects

def Test_functionToTest
    with mock(objectToMock) as mock_objectToMock:
        result = functionToTest()

我不确定如何将值传递给mock_objectToMock。

1 个答案:

答案 0 :(得分:0)

您可以从模拟对象中获取call_args_list并将其解压缩为tuple。方法如下:

import random
import string

class ObjectToMock(object):
    arg1:list = []
    arg2:list = None
    def __init__(self, arg1:list, arg2:str):
        self.arg1 = arg1
        self.arg2 = arg2
        return

def function_to_test():
    #Get list of random numbers.
    list_arg = []
    for x in range(0,5):
         list_arg.append(random.randint(1,1000))
    #Get a random string
    string_arg = ''.join(random.choices(string.ascii_uppercase + string.digits, k=5))
    return ObjectToMock(list_arg, string_arg)

from unittest.mock import patch

def test_function_to_test():
    with patch('__main__.ObjectToMock') as mock_object_to_mock:
        result = function_to_test()
        for call_obj in mock_object_to_mock.call_args_list:
            args, kwargs = call_obj  # Unpack the call function as a tuple
            print('Here are my args: {}, kwargs: {}'.format(args, kwargs))

请注意,我全部在一个脚本中运行,因此我正在修补的对象位于__main__中。您的课程将在课堂上使用的任何模块中进行。还要注意,我更改了所有骆驼肠衣/蛇肠衣的混合方式。您应该尝试遵守python样式指南,因为它会使您和其他人更轻松地阅读/维护代码。