python - 尝试模拟对象中的方法给出 'AttributeError'

标签 python unit-testing python-2.7 mocking

我正在尝试测试一个已经存在的类中的方法。在 Foo.crawler.crawlerapp.CrawlerApp 类的 inputStreamThread 方法中调用方法 addUrl

inputStreamThread 从 stdin 读取然后调用 addUrl

addUrl也在CrawlerApp类中

我希望能够在模拟 addUrl 上使用 assert_called_with 来检查 inputStreamThread 是否在做正确的事情并调用 添加网址

问题是我无法获得 CrawlerAppaddUrl 模拟的正确语法

我直接使用了模拟文档中的示例,但得到了如下所示的错误

如您所见,我也在模拟标准输入以便能够在其上呈现测试数据

我的问题是,我应该使用什么代码来执行此类测试而不显示错误?

import Foo.crawler.crawlerapp
from unittest import TestCase
from mock import patch, Mock
from mephistopheles.messageformat import EventDataFrame
from mephistopheles.messageformat.types import adservers as pbufs
import time
import sys


class testDeserial(TestCase):

    def generate_dummy_auction_event(self,url):
        adunitinfo = pbufs.AdUnitInfo(index_on_page=0, url=url)
        geoloc = pbufs.GeoLocation(country="DE", region="low")
        userinfo = pbufs.UserInfo(user_hash=1,
                                  ip_octets=1,
                                  geolocation=geoloc,
                                  language="en")
        auctioninfo = pbufs.AuctionInfo(timestamp=int(time.time()),
                                        user=userinfo,
                                        ad_unit=adunitinfo)
        return auctioninfo

    def setUp(self):
        pass

    @patch.object(Foo.crawler.crawlerapp.CrawlerApp,'addUrl')
    def test_check_url(self, MaddUrl):
        url_a = "http://audaxing.wordpress.com"
        dummy_event = self.generate_dummy_auction_event(url_a)
        with patch("sys.stdin") as mock_stdin:
            mock_stdin.read.return_value = dummy_event
            ca._running = True
            input_thread = threading.Thread(target=self.inputStreamThread)
            input_thread.start()
            time.sleep(0.5)
            ca._running = False
        MaddUrl.assert_called_with(url_a)

测试运行输出....

$ bin/tests --tests-pattern=test_deserialize
Test-module import failures:

Module: Foo.crawler.tests.test_deserialize

Traceback (most recent call last):
  File "/home/jamie/svn/Foo/crawler.buildout/trunk/src/Foo.crawler/Foo/crawler/tests/test_deserialize.py", line 11, in <module>
    class testDeserial(TestCase):
  File "/home/jamie/svn/Foo/crawler.buildout/trunk/src/Foo.crawler/Foo/crawler/tests/test_deserialize.py", line 28, in testDeserial
    @patch.object(Foo.crawler.crawlerapp.CrawlerApp,'addUrl')
AttributeError: 'function' object has no attribute 'object'



Test-modules with import problems:
  Foo.crawler.tests.test_deserialize
Total: 0 tests, 0 failures, 0 errors in 0.000 seconds.

最佳答案

我想出了最后该怎么做。打字机有点像猴子,不知道为什么我必须使用“patch”而不是“patch.object”或者为什么我需要先制作 Mock() 对象。我只是尝试了文档中示例中的所有可能模式

无论如何,这对我有用

def test_check_url(self):
    url_a = "http://audaxing.wordpress.com"
    dummy_event = self.generate_dummy_auction_event(url_a)
    with patch("sys.stdin") as mock_stdin:
        MaddUrl = Mock()
        Minit = Mock(return_value=None)
        with patch('Foo.crawler.crawlerapp.CrawlerApp.__init__', Minit, create=True):
            with patch('Foo.crawler.crawlerapp.CrawlerApp.addUrl', MaddUrl, create=True):

                ca = Foo.crawler.crawlerapp.CrawlerApp(1)
                mock_stdin.read.return_value = EventDataFrame(1, "TOKEN1", dummy_event.SerializeToString()).to_bytes()
                ca._running = True
                input_thread = threading.Thread(target=ca.inputStreamThread)
                input_thread.start()
                time.sleep(0.5)
                ca._running = False
    MaddUrl.assert_called_with(url_a)

关于python - 尝试模拟对象中的方法给出 'AttributeError',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15928447/

相关文章:

python - 具有用于分箱目的的条件的数据帧分组聚合计数函数

objective-c - 测试: Objective-C + Swift

python-2.7 - Abaqus 中的 Scipy 优化 : ImportError: DLL load failed: %1 is not a valid Win32 application

python - ast.literal_eval 用于 python 中的变量?

unit-testing - 您如何将单元测试改造为代码库?

python - 如何为 python 包 bintrees 安装 C 函数?

python - 我们应该将 session 权限存储在 python 搁置中还是作为 session 变量?

python - 在 if 语句后使用变量

python - __main__ 是否保证始终可导入?

unit-testing - 如何为速度模板编写单元测试?