模拟类属性

new*_*mer 3 python class mocking pytest

我有一个带有单个类属性的类,我想模拟它

my_class.py

class MyClass:

    __attribute = ['123', '456']
Run Code Online (Sandbox Code Playgroud)

test_my_class.py

import pytest
from directory.my_class import MyClass

def test_1(mocker):
    with mocker.patch.object(MyClass, '__attribute', {'something': 'new'}):
        test = MyClass()
Run Code Online (Sandbox Code Playgroud)

我得到:

E           AttributeError: <class 'directory.my_class.MyClass'> does not have the attribute '__attribute'
Run Code Online (Sandbox Code Playgroud)

我在尝试时也遇到同样的错误:

def test_2(mocker):
    with mocker.patch('directory.my_class.MyClass.__attribute', new_callable=mocker.PropertyMock) as a:
        a.return_value = {'something': 'new'}
        test = MyClass()
Run Code Online (Sandbox Code Playgroud)

我还尝试了直接分配以及这篇文章中的其他建议: Better way to mock class attribute in python unit test

我的项目正在使用此插件中的模拟装置:https://pypi.org/project/pytest-mock/

Eel*_*Bos 6

你可以用上面的方法来做PropertyMock

from unittest.mock import patch, PropertyMock

class MyClass:
  attr = [1, 2, 3]

with patch.object(MyClass, "attr", new_callable=PropertyMock) as attr_mock:
  attr_mock.return_value = [4, 5, 6]

  print(MyClass.attr) # prints [4, 5, 6]

print(MyClass.attr) # prints [1, 2, 3]
Run Code Online (Sandbox Code Playgroud)

有关文档参考:https://docs.python.org/3/library/unittest.mock.html#unittest.mock.PropertyMock