Nice thing about Python and Pylons is the complete lack of finds on the google. Basically anything you search on gets you the same 5 links… helpful or not.
This is a quick one though, and by quick I mean quick for you after it took me a f— load of time to get the f—ing thing right. Forgive me for swearing… even though I do it all the time… but in this case I really wanted emphasize how f—ing annoying it was to get this right.
So here’s the thing, you want to unit test a controller. Great. Now the nice thing is it’s actually pretty easy with what’s built into the TestController which is found in the __init__.py file in yourProject/tests. Imported simply by :
from yourProject.tests import *
Provided you didn’t move the tests folder.
Take the start of this method:
def test_loginUser_bad_input(self): #Here is the call to the controller and the return response response = self.app.post(url(controller='security', action='loginUser', email='null', password='null' ))
Now here’s the interesting thing, response is actually a response object. Can you belee dat? At first I thought it was just whatever the controller method would return if called by a method and not during some web request. Turns out that self.app.post actually acts like a real request. Go f—ing figure. I like. So simple yet so capable. It’s like a long lost brother of mine. You know, the long lost brother that is simple yet capable… and is a method. I’m not sure any of that makes sense.
Now the second part of this debacle is how to work with a json response. For this example I am using jsonpickle but in reality the only thing to take from this is WHERE the stupid json actually is:
jsonResponse = jsonpickle.decode(str(response.body))
Yeah so at first I thought it would be just jsonpickle.decode(response) but kept getting all sort of unhappiness. Now like I noted up top, the response is an actually object return that holds all sorts of information. (including header information.. yay?) So the next guess was what you see right above. Go figure what I was looking for was in the .body attribute.
See, told you it was simple. Painful for me, but in the end you win. And I bet you like that. Sadist f—.