Python:无论从哪里导入模块,都可以模拟修补模块 [英] Python: mock patch a module wherever it is imported from

查看:21
本文介绍了Python:无论从哪里导入模块,都可以模拟修补模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要确保运行单元测试不会触发调用一个沉重的外部世界函数,比如这个:

I need to make sure that running unit tests won't trigger calling a heavy outer world function, say, this one:

# bigbad.py
def request(param):
    return 'I searched the whole Internet for "{}"'.format(param)

多个模块使用这个函数 (bigbad.request) 并且它们以不同的方式导入它(在现实生活中它也可能从外部库导入).假设有两个模块 a 和 b,其中 b 依赖于 a 并且都使用该函数:

Multiple modules use this function (bigbad.request) and they import it differently (in real-life it may be imported from an external library as well). Say, there are two modules, a and b, where b depends on a and both use the function:

# a.py, from...import
from bigbad import request

def routine_a():
    return request('a')

# b.py, imports directly
import a
import bigbad

def routine_b():
    resp_a = a.routine_a()
    return 'resp_a: {}, resp_b=request(resp_a): {}'.format(resp_a, bigbad.request(resp_a))

有没有办法确保 bigbad.request 永远不会被调用?此代码仅模拟其中一个导入:

Is there a way to make sure that bigbad.request is not ever called? This code mocks only one of the imports:

# test_b.py
import unittest
from unittest import mock
import b

with mock.patch('bigbad.request') as mock_request:
    mock_request.return_value = 'mocked'
    print(b.routine_b())

显然我可以重构 b 并更改导入,但这样我不能保证在未来的开发过程中有人不会破坏这个规定.我认为测试应该测试行为而不是实现细节.

Obviously I could refactor b and change the imports but this way I cannot guarantee that someone during the future development is not going to break this provision. I believe tests should test behaviour than implementation details.

推荐答案

import bigbad
bigbad.request = # some dummy function

只要它在任何执行from bigbad import request 的模块运行/导入之前运行,它就会起作用.也就是只要跑了,就会收到dummy函数.

This will work as long as it runs before any module that does from bigbad import request is run/imported. That is, as long as they run after, they will receive the dummy function.

这篇关于Python:无论从哪里导入模块,都可以模拟修补模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆