python - mock 全类同学

标签 python python-2.7 unit-testing mocking

长话短说,当只是该方法被模拟对象替换时,我完全能够模拟类方法,但是当我尝试用模拟替换整个类时,我无法模拟该方法对象

@mock.patch.object 成功模拟 scan 方法,但 @mock.patch 失败。我已经按照以下示例进行了操作 https://docs.python.org/3/library/unittest.mock.html#unittest.mock.patch 但显然我做错了什么。

在这两种情况下,我都在同一命名空间中模拟词典模块(它是由 sentence_parser 中的 import lexicon 导入的),但 mock_lexicon 是词典。词典检查失败

#!python
import sys;
sys.path.append('D:\python\lexicon');
import lexicon;

import sentence_parser;
import unittest2 as unittest;
import mock;

class ParserTestCases(unittest.TestCase) :

    def setUp(self) :
        self.Parser = sentence_parser.Parser();

    @mock.patch('lexicon.lexicon')
    def test_categorizedWordsAreAssigned_v1(self, mock_lexicon) :

        print "mock is lexicon:";
        print mock_lexicon is lexicon.lexicon + "\n";

        instance = mock_lexicon.return_value;
        instance.scan.return_value = "anything";    

        self.Parser.categorize_words_in_sentence("sentence");
        instance.scan.assert_called_once_with("sentence");

    @mock.patch.object(lexicon.lexicon, 'scan')
    def test_categorizedWordsAreAssigned_v2(self, mock_scan) :

        mock_scan.return_value = "anything";    

        self.Parser.categorize_words_in_sentence("sentence");
        mock_scan.assert_called_once_with("sentence");

if (__name__ == '__main__') :
    unittest.main()

输出:

mock is lexicon:
False

======================================================================
FAIL: test_categorizedWordsAreAssigned_v1 (__main__.ParserTestCases)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "D:\python\get_img\getImage_env\lib\site-packages\mock\mock.py", line 1305, in patched
    return func(*args, **keywargs)
  File "./test_sentence_parser.py", line 26, in test_categorizedWordsAreAssigned_v1
    instance.scan.assert_called_once_with("sentence");
  File "D:\python\get_img\getImage_env\lib\site-packages\mock\mock.py", line 947, in assert_called_once_with
    raise AssertionError(msg)
AssertionError: Expected 'scan' to be called once. Called 0 times.

----------------------------------------------------------------------
Ran 2 tests in 0.009s

FAILED (failures=1)

编辑:

为了澄清,解析器定义如下

#!python

import sys;
sys.path.append('D:\python\lexicon');
import lexicon;

class Parser(object) :

    my_lexicon = lexicon.lexicon()

    def __init__(self) :
        self.categorized_words = ['test'];

    def categorize_words_in_sentence(self, sentence) :
        self.categorized_words = self.my_lexicon.scan(sentence);


if (__name__ == '__main__') :
    instance = Parser();
    instance.categorize_words_in_sentence("bear");
    print instance.categorized_words;

最佳答案

这里真正相关的是categorize_words_in_sentence Parser的方法如何使用lexicon。但首先我们应该消除噪音:

print mock_lexicon is lexicon.lexicon + "\n"

什么会导致我们走向错误的方向:尝试用以下方式替换它

self.assertIs(mock_lexicon, lexicon.lexicon)

你会明白你正在打印 False 因为 mock_lexicon 不是 lexicon.lexicon + "\n" 而只是 词典.词典.

现在我无法告诉你为什么第一个测试不起作用,因为答案在 categorize_words_in_sentence 方法中或更可能在 sentence_parser 模块中,我猜你可以在其中使用类似的东西

from lexicon import lexicon

在这两种情况下,请查看 Where to Patch文档可以帮助您了解可能的原因以及在您的案例中真正需要修补的内容。

第二个版本之所以有效,只是因为您正在修补对象而不是引用(应该不同)。

最后更简洁和通用的版本可以是:

@mock.patch('lexicon.lexicon.scan', return_value="anything")
def test_categorizedWordsAreAssigned_v3(self, mock_scan) :
    self.Parser.categorize_words_in_sentence("sentence")
    mock_scan.assert_called_once_with("sentence")

还有一件事:删除 unittest2 至少您不使用 python 2.4 并且您对向后移植的 unittest 功能感兴趣。

[编辑]

现在我可以停止猜测并指出为什么第一个版本不起作用并且永远不会起作用:

class Parser(object) :
    my_lexicon = lexicon.lexicon()

Parser.my_lexicon 属性在加载时进行评估。这意味着当您导入 sentence_parser 时,会创建一个 lexicon 以及与 Parser.my_lexicon 关联的引用。当您修补lexicon.lexicon时,您会保持此引用不变,并且您的解析器对象仍使用导入时创建的原始引用。

您可以做的是通过以下方式修补 Parser 类中的引用

@patch("sentence_parser.Parser.my_lexicon")

您可以使用create_autospect如果您想为您的模拟提供相同的词典签名。

@patch("sentence_parser.Parser.my_lexicon", create_autospec("lexicon.lexicon", instance=True))

关于python - mock 全类同学,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33660332/

相关文章:

用于 ssh 处理的 python 库

asp.net - 如何在测试工具中实例化 asp.net 代码隐藏类?

python - 如何找到运动物体轨迹中的冗余路径(子路径)?

python - Tcl 错误 : bad geometry specifier

javascript - 单元测试以确保函数调用 api 并将数据分配给变量

unit-testing - 以下要求的输入案例是什么

Python 从 Python 字典中获取字符串(键 + 值)

python - 语音到文本 - 将说话者标签映射到 JSON 响应中的相应转录本

python - scrapy LinkExtractor(allow=(url)) 获取错误的抓取页面,正则表达式不起作用

python - 如何使用Python子进程捕获子进程的错误?