Replacing a method without passthrough.

Asked by Kevin Turner

After being introduced to Mocker by Mike at a recent Portland Python meeting, I'm trying it out with this integration test I'm writing. There's one part left I'm not quite sure how to do, which looks something like this:

class Message(object):
    def send(self, destination):
        # Does network stuff I don't want the tests to invoke.
        socket.blahblahblah

class OurClass(object):

    messageClass = Message

    def __init__(self, where):
        self.there = where

    def yell(self):
        m = self.messageClass()
        m.send(self.there)

class TestWithoutMocker(TestCase):

    def test_yell(self):
        send_list = []
        class FakeMessage(Message):
            def send(self, destination):
                # Don't passthrough! That would be bad.
                send_list.append(destination)

        that = OurClass("there")
        that.messageClass = FakeMessage
        that.yell()
        self.failUnlessEqual(["there"], send_list)

# end

I tried to figure out how to use mocker to provide an expectation and result for Message.send without passthrough, but I haven't quite got it yet.

Question information

Language:
English Edit question
Status:
Solved
For:
Mocker Edit question
Assignee:
No assignee Edit question
Solved by:
Gustavo Niemeyer
Solved:
Last query:
Last reply:
Revision history for this message
Best Gustavo Niemeyer (niemeyer) said :
#1

There are a number of ways you could do it, and all of them would work given only
the above contraints. One or the other might be best, depending on additional
details.

Here is one simple way:

def test_yell(self):
    Message_mock = self.mocker.patch(Message)
    Message_mock.send("there")
    self.mocker.replay()

    that = OurClass("there")
    that.yell()

Is that reasonable for your case?

Revision history for this message
Kevin Turner (keturn) said :
#2

Okay, that does work. Part of this was me being slow to understand how patch works (record expectations on the mock_object, but they will replay in the real one), and part of it was me assuming that patch would default to passthrough and not finding a way to turn it off.

Thanks!

Revision history for this message
Kevin Turner (keturn) said :
#3

Thanks Gustavo Niemeyer, that solved my question.