Posts about Python

Avatar for vbabiy@howsthe.com

Datetime mocking with pyxmox

Published Feb. 11, 2010 by Vitaly Babiy

This is a reference on how to mock out the datetime.now() call in python using mox. Since datetime is a built-in it makes things a little more tricky.

def test_datetime(self):
    now = datetime.datetime.now() # Store it for later use
    m.StubOutWithMock(datetime, 'datetime')

    datetime.datetime.now().AndReturn(now)

    m.ReplayAll()

    datetime.datetime.now()

    m.VerifyAll()
    m.UnsetStubs()

First we will store the current datetime, this has to be done before mocking takes place. Next we use StubOutWitMock to mock out the datetime class, we then record the call to now and have it return our stored now. If you have any question leave them in the comments.

Links:

Avatar for vbabiy@howsthe.com

Python mocking with mox

Published Jan. 10, 2010 by Vitaly Babiy

When building an application it's hard not to depend on some outside resource, that you have no control over. When writing unit tests for this type of application it gets tricky, but thanks to mocking you are able to do so. Mocking comes in two forms, manual (a.k.a monkey patching) or using a mocking framework, we will be using the latter. A mocking framework creates objects that add expectations, define their methods, and return values for each method call in a simple way.

There are a few mocking frameworks available for python:

A blog about development, marketing, and design.