問題描述
我需要測試一個需要使用 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的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!