Custom Search

SUBSCRIBE

SUBSCRIBE : 300 + Free Video Tutorials Programming (Python, golang, Julia), DevOps

Wednesday, November 26, 2014

Python mox mock unittest MultipleTimes example

1)
Without MultipleTimes

class Time:
    def get_time():
        pass


import mox

## Start recording (start record mode)
t=mox.MockObject(Time)

t.get_time().AndReturn("you can call me only once")


## Stop recording (start reply mode)

mox.Replay(t)

t.get_time()

t.get_time()


* Here You can call the method "get_time" only once 




2)
With MultipleTimes

class Time:
    def get_time():
        pass

import mox

t=mox.MockObject(Time)

t.get_time().MultipleTimes().AndReturn("you can call me multiple times")

mox.Replay(t)

t.get_time()

t.get_time()

* Here You can call the method "get_time" multiple times



2 comments:

  1. https://github.com/openstack/python-neutronclient/blob/master/neutronclient/tests/unit/test_cli20.py

    https://code.google.com/p/pymox/wiki/MoxDocumentation
    https://code.google.com/p/pymox/wiki/MoxDocumentation#Stub_Out <== Stub_Out

    https://code.google.com/p/pymox/wiki/MoxRecipes

    ReplyDelete
  2. import mox

    class MyRequestHandler(object):
    def handle_request(self, request):
    self.authenticate(request)
    self.authorize(request)
    self.process(request)

    def authenticate(self, request):
    print "===in authenticate==="

    def authorize(self, request):
    print "===in authorize==="

    def process(self, request):
    print "===in process==="

    handler = MyRequestHandler()

    ##### Start recording (put mock in record mode) #####
    m = mox.Mox()
    m.StubOutWithMock(handler, "authenticate")
    m.StubOutWithMock(handler, "authorize")
    ##Execute this file by commenting and uncommenting following line
    m.StubOutWithMock(handler, "process")

    handler.authenticate(mox.IsA(int))
    handler.authorize(mox.IsA(int))
    handler.process(mox.IsA(int))

    #handler.process().MultipleTimes().AndReturn("vvvvvvvv")

    ##### Stop recording (put mock in reply mode) #####
    m.ReplayAll()

    ##### Start playing #####

    ##Execute this file by passing int and string to method "handle_request"
    handler.handle_request(1)


    #m.UnsetStubs()
    ##Verify that we played all recorded things
    #m.VerifyAll()

    ReplyDelete