pythonmoxpymox

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?


Solution

  • 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.