python - 为什么我的测试通过时却出现了相互矛盾的断言?

标签 python unit-testing pytest

我是 Python/Pytest 新手,我正在尝试理解模拟/修补。我目前正在向现有代码库添加测试,但在这些概念上遇到了很多麻烦。

我花了几个小时阅读文档(pytest、pytest-mock)、Github 问题、代码等。我还花了很多时间尝试理解我缺少的内容。

我准备了一个小示例项目来帮助展示我所看到的内容。

项目结构:

runner.py
mypkg
  __init__.py
  MyClass.py
  my_test.py
tests
  test_my_class.py

文件内容:

runner.py:

from mypkg import my_test

my_test.run()

mypkg/MyClass.py:

class MyClass:
    test_var = None

    def __init__(self, *args, **kwargs):
        self.test_var = args[0]

    def do_something(self):
        self.do_something_else()

    def do_something_else(self):
        print('Something else')
        print(self.test_var)

mypkg/my_test.py:

from .MyClass import MyClass

def run():
    x = MyClass('test')
    x.do_something()

测试/test_my_class.py:

from mypkg import my_test

def test_my_test(mocker):
    mocker.patch('mypkg.my_test.MyClass')

    my_test.run()
    my_test.MyClass.assert_called_once_with('test')
    my_test.MyClass.assert_not_called
    assert my_test.MyClass.call_count == 1

    my_test.MyClass.return_value.do_something.assert_not_called
    assert my_test.MyClass.return_value.do_something.call_count == 1

    print(my_test.MyClass.mock_calls)

问题在于,即使断言相互冲突,测试也能通过。我不明白 call_count 如何为 1 和 assert_not_called可以同时通过。我不确定我是否在错误的地方进行了修补或错误地执行了其他操作。

将模拟调用转储到 my_test.MyClass显示:[call('test'), call().do_something()] 。我不确定我错过了什么。

我正在使用 python 3.6.5、pytest 4.4.1 和 pytest-mock 1.10.4

最佳答案

这是一个方法。它应该被称为:

mock.assert_not_called    # does nothing useful 
mock.assert_not_called()  # actually makes an assertion

关于python - 为什么我的测试通过时却出现了相互矛盾的断言?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55769338/

相关文章:

python - 如何使用 opencv 和 python 获取 Gstreamer 直播流?

java - 如何在单元测试中处理大字符串?

python - pytest自定义断言,如何获取回溯

python - 在python中将字符串压缩为数字

python - 使用 PySide 将 QImage 转为 Numpy 数组

Python - 在先前将标准输出重定向到文件后将其重置为正常

C# 和 Moq - 如何断言未引发事件

unit-testing - Akka.net Actors 的单元测试

python - 如何让python函数根据环境变量使用字典中的值?

pytest - 如何在多个测试函数之间共享参数化参数?