Posts Tagged ‘Django’

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.

Django Error: ‘CSRF verification failed. Request aborted.’

Thursday, June 2nd, 2011

I just got this error when trying to execute a Django application locally. A quick search on the web revealed that I needed to include the following two lines:

'django.middleware.csrf.CsrfViewMiddleware'
'django.middleware.csrf.CsrfResponseMiddleware'

in the ‘MIDDLEWARE_CLASSES’ setting in the Settings.py of the application.

In my setup ‘django.middleware.csrf.CsrfViewMiddleware’ class path was already there, but ‘django.middleware.csrf.CsrfResponseMiddleware’ path was not. I added the latter and it seemed to have resolved the error.

I’m not completely sure what these classes do in detail, but it appears to revolve around security related to the local developing environment and obviously cross-site forgery. I also noticed in the ‘django.middleware.csrf.CsrfResponseMiddleware’ class there are notes that the class was deprecated as of Django 1.4. Once I saw this I removed the path from my Settings.py file, re-ran the application, and it appears to still work. I can’t really explain it, but adding it (at least temporarily) resolved the issue so I thought I would spread the wealth.

Just Finished Reading: Django – Visual QuickPro Guide

Wednesday, June 1st, 2011

I am pretty familiar with the MVC structure and have been writing Python for a while now mostly within the context of unit and integration testing. I started to think that maybe it was time to begin looking into web development with Python. In the past I’ve done a little work with python and CGI, but decided to look into Django as a framework for building Python sites.

I read a number of reviews on this book before picking it up and many of the complaints seemed to revolve around the fact that the book does not consistently build an application throughout the chapters. While true, I believe it adds to the learning experience in that it drills the basics of creating a Django application into your head. The book has 10 chapters and each chapter is a new application. While many of the applications are simply expanded versions of the application built in the previous chapter the author to go through again the process of creating the application. While probably annoying for the advanced Django programmer, the beginner leaves the book with the ability to set up a Django application in his or her sleep. Ultimately repetition is the best way to learn, and this book is full of repetition.

The writing style was clean and concise. No real issues with versioning. All of the code seemed to work as illustrated. Overall, I was looking to get a broad idea of what Django was all about, and on a high level what I could get out of it. If you’re at all advanced with the Django framework this book will probably bore you out of your mind, but if your a Django newbie I think you’ll find this book very informative.

If I had one criticism of the book, it would be that on a very basic level the book continued to be very instructive in how to accomplish certain tasks. I like the idea that I have to create a new application and set up a new database for each chapter. But I also think that it is good to force the user to begin doing it themselves without instructions. For example after chapter 6 or so the instructions should have indicated to the user that they should create an application named ‘thisApplication’ with a database named ‘thisDB’ instead of going through detailed instructions each time.

Overall good book, and well worth the time to read.