Simulating User Login in a Django View Unit Test

July 26th, 2011 - by Matthew Cook

 

 

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

July 25th, 2011 - by Matthew Cook

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.

Tags , ,

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

July 24th, 2011 - by Matthew Cook

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

July 23rd, 2011 - by Matthew Cook

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.

Just Finished Reading: 97 Things Every Programmer Should Know

June 10th, 2011 - by Matthew Cook

This is a very good book for providing high-level insight into both the technical and the procedural aspects of programming. By procedural I mean in general the software development lifecycle process. There are 97 chapters, each roughly a page in length on a topic every programmer should know. The short concise chapters actually made this a very easy and quick read.

The book did what I would want any book to do. It taught me a lot of things I didn’t know, and confirmed a lot of things I thought I knew. I enjoyed the chapters on tips for programmers interacting with and working with QA departments. I feel that it is very important for both teams to understand each others approach. I also felt like there was a lot of common sense in the book. The advice given in many cases was good practical tips that could be applied independently of organizational structure. Essentially, most of what I found could be practiced by both the cowboy coding freelancer and the programmer working within the confines of structured processes.

Lastly I’ll note that I thought it was pretty cool that some topics were covered multiple times from different perspectives. Not to the point of contradiction, but enough to indicate the context sensitivity of certain topics. Again, a good read. I certainly feel like I came out of the book a better programmer.

Using Badboy to build JMeter Test Plans over an SSL

June 8th, 2011 - by Matthew Cook

I’ve just recently began using JMeter to stress/load test a Coldfusion application. After reading some blogs on JMeter I got everything set up locally and created a proxy site to my application. But I quickly realized that the proxy is not supported for applications running under an SSL.

The JMeter forum revealed that an easy way to create test cases under an SSL is to actually create the test with a program called Badboy. Luckily for me I’ve been using badboy for automated regression testing for the past year or so. I had never noticed however, that once a badboy test is created there is an export to JMeter option. After exporting a test case I then learned that the badboy export has not yet been updated to support JMeter 2.4. However, it does support JMeter 2.3.4

So the steps for setting up an environment for creating JMeter 2.4 test cases for an application running under an SSL are:

  1. Download JMeter 2.4 (http://jakarta.apache.org/site/downloads/downloads_jmeter.cgi)
  2. Download JMeter 2.3 (http://archive.apache.org/dist/jakarta/jmeter/binaries/)
  3. Download BadBoy (http://www.badboy.com.au/download/index)

Note that both versions of JMeter are downloaded on the assumption that you will want to execute your JMeter tests in 2.4, but you will need 2.3 to make the test cases compatible with 2.4. If you are happy just using 2.3 then you will not need to download 2.4.

Once you have the necessary software do the following:

Read the rest of this entry »

Loading resizable fonts dynamically based on window size

June 6th, 2011 - by Matthew Cook

A reader asked concerning a post I wrote a while back on Resizing text with jQuery and window resize:

Can the text resize adapt to the window size when the page is loaded and also change when the window gets resized?

Essentially, in my previous post I had hard-coded a font size in the CSS of 30px. It would then resize as the window was resized horizontally. But no matter what size the window was when the page was loaded the text was always set to 30px. So I’ve wrote up a simple code sample below in jQuery illustrating how to set the font-size in a div based on the size of the window that the site is loaded in. The original code was fairly easy to refactor to accomplish this. Essentially I added the following function

getOriginalFontSize = function()
{
	var windowWidth = $(window).width();

	var thisFontSize = windowWidth / 50;

	return thisFontSize;
}

and changed the line

var originalFontSize = 30;

to

var originalFontSize = getOriginalFontSize();

So the final block of javascript looks like

Read the rest of this entry »

Tags

Just Finished Reading: Head First Python

June 5th, 2011 - by Matthew Cook

I’m usually a huge fan of the Head First series of books. They are, in general, written in a way that is geared towards efficient learning. I almost always take great joy in some of their puzzles and subtle humor. This book, was no exception up to the chapter on mobile development with Python.

At some point in this chapter nothing seemed to work. I ended up doing a lot of research trying to understand how to do now what the book was instructing me how to do then. The problem was essentially that the Android API for Python had been updated and changed fairly substantially it seems since the book was written. While this is natural for APIs and programs in general it can really ruin the teaching / learning experience for someone really new to the topic.

The resulting issue was that each of the following chapters (which I believe was three) were very difficult to follow since they were building on the mobile app development chapter that had fallen to pieces.

In the end I learned a lot about Python outside of the Android API, but there may be better general python references out there to check out.

Tags

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

June 2nd, 2011 - by Matthew Cook

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

June 1st, 2011 - by Matthew Cook

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.

Tags ,