Archive for July, 2011

Simulating User Login in a Django View Unit Test

Tuesday, July 26th, 2011

 

 

So attempting to simulate a user login for a unit test has been driving me crazy for about the last hour or so. Django offers a pretty sweet testing client that simulates the http request/response model allowing for fairly robust unit tests to be built around the application views themselves. I was admittedly skeptical of unit testing views, but given the context I’ve become a believer. But on that note, keep in mind that they are still unit tests, they are not a replacement for Integration or User Acceptance tests.

As such I was a very happy camper until I began writing a test for a view that used the request.user.id value of a logged in user. Of course to test the functional part of the view it checked if a user was logged in (request.user.id != null), and if null would skip processing. Well, that doesn’t do me any good. I needed to convince the view that I am logged in.

So I went through the ropes of using the RequestFactory and the User model to create a fake request with a simulated user. While this worked, there were still session issues. I’ll also note that I found very little on the web about simulating user authentication in unit tests which surprised me since django documentation has never been something I’ve had trouble finding.

Eventually, I discovered a login() method in the Client model. It accepts a username and password and performs the login without requiring the request like the login() method in the ‘auth’ module. Keep in mind that the primary database is not used in unit tests, so an empty replica is used. As such you will need to create the mock user at runtime.

So I’ll wrap up with a working example of the code. Enjoy.

from django.test import TestCase
from django.test.client import Client
from django.contrib.auth.models import User

class ViewsTestCase(TestCase):
    def setUp(self):
        self.client = Client()

    def test_MyView(self):
        User.objects.create_user('fakename', 'fake@pukkared.com', 'mypassword')

        #use test client to perform login
        user = self.client.login(username='fakename', password='mypassword')

        response = self.client.post('/myViewUrlPath/')

Accessing SQLite database in a Django application

Monday, July 25th, 2011

I’ve been building some apps in Django lately. The apps are fairly small and Django comes with what is pretty much out of the box support for SQLite. While I love the ORM built in data management in Django, during development I often find myself needing to visually view the contents in my database, and if necessary quickly make updates.

So I started looking around and found a pretty cool free app called SQLite Database Browser. While it’s got a few bugs, I really admire the simplicity of the application. When it really comes down to it, I want to be able to view the data cleanly and quickly. Sometimes I will want to update, delete, or insert data. And the very few times that I would want to perform DBA tasks, I’m going to handle that via other means anyways. I found that viewing data is quick and simple. Setup is also very simple. If working locally, just open your db file in your project.

The one bug I found that is pretty annoying concerns creating records. If the table contains fields that are not nullable it becomes impossible to perform inserts via the GUI interface. This pretty much means that you can never really create anything. It appears that in the preferences you can assign a default for non-nullable value that will allow record creation. Only problem is that this preference doesn’t seem to work. I set the preference, close the dialog, reopen the dialog and the preferences are no longer set. Doesn’t seem to be saving or something. Overall, works very well with SQLite databases.

Just Finished Reading: Design Patterns Explained: A New Perspective on Object-Oriented Design

Sunday, July 24th, 2011

This was really an excellent book. I’m hesitant to say if it is really better than other books I’ve read on design patterns simply because I question how much reader experience plays a role in getting a book like this. This is not the first book I’ve read on Design Patterns and OOP programming. However, it is the first one that I’ve really felt that I got. Now there are two possible reasons why I think I got it. First is that it is a clear well-written, well-organized book. Second, is that I actually have some experience to apply to the concepts in the book.

First off, it was indeed a good book. Theory was balanced well with examples. Theory was related with clarity, and the examples were relevant to the theory. I particularly liked the focus not on functionality, but on responsibility. I feel it gives the program more of a human quality than just a machine. Beyond the way it changes one’s perception of the program, it really I think gives more meaning to the program. The reality is that after spending months working on a program I do become somewhat attached to it. Handing that program off to someone else to maintain is not always easy. I’ve noticed that after reading this book I’ve looked at my programs as less of a set of functionality that solves a problem, and more as a set of workers, each with there own set of responsibilities, that, at a high level, solves a given problem. I kind of view it as my classes have a responsibility. That class is decomposed into the functionality necessary to perform that responsibility. At this point testing now involves straight unit tests of pieces of functionality, and something more that tests that a responsibility is performed. This seems above unit testing, but not quite integration testing. Above all, my development style has not really changed, only my way of thinking about it.

Which brings me to my next observation. Which is how my experience affected my perception of the book. I’ve read a number of OOP books that revolve around the explanation and promotion of design patterns. However, I read all of them during my first year of real day-in day-out development. They sort of planted the seeds, but I remember going into the books with so much excitement, only to come out on the other end confused and wondering what just happened.

I think I now understand though. I didn’t come out of this one dazed and confused, and I’m not convinced that it is because it was a much better book. Instead what I found throughout this book was a constant connection with my experience. As he explained the Adapter Pattern, I would think that I used this all the time, I just didn’t realize it had a name. When explaining the Bridge Pattern I’m thinking of how I could have written better applications if I had understood then what I know now. A number of years have passed between reading my first Design Patterns books and now. And those few years have been spent developing software full-time. As such Design Patterns now make sense to me. Explanations seemed to clarify or give names to what I already know conceptually, or provide ways to improve designs I have or am already working on. I feel that for me at least I had to spend time designing software without patterns to really understand how patterns can provide consistency, maintainability, and a common dictionary of ideas for developers to communicate more effectively. Overall, very much worth the read.

Python IDLE performs a SaveAs with every file save

Saturday, July 23rd, 2011

This is really just a note to myself and others who may encounter the Python IDLE performing a saveAs every time command/ctrl S shortcut is performed. This happened to me while working on some Python code. After looking around for what could be the issue I found that if CapsLock is turned on the save shortcut becomes a SaveAs function. Seems pretty strange to me as I see no real reason for this. Nonetheless, simple enough to get around, just mildly frustrating in the moment. Turn off your CapsLock.