Archive for the ‘Python’ Category

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.

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.

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.

Using Selenium 2.0 with Python 3.2 doesn’t work well yet

Wednesday, May 4th, 2011

So I recently set up a testing environment using the Selenium webdriver and Python 3.2. I had some initial issues with getting it to just generally run which I resolved and blogged here. Nonetheless, I’ve since had a chance to dig a little deeper and it turns out that there are still things in the code that did not convert well from Python version 2 to 3 using the 2to3.py utility.

As such, I’ve uninstalled Python 3.2 and reinstalled version 2.7. I’ve run some of the tests that were failing while I had 3.2 installed and everything seems to be passing. So that’s good news. I’ll keep an eye out on and updated Python binding for Selenium 2 and give it another shot once there is an update.

Using Selenium 2.0 with Python 3.2

Wednesday, May 4th, 2011

Currently the Python Bindings for Selenium are not completely compatible with Python 3.2. I’ll show here how to make the python files compatible with version 3.2 using the python 2to3 utility. I am assuming here that you have Python installed and running, you have downloaded and installed Selenium 2.0, and that you have downloaded the Python Bindings and dropped the ‘selenium’ directory into your python ‘Lib’ directory to be used as a module.

So if you have all of this installed and you run the following line in the Python IDLE

from selenium import webdriver

you will most likely (considering that the Binding code has not been updated between now and then) get an error indicating a syntax error on line 193 or thereabouts. This syntax error is occurring because the Binding code is written for python version 2.7.

Good news though. Python 3.2 comes with a utility in the ‘Tools’ directory that will convert any .py file or files from version 2 to version 3.

If you want to find the actual file you can find it in the Python32/Tools/Scripts directory. It is named 2to3.py.

So we’ll execute this utility from the command line. So if on windows do Start/Run – type cmd to open the prompt. On mac use Applications/Utilities/Terminal.

(more…)

Python permission denied error when executing a CGI script

Friday, January 21st, 2011

I’ve just started playing with python with the intent of building android apps. As such this may be obvious to the seasoned python programmer, but nonetheless was not too terribly obvious to me at first.

After creating a CGI script to run I noticed that when the browser would execute the script I would get a 200 OK response from the browser, but the page was empty. Upon checking the terminal I received the following error:

Traceback (most recent call last):
File “/Library/Frameworks/Python.framework/Versions/3.1/lib/python3.1/http/server.py”, line 1059, in run_cgi
os.execve(scriptfile, args, env)
OSError: [Errno 13] Permission denied

The solution here is to give the script permission to be executed. To do this run the following line in the terminal (obviously I’m on a mac here):

chmod +x [name of you CGI script]

So just to keep things simple, assume you have a script in your Documents directory named ‘myScript.py’. You would execute the following in the terminal:

Documents myComputer$ chmod +x myScript.py

Essentially, this changes the mode of the specified script to be executable.

One thing to keep in mind, that dumbly wasted a few minutes of my time, is that if you have a terminal window open running the python server you cannot perform the above execution in that window. Make sure you open a new terminal window and execute on the command line.