Python Pytest模拟程序/模拟/魔术模拟/补丁:创建同一类的多个模拟实例

时间:2019-09-18 17:39:20

标签: python mocking pytest magicmock

上课

class Student:
    __name = 'blah'

    @property
    def name(self):
        return self._NAME

    def submit_homework():
        # work

我如何创建一个返回新的Student模拟实例的工厂。在测试中,我需要能够创建多个Student实例,为其分配所有唯一名称,并返回submit_homework

我尝试过

@pytest.fixture
def mock_student_factory(mocker):

    def _mock_student_factory(stage_name: str='name'):

        instance = mocker.patch('student.Student', autospec=True)
        type(instance).name = mock.PropertyMock(return_value=stage_name)
        print(instance)

        return instance

    yield _mock_stage_factory

它对于第一次致电工厂很有效,但在随后的致电中死亡。

mock_student_0 = mock_student_factory('NAME-0')
mock_student_1 = mock_student_factory('NAME-1') # Throws

例外

self = <[AttributeError("_name") raised in repr()] Parameter object at 0x1159951b0>
name = <MagicMock name='Student.submit_homework.__code__.co_varnames.__getitem__()' id='4657025152'>
kind = <_ParameterKind.VAR_POSITIONAL: 2>

    def __init__(self, name, kind, *, default=_empty, annotation=_empty):
        try:
            self._kind = _ParameterKind(kind)
        except ValueError:
            raise ValueError(f'value {kind!r} is not a valid Parameter.kind')
        if default is not _empty:
            if self._kind in (_VAR_POSITIONAL, _VAR_KEYWORD):
                msg = '{} parameters cannot have default values'
                msg = msg.format(_get_paramkind_descr(self._kind))
                raise ValueError(msg)
        self._default = default
        self._annotation = annotation

        if name is _empty:
            raise ValueError('name is a required attribute for Parameter')

        if not isinstance(name, str):
            msg = 'name must be a str, not a {}'.format(type(name).__name__)
>           raise TypeError(msg)
E           TypeError: name must be a str, not a MagicMock

../../../../.pyenv/versions/3.7.0/lib/python3.7/inspect.py:2478: TypeError

问题:是否可以一次创建同一类的多个模拟?如果可以,怎么办?

0 个答案:

没有答案