Friday, May 03, 2013

Mock a socket timeout with HTTPretty

Let's say you have a client that raises MyClientTimeoutException if the underlying socket connect times out. You can unit test this by using the HTTPretty library and stubbing out socket. This example uses Mox.

import socket
import unittest

from httpretty import HTTPretty, httprettified
import stubout

class Test(unittest.TestCase):
    def setUp(self):
        super(Test, self).setUp()
        self.stubs = stubout.StubOutForTesting()

    def tearDown(self):
        super(Test, self).tearDown()
        self.stubs.UnsetAll()
        self.stubs.SmartUnsetAll()

    @httprettified
    def test_timeout_call(self):
        client = MyClient()
        HTTPretty.register_uri(HTTPretty.GET, "http://foo/")

        # fake a timeout
        def fake_create_connection(address, timeout):
            raise socket.timeout('timeout')

        self.stubs.Set(socket, 'create_connection', fake_create_connection)
        self.assertRaises(MyClientTimeoutException,
                          client.call,
                          "http://foo/")

19 comments:

  1. Great Post!
    Thanks a lot for sharing!
    I found this blog to be very useful!!
    DevOps training in Bangalore

    ReplyDelete
  2. 114F1917C1Levi0E9C716A0A10/11/2024 9:27 AM

    165B911A88
    telegram show sitesi

    ReplyDelete