Pytest 补丁保留在其他测试类中

问题描述 投票:0回答:1

我有一个包含

/src
/test
目录的项目结构。

第一个执行的测试是

/test/kernel_application_test.py

在那里,我创建了一个测试类

@mock.patch('customlib.snowflake.SnowFlakeConnector', autospec=True)
class TestExecuteApplication(unittest.TestCase):

然后另一个类被执行:

/test/sql_loader_test.py

在该类中,导入了

customlib.snowflake.SnowFlakeConnector
,没有补丁。请注意,
/test/sql_loader_test.py
中的测试我创建了另一个继承自unittest.TestCase的类。

如果我运行

pytest /test/sql_loader_test.py
,测试会正确运行,但是当我运行
pytest
时,
/test/sql_loader_test.py
内的测试会稍后执行,并将 SnowFlakeConnector 视为模拟,即使它没有在那里定义为补丁。如果我打印我得到的对象:

<NonCallableMagicMock name='SnowFlakeConnector()' spec='SnowFlakeConnector' id='5159517536'>

请注意,id 与

/test/kernel_application_test.py
中打印的相同,但我不明白应用于一个测试的补丁如何影响其他测试。我的猜测是,使用补丁装饰器,补丁在类执行后被删除,但情况似乎并非如此

python pytest
1个回答
0
投票

当我将模拟与 pytest 一起使用时,我使用

pytest-mock
pytest 插件,然后通过
mocker
pytest 夹具访问模拟功能。我怀疑您使用的方法可能在其他框架中有效,但不是 pytest 中的工作方式。

虽然使用装饰器和上下文管理进行模拟很棒,但不幸的是,在 pytest 中这不是方法。

相反,你需要这样的东西:

pip install pytest-mock

和:

class TestExecuteApplication:  # NOTE: there's no reason to inherit from TestCase when using pytest

    def test_one(self, mocker):   # Mentioning 'mocker' brings it in as a fixture
       mocker.patch('customlib.snowflake.SnowFlakeConnector', autospec=True)
       # Now access that mocked code and write your test assertions
       # after this test function finishes, the mock patch will be undone
       assert TheThingsYouAssertForYourTest == 1234
© www.soinside.com 2019 - 2024. All rights reserved.