一个模拟/存根 python 模块如何像 urllib

How can one mock/stub python module like urllib(一个模拟/存根 python 模块如何像 urllib)
本文介绍了一个模拟/存根 python 模块如何像 urllib的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我需要测试一个需要使用 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()
    ...

你可以这样定义你的测试:

You could define your test like this:

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.

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

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

groupby multiple coords along a single dimension in xarray(在xarray中按单个维度的多个坐标分组)
Group by and Sum in Pandas without losing columns(Pandas中的GROUP BY AND SUM不丢失列)
Group by + New Column + Grab value former row based on conditionals(GROUP BY+新列+基于条件的前一行抓取值)
Groupby and interpolate in Pandas(PANDA中的Groupby算法和插值算法)
Pandas - Group Rows based on a column and replace NaN with non-null values(PANAS-基于列对行进行分组,并将NaN替换为非空值)
Grouping pandas DataFrame by 10 minute intervals(按10分钟间隔对 pandas 数据帧进行分组)