【问题标题】:How to unit test this code with pymox?如何用 pymox 对这段代码进行单元测试?
【发布时间】:2012-07-06 15:50:57
【问题描述】:

所以我已经安装了pymox,我想测试一下这个方法:

class HttpStorage():

    def download(self, input, output):
        try:
            file_to_download = urllib2.urlopen(input)
        except URLError:
            raise IOError("Opening input URL failed")

        f = open(output, "wb")
        f.write(file_to_download.read())
        f.close()
        return True

我正在阅读 pymox 文档,但我不知道该怎么做。你能帮我提供一些示例代码吗?

【问题讨论】:

  • 有点离题,但为什么要使用pymox呢? stdlib unittest 模块看起来非常充实。

标签: python mox pymox


【解决方案1】:
import unittest
import mox

class HttpStorageTest(mox.MoxTestBase):

  def setUp(self):
    self.httpstorage = HttpStorage()

  def test_download(self):
    self.mox.StubOutWithMock(urllib2, "urlopen")
    test_file = open("testfile")
    urllib2.urlopen(mox.IgnoreArg()).AndReturn(test_file)

    self.mox.ReplayAll()
    feedback = self.httpstorage.download(test_input, test_output)
    self.assertEqual(feedback, True)

您可以尝试这种格式来测试您的下载功能,因为 urllib2.openurl() 已被模拟进行单元测试。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多