小编San*_*ani的帖子

检查测试期间 pytest 夹具是否被调用一次

是否提供诸如检查模拟是否实际被调用一次(或带有某些参数的一次)之pytest类的功能?unittest.mock

示例源代码:

my_package/my_module.py

from com.abc.validation import Validation


class MyModule:
    def __init__(self):
        pass

    def will_call_other_package(self):
        val = Validation()
        val.do()

    def run(self):
        self.will_call_other_package()
Run Code Online (Sandbox Code Playgroud)

上述源码的示例测试代码:

test_my_module.py

import pytest
from pytest_mock import mocker

from my_package.my_module import MyModule

@pytest.fixture
def mock_will_call_other_package(mocker):
    mocker.patch('my_package.my_module.will_call_other_package')


@pytest.mark.usefixtures("mock_will_call_other_package")
class TestMyModule:

    def test_run(self):
        MyModule().run()
        #check `will_call_other_package` method is called.

        #Looking for something similar to what unittest.mock provide
        #mock_will_call_other_package.called_once

Run Code Online (Sandbox Code Playgroud)

python pytest pytest-mock

3
推荐指数
1
解决办法
5607
查看次数

标签 统计

pytest ×1

pytest-mock ×1

python ×1