像urllib这样的模拟/存根python模块如何 [英] How can one mock/stub python module like urllib

查看:89
本文介绍了像urllib这样的模拟/存根python模块如何的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要测试一个函数,该函数需要使用urllib.urlopen(它也使用urllib.urlencode)来查询外部服务器上的页面.服务器可能已关闭,页面可能已更改;我不能依靠它进行测试.

I need to test a function that needs to query a page on an external server using urllib.urlopen (it also uses urllib.urlencode). The server could be down, the page could change; I can't rely on it for a test.

控制urllib.urlopen返回的最佳方法是什么?

What is the best way to control what urllib.urlopen returns?

推荐答案

另一种简单的方法是让您的测试覆盖urllib的urlopen()函数.例如,如果您的模块有

Another simple approach is to have your test override urllib's urlopen() function. For example, if your module has

import urllib

def some_function_that_uses_urllib():
    ...
    urllib.urlopen()
    ...

您可以这样定义测试:

import mymodule

def dummy_urlopen(url):
    ...

mymodule.urllib.urlopen = dummy_urlopen

然后,当您的测试调用mymodule中的函数时,将调用dummy_urlopen()而不是实际的urlopen().像Python这样的动态语言,使测试方法和类的存根变得非常容易.

Then, when your tests invoke functions in mymodule, dummy_urlopen() will be called instead of the real urlopen(). Dynamic languages like Python make it super easy to stub out methods and classes for testing.

有关我的博客的更多信息,请参见 http://softwarecorner.wordpress.com/上的博客文章.测试的依赖项.

See my blog posts at http://softwarecorner.wordpress.com/ for more information about stubbing out dependencies for tests.

这篇关于像urllib这样的模拟/存根python模块如何的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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