More specifically, I did not want to mock the Data Store Model objects, since that very quickly turns into mocking hell - you just end up spending three times as much time thinking about mocking than you are about code. Fortunately, after quite a bit of digging, I discovered that Google provides a temporary, in-memory datastore stub, specifically made for unit testing! They also provide stubs for mail, urlfetch and the user service. MAN that is nice!
For this example, I am using:
- App Engine SDK 1.1
- Django Helper r30
- Django 0.97
We will be using the Test Runner provided by Django. Django looks for tests in a number of places, one is tests.py - which it expects to be in same folder as models.py and views.py. To have django run your tests you go:
manage.py test nameofYourApp
The code
models.py
tests.py
'
# expect a call to render_to_response. We expect ANY parameters here,
# since checkArgumentsOfRenderToResponse will be testing the input.
self.render_to_response(mocker.ANY, mocker.ANY)
# forward the render_to_response call to checkArgumentsOfRenderToResponse
m.call(checkArgumentsOfRenderToResponse)
#okay, we are done recording our expectations.
m.replay()
# call the view!
address(mockRequest)
retrAddress = Address.all().filter("user = ", users.get_current_user()).get()
self.assertTrue("Mattias Johansson", retrAddress.name)
def testAddressNotLoggedInRedirect(self):
# fake the request
mockRequest = self.mocker.mock()
os.environ['USER_EMAIL'] = ''
self.assertTrue(users.get_current_user() == None) # The user is now None
# Expect a redirect to login.
self.HttpResponseRedirect(users.create_login_url("/address"))
#okay, we are done recording our expectations.
self.mocker.replay()
# call the view!
address(mockRequest)
views.py
address.html is basically just "{{ form }}" and some HTML.
There ya go. Post any questions as comments, and I will try to answer them!