«back

spaceblog

RSS

Dad, I dug another hole...

Tue, 15 Aug 2006 13:53

I wrote another mock object, this time replacing urlopen from urllib2.

import urllib2
import StringIO
import unittest

class Dummy_urllib2(object):

    def install(cls):
        urllib2.urlopen = Dummy_urllib2.urlopen

    install = classmethod(install)

    def urlopen(self, url, data=None):
        self.url = url
        self.data = data

        response = StringIO.StringIO("foo")

        def geturl():
            return url

        response.geturl = geturl

        def info():
            return {}

        response.info = info

        return response

    urlopen = classmethod(urlopen)


class TestDummy_urllib2(unittest.TestCase):
    def test_install(self):
        Dummy_urllib2.install()

        url = 'http://notfound.example.org'

        try:
            r = urllib2.urlopen(url)
        except urllib2.URLError, e:
            self.fail("URLError raised, Dummy_urllib2 not installed or failed: %s" % e)

        self.assertEqual(url, Dummy_urllib2.url)
        self.assertEqual(url, r.geturl())
        self.assertEqual(None, Dummy_urllib2.data)
        self.assertEqual("foo", r.read())

if __name__ == '__main__':
    unittest.main()

This time it comes with it's own test suite. How meta!

All content Copyright © 2002-2005 Jamie Wilkinson. Entries in this blog are licensed under the Creative Commons Attribution-Sharealike v2 License.