簡體   English   中英

如何模擬在同一文件中定義但未被測試方法導入的函數?

[英]How to mock a function that is defined in the same file and is not imported by the method being tested?

到目前為止,我有以下代碼:

import unittest
from mock import patch, Mock


def method_1():
    from math import ceil
    return ceil(1.2)


def test_1():
    m = Mock(return_value=10)
    with patch('math.ceil', m) as p:
        a = method_1()
        assert(a == 10)


def method_2():
    return method_1() + 1


def test_2():
    m = Mock(return_value=20)
    with patch('method_1', m) as p:
        a = method_2()
        assert(a == 21)

在運行測試時,出現以下錯誤:

$ nosetests -s unittest.py 
.E
======================================================================
ERROR: unittest.test_2
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/nose/case.py", line 197, in runTest
    self.test(*self.arg)
  File "/srv/www/rpr/unittest.py", line 27, in test_2
    with patch('method_1', m) as p:
  File "/usr/local/lib/python2.7/dist-packages/mock.py", line 1564, in patch
    getter, attribute = _get_target(target)
  File "/usr/local/lib/python2.7/dist-packages/mock.py", line 1413, in _get_target
    (target,))
TypeError: Need a valid target to patch. You supplied: 'method_1'

----------------------------------------------------------------------
Ran 2 tests in 27.840s

FAILED (errors=1)

我能夠正確模擬math.ceil ,並且test_1通過而沒有任何問題。 我很難method_1本身。 我該怎么做呢?

我必須將test_2更改為以下內容才能使其正常工作:

def test_2():
    m = Mock(return_value=20)
    with patch(__name__ + '.method_1', m) as p:
        a = method_2()
        assert(a == 21)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM