Created
September 1, 2012 09:35
-
-
Save imankulov/3568331 to your computer and use it in GitHub Desktop.
Helper class to ease testing Django views
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
from django.test.client import Client as BaseClient | |
from django.core.urlresolvers import reverse | |
class Client(BaseClient): | |
""" | |
I used to be reluctant testing Django views until I wrote this class | |
Helper class to ease testing Django views by reducing the number | |
of lines of code, imports, quotes and curly brackets | |
For example, to test access to URL | |
/hello/Mary/?my_name=John | |
I used to write | |
.. code-block:: python | |
from django.core.urlresolvers import reverse | |
from django.test.client import Client | |
client = Client() | |
url = reverse('core-hello', kwargs={'name': 'Mary'}) | |
resp = client.get(url, {'my_name': 'John'}) | |
Now, assuming the view serving URL "/hello/<smth>/" has the name | |
"core-hello" I can write | |
.. code-block:: python | |
from myapp.tests_helpers import Client | |
resp = Client().view('core-hello', name='Mary').get(my_name='John') | |
Or, if I want to use direct urls | |
.. code-block:: python | |
from myapp.tests_helpers import Client | |
resp = Client().url('/hello/Mary/').get(my_name='John') | |
""" | |
class Url(object): | |
def __init__(self, client, address): | |
self.client = client | |
self.address = address | |
def _proxy_to_client(method_name): | |
def meth(self, **kwargs): | |
return getattr(self.client, method_name)(self.address, kwargs) | |
return meth | |
get = _proxy_to_client('get') | |
post = _proxy_to_client('post') | |
head = _proxy_to_client('head') | |
options = _proxy_to_client('options') | |
put = _proxy_to_client('put') | |
delete = _proxy_to_client('delete') | |
def view(self, view_name, *args, **kwargs): | |
address = reverse(view_name, args=args, kwargs=kwargs) | |
return self.Url(self, address) | |
def url(self, address): | |
return self.Url(self, address) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment