用繁琐的__init__模拟一堂课

时间:2014-10-15 04:35:09

标签: python django mocking pytest

我有一个实际连接到服务的类,并进行身份验证和填充,但所有这些都在我的代码中的其他地方进行了很好的测试,我只想在以下测试中进行模拟:

对象繁琐的__init __

class B(object):
    def __init__(self, username, password):
        con = connect_to_service() # 
        auth = con.authenticate(username, password)

    def upload(self)
        return "Uploaded"

class A(object):
    def send():
       b = B('user', 'pass')
       b.upload()

tests.py

# Now, I want here to test A, and since it uses B, I need to mock it, but I can't get it to work.
def test_A():
    # Here I need to mock B and B.upload, I tried this:
    a = A()
    b = Mock()
    b.upload.return_value='Hi'
    a.send()

但是这个测试很有意思,因为它在B. init 上达到了auth(),我想成为Mock模型。

2 个答案:

答案 0 :(得分:4)

我认为这是mock.patch的典型用例。请注意patch装饰者需要主模块所在模块的完整路径__main__

from mock import patch, Mock
from abmodule import A,  B #Where A and B are

@patch("abmodule.B")
def test_A(bmock):
    # Set B costructor to return a Mock object
    bmock.return_value = Mock()
    bmock.upload.return_value='Hi'
    a = A()
    a.send()
    #Check if upload was called!
    bmock.return_value.upload.assert_called_with()

之后,您可以再次使用代码其他部分中的原始B:修补后的版本只在函数范围内。

答案 1 :(得分:1)

您需要使用模拟的B.修补实际类.py.test为此提供monkeypatch fixture:

import unittest.mock
import mut  # module under test, where A and B are defined.

def test_A(monkeypatch):
    b = unitest.mock.Mock()
    b.upload.return_value = 'Hi'
    monkeypatch.setattr(mut, 'B', b)
    a = mut.A()
    a.send()