为什么我的测试通过了冲突的断言?

时间:2019-04-20 00:59:22

标签: 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

1 个答案:

答案 0 :(得分:0)

这是一种方法。应该叫做:

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