Mix in classes

These mixin classes may be added to a TestCase to add additional functionality.

1from django_test_tools import UserTestMixin, ViewTestMixin
2
3class MyTestCase(TestCase, UserTestMixin, ViewTestMixin):
4
5    def my_test(self):
6        # perform tests

UserTestMixin

UserTestMixin contains a collection of utilities for creating users.

CREATE_USER

create_user(cls, username='tester', **kwargs)

Retrieves or creates a user and returns it. Password is set to secret. Additional kwargs are passed to User init if given. This is a class method and may be executed without a UserTextMixin instance.

CREATE_USERS

create_users(self, users, context={})

Create multiple users and add them to the given context. The pattern that django_test_tools expects is that you will create a set of users and then grant them specific permissions or cases.

users is a list of usernames or a tuple of username and kwargs to pass to create_user
context is any dict. This may be used to automatically add the users to a context, or test instance.

 1class MyTestCase(TestCase, UserTestMixin):
 2
 3    def setUp(self):
 4        user_list = [
 5            ('superuser', {is_superuser:True}),
 6            ('joe', {email:'joe@foo.org'}),
 7            'smith',
 8        ]
 9
10        # add users to TestCase instance.
11        self.create_users(user_list, self.__dict__)
12
13        # add users to global context.  make it easy to reference objects within test methods
14        # be careful that you do not corrupt context for other tests!
15        self.create_users(user_list, globals())

CREATE_STANDARD_USERS

Helper method that creates a superuser and an unauthorized user. They are added to the context under those names.

ViewTestMixin

ViewTestMixin contains a collection of assertions and other helper methods for testing django views. They are designed for iteration over common test cases.

ASSERT_200

assert_200(url, args, users, template=None, mime=None, tests=None, setup=False, data={}, method='get', follow=False)

Tests a view that executes successfully.

URLs used for requests are constructed from a format string urls and a tuple of args. The url is constructed by applying the args to the format string. Keeping these as separate arguments allows tests to manipulate the args to test other cases such as 404.

1def test_my_view(self):
2    url = '/my/url/%s/some/%s'
3    args = ('with', 'some')

users should be a list of User instances. Create each User and assign the correct permissions or state. Each user will be logged in and its permissions checked. django_test_tools expects all users to have a password of 'secret'

 1def test_example(self):
 2    # create some users and stick them in the local context
 3    self.create_users([
 4        ('superuser', {is_superuser:True})
 5        'admin_user'
 6        'other_user'
 7        ],locals())
 8
 9    # give them some perms
10    admin_user.grant('admin')
11    other_user.grant('other')
12
13    # execute test
14    self.assert_200(url, args, [superuser, admin_user, other_user])

By default, assert_200 will check if the response code is 200. It will also check mimetype against the mime kwarg, and template usage against the template arg. By default it will expect a mimetype of 'text/html; charset=utf-8' and no template.

Any http method can be used by specifying the the method kwarg. It should be one of the following strings: get, post, *delete.

HTTP Redirects will be followed if follow is set to True.

Additional test assertions can be run by passing in a function to the tests kwarg. Test functions receive both the User and response object from the request.

1def test_example(self):
2
3    def tests(user, response):
4        """ extra tests, this tests the content of the response """" 
5        self.assertEqual('hello world!', response.content)
6
7    # execute test
8    self.assert_200(url, args, users, tests=tests)
  • setup - call self.setup() before testing each user. This is needed when a test alters the state in such a way that the test can not be run again for another user.

ASSERT_401

assert_401(url, args, data={}, method='get'):

Tests that a url will redirect to the login url for an anonymous user.

  • url - format string for url
  • args - args to pass to format url with
  • users - list of users to check. Each user will be checked individually. It is expected that each user has their permissions set prior to being given to this method
  • method - which http method to use. may be get, post, or delete

ASSERT_403

assert_403(url, args, users, data={}, method='get')

Tests access to a url by unauthorized users.

  • url - format string for url
  • args - args to pass to format url with
  • users - list of users to check. Each user will be checked individually. It is expected that each user has their permissions set prior to being given to this method
  • method - which http method to use. may be get, post, or delete

ASSERT_404

assert_404(url, args, data=dict(), method='get')

Tests that invalid arguments in the url will result in 404 errors. This works by replacing each value in args with a nonsense value one at a time.

  • url - format string for url
  • args - args to pass to format url with
  • users - list of users to check. Each user will be checked individually. It is expected that each user has their permissions set prior to being given to this method
  • method - which http method to use. may be get, post, or delete

ASSERT_STANDARD_FAILS

assert_standard_fails(url, args, data=dict{}, method='get', login_required=True, authorized=True)

For secured views its common to always check for login required, unauthorized users, and 404 cases. assert_standard_fails checks all of these in a single method. Internally this just calls assert_401, assert_403, and assert_404

  • url - format string for url
  • args - args to pass to format url with
  • users - list of users to check. Each user will be checked individually. It is expected that each user has their permissions set prior to being given to this method
  • method - which http method to use. may be get, post, or delete
  • login_required - test for login required, defaults to True.
  • authorized - test for an unauthorized user being restricted, defaults to True.

ASSERT_VIEW_MISSING_FIELDS

assert_view_missing_fields(url, args, data, fields=None, template=None, mime=None, tests=None, method='post')

Tests fields that are required for a view. The validation is usually from a form but it may be a manual check in a view that results in an error condition. Each field in fields will be tried individually.

  • url - format string for url
  • args - args to pass to format url with
  • data - dictionary of data to be passed to the request
  • fields - list of field keys that are required
  • template - if given, template that responses should use
  • mime - if given, mime for response
  • tests - a function that executes additional tests on the responses from the client
  • method - which http method to use. may be get, post, or delete

ASSERT_VIEW_VALUES

assert_view_values(url, args, data, fields, template=None, mime=None, tests=None, method='post')

Tests fields that should raise an error for a specific type of invalid data is sent. This is used for blackbox testing form validation via the view it is used in.

  • url - format string for url
  • args - args to pass to format url with
  • data - dictionary of data to be passed to the request
  • fields - list of field keys that are required
  • template - if given, template that responses should use
  • mime - if given, mime for response
  • tests - a function that executes additional tests on the responses from the client
  • method - which http method to use. may be get, post, or delete
1

FormTestMixin

ASSERT_MISSING_FIELDS

assert_missing_fields(cls, data, fields=None)

Tests fields that should raise a required exception.

  • cls - the form class to test.
  • data - dictionary of valid data for the form.
  • fields - list of required field names, or none if all fields are required.

ASSERT_INVALID_VALUE

assert_invalid_value(cls, data, fields)

Tests field values that should result in a validation error.

  • cls - the form class to test.
  • data - dictionary of valid data for the form.
  • fields - list of required field names, or none if all fields are required.
1