Python内部实体模拟

标签 python unit-testing mocking patch magicmock

我想测试一个方法,无论它是否调用临时内部对象的特定方法。 (ConfigParser.read)

因此该对象是在内部创建的,方法退出后无法从外部访问它。

使用Python 2.7

在 foobar.py 中

 import ConfigParser

 class FooBar:
     def method(self, filename):
         config=ConfigParser.ConfigParser()
         config.read(filename)
         do_some_stuff()

我想测试config.read是否被调用。

据我了解,补丁装饰器是为此而制作的,但不幸的是,测试用例接收到的 MagicMock 对象与内部创建的对象不同,并且我无法接近方法内部的对象。

我尝试过这样的:

class TestFooBar(TestCase):

    def setUp(self):
         self.myfoobar = FooBar()

    @mock.patch('foobar.ConfigParser')
    def test_read(self,mock_foobar):
        self.myfoobar.method("configuration.ini")
        assert mock_foobar.called # THIS IS OKAY
        assert mock_foobar.read.called # THIS FAILS
        mock_foobar.read.assert_called_with("configuration.ini") # FAILS TOO

问题是: -mock_foobar是在self.myfoobar.method在内部创建ConfigReader之前创建的。 - 调试时mock_foobar具有有关先前调用的内部数据,但没有“read”属性(用于模拟read方法的内部MagicMock)

当然,一种解决办法是重构并为 .read() 或 init() 提供一个 ConfigReader 对象,但并不总是可以更改代码,我想掌握该方法的内部对象,而不接触被测模块。

最佳答案

你已经很接近了!问题是您正在模拟该类,但随后您的测试会检查该模拟类上是否调用了 read() - 但实际上您希望在调用该类时返回的实例上调用 read() 。以下作品 - 我发现第二个测试比第一个测试更具可读性,但它们都有效:

import ConfigParser
from unittest import TestCase

from mock import create_autospec, patch, Mock 


class FooBar(object):
    def method(self, filename):
        config=ConfigParser.ConfigParser()
        config.read(filename)


class TestFooBar(TestCase):

    def setUp(self):
         self.myfoobar = FooBar()

    @patch('ConfigParser.ConfigParser')
    def test_method(self, config_parser_class_mock):
        config_parser_mock = config_parser_class_mock.return_value

        self.myfoobar.method("configuration.ini")

        config_parser_class_mock.assert_called_once_with()
        config_parser_mock.read.assert_called_once_with("configuration.ini")

    def test_method_better(self):
        config_parser_mock = create_autospec(ConfigParser.ConfigParser, instance=True)
        config_parser_class_mock = Mock(return_value=config_parser_mock)

        with patch('ConfigParser.ConfigParser', config_parser_class_mock):
            self.myfoobar.method("configuration.ini")

        config_parser_class_mock.assert_called_once_with()
        config_parser_mock.read.assert_called_once_with("configuration.ini")

关于Python内部实体模拟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32232988/

相关文章:

python - 如何查找 ImageDataGenerator 生成的图像数量

java - 如何模拟抽象类方法?

ruby - 模拟 ruby​​ 类的初始化方法?

unit-testing - 高级单元测试和模拟对象的值(value)

基于参数值的 C++ 假/模拟返回值

python - 如何使用 Django 从 .py 文件中读取媒体文件?

python - opencv背景减法

python - Python 中的 Kruskal 算法

c# - 如果我使用 try/catch,为什么我的 C# 异常单元测试会失败?

reactjs - jest.fn() 值必须是模拟函数或 spy 接收函数 : [Function getTemplates]