简体   繁体   English

为什么我的 mock.assert_call_once() 没有通过?

[英]Why isn't my mock.assert_called_once() passing?

I have function 1 here:我在这里有 function 1 :

def f1(x):
    f2(x+3)
    return x * x

And function 2 here: function 2 在这里:

def f2(y):
    print("Whatever you do, don't print this.")

I wrote my test here:我在这里写了我的测试:

def test_f1(mocker):
    mock = mocker.patch("functions.f2")
    assert f1(1) == 1
    assert f2(1) is None
    mock.f2.assert_called_once()

When I run pytest, it throws the error:当我运行 pytest 时,它会抛出错误:

>       mock.f2.assert_called_once()
E       AssertionError: Expected 'f2' to have been called once. Called 0 times.

I literally just called "f2" but it's not picking up on it?我真的只是叫“f2”,但它没有接受它? Not sure why.不知道为什么。

For a number of reasons:出于多种原因:

  1. mocker.patch returns the mock, so the mocked f2 is mock , not mock.f2 . mocker.patch返回模拟,所以模拟的f2mock ,而不是mock.f2

  2. From the code you posted, it appears you have a line like从您发布的代码中,您似乎有一行

    from functions import f1, f2

    or或者

    from functions import *

    This means that if you monkey-patch functions.f2 , you are not monkey-patching your local variable f2 .这意味着,如果您对functions.f2进行猴子补丁,您就不会对局部变量f2进行猴子补丁 mock is the same as the mocked functions.f2 , but f2 is no longer the same as functions.f2 (because it's the original functions.f2 , not the mocked one). mock与模拟的functions.f2相同,但f2不再与functions.f2相同(因为它是原始的functions.f2 ,而不是模拟的)。 You can fix this (along with problem #1) with code like:您可以使用以下代码解决此问题(以及问题 #1):

     f2 = mocker.patch("functions.f2") #... f2.assert_called_once()
  3. Except now assert f2(1) is None will fail.除了现在assert f2(1) is None将失败。 This is because you mocked f2 .这是因为您嘲笑了f2 That means the real f2 isn't called.这意味着真正的f2没有被调用。 Did you mean to do a spy instead of a mock?你的意思是做间谍而不是模拟? With a spy, the real function is called.有了间谍,真正的function被调用。 pytest-mock can handle spies, though you might need to change your imports slightly: pytest-mock 可以处理间谍,但您可能需要稍微更改导入:

     import functions from functions import f1, f2 def test_f2(mocker): f2 = mocker.spy(functions, 'f2') assert f1(1) == 1 assert f2(1) is None f2.assert_called_once()
  4. And now we finally...get a failed assert_called_once() again, this time because f2 has been called twice.现在我们终于……再次得到一个失败的assert_called_once() ,这一次是因为f2被调用了两次。 That's because it's called once when you call f1(1) , and then a second time when you call f2(1) .那是因为它在您调用f1(1)时调用一次,然后在您调用f2(1)时调用第二次。

You're asserting that mock.f2() was done, not that f2() was done.您断言mock.f2()已完成,而不是f2()已完成。

I'm not exactly clear on what kind of object your fixture mocker is, nor am I sure I understand what you actually want to do, but perhaps you want mock.assert_called_once() ?我不太清楚你的夹具模拟器是哪种mocker ,我也不确定我理解你真正想要做什么,但也许你想要mock.assert_called_once() You can also check mock.mock_calls() .您还可以检查mock.mock_calls()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM