简体   繁体   中英

How to unit test this code with pymox?

So I have installed pymox and I would like to test this method:

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

I am reading through the pymox documentation but I cannot figure out how to do it. Could you help me with some example code?

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)

You could try this format to test your download funciton, as the urllib2.openurl() has been mocked to do unit test.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM