2

This is my first time testing a socket interface using mocking. I have a class which invoked the _socket.sendto() method. I would like to test if an exception is raised.

class socketUDP(object):

    def __init__(self, host="127.0.0.1", port=2003):
        self.host = host
        self.port = port

        self._socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)


    def send(self, metric, value):

        message = "%s %f\n" % (metric, value)

        try:
            self._socket.sendto(
                message, (self.host, self.port))
        except Exception, e:
            # I would like to test if this exception is raised
            print "Could not relay data: %s" % e

Update:
I am writing some unit tests for the send method and one of the tests I want to do is to see if an exception was raised

yesh
  • 2,052
  • 4
  • 28
  • 51
  • 1
    "Test" as in you're writing tests for the `send` method, or "test" as in you're trying to figure out, within `send`, whether the exception was thrown? And why are you catching the error inside the method anyway? – user2357112 May 15 '15 at 18:26
  • I am writing some unit tests for the send method and one of the tests I want to do is to see if an exception was raised. – yesh May 15 '15 at 18:28

1 Answers1

1

If the send() method catches the exception, this will be rather difficult. You might try monkey-patching the socket.send() method, but that's an iffy solution at best. It seems to me that in this case, you're testing implementation details rather than conformance to an interface, which is a questionable strategy to begin with.

If the send() method does not catch the exception, you can just use assertRaises().

Kevin
  • 28,963
  • 9
  • 62
  • 81