django-test-plus


Namedjango-test-plus JSON
Version 2.2.3 PyPI version JSON
download
home_pagehttps://github.com/revsys/django-test-plus/
Summary"django-test-plus provides useful additions to Django's default TestCase"
upload_time2023-07-11 11:43:48
maintainer
docs_urlNone
authorFrank Wiles
requires_python>=3.6
license
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage
            # django-test-plus

Useful additions to Django's default TestCase from [REVSYS](https://www.revsys.com/)

[![pypi](https://img.shields.io/pypi/v/django-test-plus.svg)](https://pypi.org/project/django-test-plus/)
[![build matrix demo](https://github.com/revsys/django-test-plus/actions/workflows/actions.yml/badge.svg)](https://github.com/revsys/django-test-plus/actions/workflows/actions.yml)

## Rationale

Let's face it, writing tests isn't always fun. Part of the reason for
that is all of the boilerplate you end up writing. django-test-plus is
an attempt to cut down on some of that when writing Django tests. We
guarantee it will increase the time before you get carpal tunnel by at
least 3 weeks!

If you would like to get started testing your Django apps or improve how your
team is testing we offer [TestStart](https://www.revsys.com/teststart/)
to help your team dramatically improve your productivity.

## Support

Supports: Python 3.6, 3.7, 3.8, 3.9, 3.10, and 3.11.

Supports Django Versions: 2.0, 2.1, 2.2, 3.0, 3.1, 3.2, 4.0, 4.1, and 4.2.

## Documentation

Full documentation is available at http://django-test-plus.readthedocs.org

## Installation

```shell
$ pip install django-test-plus
```

## Usage

To use django-test-plus, have your tests inherit from test_plus.test.TestCase rather than the normal django.test.TestCase::

```python
from test_plus.test import TestCase

class MyViewTests(TestCase):
    ...
```

This is sufficient to get things rolling, but you are encouraged to
create *your own* sub-classes for your projects. This will allow you
to add your own project-specific helper methods.

For example, if you have a django project named 'myproject', you might
create the following in `myproject/test.py`:

```python
from test_plus.test import TestCase as PlusTestCase

class TestCase(PlusTestCase):
    pass
```

And then in your tests use:

```python
from myproject.test import TestCase

class MyViewTests(TestCase):
    ...
```

This import, which is similar to the way you would import Django's TestCase,
is also valid:

```python
from test_plus import TestCase
```

## pytest Usage

You can get a TestCase like object as a pytest fixture now by asking for `tp`. All of the methods below would then work in pytest functions. For
example:

```python
def test_url_reverse(tp):
    expected_url = '/api/'
    reversed_url = tp.reverse('api')
    assert expected_url == reversed_url
```

The `tp_api` fixture will provide a `TestCase` that uses django-rest-framework's `APIClient()`:

```python
def test_url_reverse(tp_api):
    response = tp_api.client.post("myapi", format="json")
    assert response.status_code == 200
```

## Methods

### `reverse(url_name, *args, **kwargs)`

When testing views you often find yourself needing to reverse the URL's name. With django-test-plus there is no need for the `from django.core.urlresolvers import reverse` boilerplate. Instead, use:

```python
def test_something(self):
    url = self.reverse('my-url-name')
    slug_url = self.reverse('name-takes-a-slug', slug='my-slug')
    pk_url = self.reverse('name-takes-a-pk', pk=12)
```

As you can see our reverse also passes along any args or kwargs you need
to pass in.

## `get(url_name, follow=True, *args, **kwargs)`

Another thing you do often is HTTP get urls. Our `get()` method
assumes you are passing in a named URL with any args or kwargs necessary
to reverse the url_name.
If needed, place kwargs for `TestClient.get()` in an 'extra' dictionary.:

```python
def test_get_named_url(self):
    response = self.get('my-url-name')
    # Get XML data via AJAX request
    xml_response = self.get(
        'my-url-name',
        extra={'HTTP_X_REQUESTED_WITH': 'XMLHttpRequest'})
```

When using this get method two other things happen for you: we store the
last response in `self.last_response` and the response's Context in `self.context`.

So instead of:

```python
def test_default_django(self):
    response = self.client.get(reverse('my-url-name'))
    self.assertTrue('foo' in response.context)
    self.assertEqual(response.context['foo'], 12)
```

You can write:

```python
def test_testplus_get(self):
    self.get('my-url-name')
    self.assertInContext('foo')
    self.assertEqual(self.context['foo'], 12)
```

It's also smart about already reversed URLs, so you can be lazy and do:

```python
def test_testplus_get(self):
    url = self.reverse('my-url-name')
    self.get(url)
    self.response_200()
```

If you need to pass query string parameters to your url name, you can do so like this. Assuming the name 'search' maps to '/search/' then:

```python
def test_testplus_get_query(self):
    self.get('search', data={'query': 'testing'})
```

Would GET `/search/?query=testing`.

## `post(url_name, data, follow=True, *args, **kwargs)`

Our `post()` method takes a named URL, an optional dictionary of data you wish
to post and any args or kwargs necessary to reverse the url_name.
If needed, place kwargs for `TestClient.post()` in an 'extra' dictionary.:

```python
def test_post_named_url(self):
    response = self.post('my-url-name', data={'coolness-factor': 11.0},
                         extra={'HTTP_X_REQUESTED_WITH': 'XMLHttpRequest'})
```

*NOTE* Along with the frequently used get and post, we support all of the HTTP verbs such as put, patch, head, trace, options, and delete in the same fashion.

## `get_context(key)`

Often you need to get things out of the template context:

```python
def test_context_data(self):
    self.get('my-view-with-some-context')
    slug = self.get_context('slug')
```

## `assertInContext(key)`

You can ensure a specific key exists in the last response's context by
using:

```python
def test_in_context(self):
    self.get('my-view-with-some-context')
    self.assertInContext('some-key')
```

## `assertContext(key, value)`

We can get context values and ensure they exist, but we can also test
equality while we're at it. This asserts that key == value:

```python
def test_in_context(self):
    self.get('my-view-with-some-context')
    self.assertContext('some-key', 'expected value')
```

## `assert_http_###_<status_name>(response, msg=None)` - status code checking

Another test you often need to do is check that a response has a certain
HTTP status code. With Django's default TestCase you would write:

```python
from django.core.urlresolvers import reverse

def test_status(self):
    response = self.client.get(reverse('my-url-name'))
    self.assertEqual(response.status_code, 200)
```

With django-test-plus you can shorten that to be:

```python
def test_better_status(self):
    response = self.get('my-url-name')
    self.assert_http_200_ok(response)
```

Django-test-plus provides a majority of the status codes assertions for you. The status assertions
can be found in their own [mixin](https://github.com/revsys/django-test-plus/blob/main/test_plus/status_codes.py)
and should be searchable if you're using an IDE like pycharm. It should be noted that in previous
versions, django-test-plus had assertion methods in the pattern of `response_###()`, which are still
available but have since been deprecated. See below for a list of those methods.

Each of the assertion methods takes an optional Django test client `response` and a string `msg` argument
that, if specified, is used as the error message when a failure occurs. The methods,
`assert_http_301_moved_permanently` and `assert_http_302_found` also take an optional `url` argument that
if passed, will check to make sure the `response.url` matches.

If it's available, the `assert_http_###_<status_name>` methods will use the last response. So you
can do:

```python
def test_status(self):
    self.get('my-url-name')
    self.assert_http_200_ok()
```

Which is a bit shorter.

The `response_###()` methods that are deprecated, but still available for use, include:

- `response_200()`
- `response_201()`
- `response_204()`
- `response_301()`
- `response_302()`
- `response_400()`
- `response_401()`
- `response_403()`
- `response_404()`
- `response_405()`
- `response_409()`
- `response_410()`

All of which take an optional Django test client response and a str msg argument that, if specified, is used as the error message when a failure occurs. Just like the `assert_http_###_<status_name>()` methods, these methods will use the last response if it's available.

## `get_check_200(url_name, *args, **kwargs)`

GETing and checking views return status 200 is a common test. This method makes it more convenient::

```python
def test_even_better_status(self):
    response = self.get_check_200('my-url-name')
```

## make_user(username='testuser', password='password', perms=None)

When testing out views you often need to create various users to ensure
all of your logic is safe and sound. To make this process easier, this
method will create a user for you:

```python
def test_user_stuff(self)
    user1 = self.make_user('u1')
    user2 = self.make_user('u2')
```

If creating a User in your project is more complicated, say for example
you removed the `username` field from the default Django Auth model,
you can provide a [Factory
Boy](https://factoryboy.readthedocs.org/en/latest/) factory to create
it or override this method on your own sub-class.

To use a Factory Boy factory, create your class like this::

```python
from test_plus.test import TestCase
from .factories import UserFactory


class MySpecialTest(TestCase):
    user_factory = UserFactory

    def test_special_creation(self):
        user1 = self.make_user('u1')
```

**NOTE:** Users created by this method will have their password
set to the string 'password' by default, in order to ease testing.
If you need a specific password, override the `password` parameter.

You can also pass in user permissions by passing in a string of
'`<app_name>.<perm name>`' or '`<app_name>.*`'.  For example:

```python
user2 = self.make_user(perms=['myapp.create_widget', 'otherapp.*'])
```

## `print_form_errors(response_or_form=None)`

When debugging a failing test for a view with a form, this method helps you
quickly look at any form errors.

Example usage:

```python
class MyFormTest(TestCase):

    self.post('my-url-name', data={})
    self.print_form_errors()

    # or

    resp = self.post('my-url-name', data={})
    self.print_form_errors(resp)

    # or

    form = MyForm(data={})
    self.print_form_errors(form)
```

## Authentication Helpers

### `assertLoginRequired(url_name, *args, **kwargs)`

This method helps you test that a given named URL requires authorization:

```python
def test_auth(self):
    self.assertLoginRequired('my-restricted-url')
    self.assertLoginRequired('my-restricted-object', pk=12)
    self.assertLoginRequired('my-restricted-object', slug='something')
```

### `login()` context

Along with ensuring a view requires login and creating users, the next
thing you end up doing is logging in as various users to test your
restriction logic:

```python
def test_restrictions(self):
    user1 = self.make_user('u1')
    user2 = self.make_user('u2')

    self.assertLoginRequired('my-protected-view')

    with self.login(username=user1.username, password='password'):
        response = self.get('my-protected-view')
        # Test user1 sees what they should be seeing

    with self.login(username=user2.username, password='password'):
        response = self.get('my-protected-view')
        # Test user2 see what they should be seeing
```

Since we're likely creating our users using `make_user()` from above,
the login context assumes the password is 'password' unless specified
otherwise. Therefore you you can do:

```python
def test_restrictions(self):
    user1 = self.make_user('u1')

    with self.login(username=user1.username):
        response = self.get('my-protected-view')
```

We can also derive the username if we're using `make_user()` so we can
shorten that up even further like this:

```python
def test_restrictions(self):
    user1 = self.make_user('u1')

    with self.login(user1):
        response = self.get('my-protected-view')
```

## Ensuring low query counts

### `assertNumQueriesLessThan(number)` - context

Django provides
[`assertNumQueries`](https://docs.djangoproject.com/en/1.8/topics/testing/tools/#django.test.TransactionTestCase.assertNumQueries)
which is great when your code generates a specific number of
queries. However, if this number varies due to the nature of your data, with
this method you can still test to ensure the code doesn't start producing a ton
more queries than you expect:

```python
def test_something_out(self):

    with self.assertNumQueriesLessThan(7):
        self.get('some-view-with-6-queries')
```

### `assertGoodView(url_name, *args, **kwargs)`

This method does a few things for you. It:

- Retrieves the name URL
- Ensures the view does not generate more than 50 queries
- Ensures the response has status code 200
- Returns the response

Often a wide, sweeping test like this is better than no test at all. You
can use it like this:

```python
def test_better_than_nothing(self):
    response = self.assertGoodView('my-url-name')
```

## Testing DRF views

To take advantage of the convenience of DRF's test client, you can create a subclass of `TestCase` and set the `client_class` property:

```python
from test_plus import TestCase
from rest_framework.test import APIClient


class APITestCase(TestCase):
    client_class = APIClient
```

For convenience, `test_plus` ships with `APITestCase`, which does just that:

```python
from test_plus import APITestCase


class MyAPITestCase(APITestCase):

    def test_post(self):
        data = {'testing': {'prop': 'value'}}
        self.post('view-json', data=data, extra={'format': 'json'})
        self.assert_http_200_ok()
```

Note that using `APITestCase` requires Django >= 1.8 and having installed `django-rest-framework`.

## Testing class-based "generic" views

The TestCase methods `get()` and `post()` work for both function-based
and class-based views. However, in doing so they invoke Django's
URL resolution, middleware, template processing, and decorator systems.
For integration testing this is desirable, as you want to ensure your
URLs resolve properly, view permissions are enforced, etc.
For unit testing this is costly because all these Django request/response
systems are invoked in addition to your method, and they typically do not
affect the end result.

Class-based views (derived from Django's `generic.models.View` class)
contain methods and mixins which makes granular unit testing (more) feasible.
Quite often your usage of a generic view class comprises an override
of an existing method. Invoking the entire view and the Django request/response
stack is a waste of time when you really want to call the overridden
method directly and test the result.

CBVTestCase to the rescue!

As with TestCase above, have your tests inherit
from test_plus.test.CBVTestCase rather than TestCase like so:

```python
from test_plus.test import CBVTestCase

class MyViewTests(CBVTestCase):
```

## Methods

### `get_instance(cls, initkwargs=None, request=None, *args, **kwargs)`

This core method simplifies the instantiation of your class, giving you
a way to invoke class methods directly.

Returns an instance of `cls`, initialized with `initkwargs`.
Sets `request`, `args`, and `kwargs` attributes on the class instance.
`args` and `kwargs` are the same values you would pass to `reverse()`.

Sample usage:

```python
from django.views import generic
from test_plus.test import CBVTestCase

class MyClass(generic.DetailView)

    def get_context_data(self, **kwargs):
        kwargs['answer'] = 42
        return kwargs

class MyTests(CBVTestCase):

    def test_context_data(self):
        my_view = self.get_instance(MyClass, {'object': some_object})
        context = my_view.get_context_data()
        self.assertEqual(context['answer'], 42)
```

### `get(cls, initkwargs=None, *args, **kwargs)`

Invokes `cls.get()` and returns the response, rendering template if possible.
Builds on the `CBVTestCase.get_instance()` foundation.

All test_plus.test.TestCase methods are valid, so the following works:

```python
response = self.get(MyClass)
self.assertContext('my_key', expected_value)
```

All test_plus TestCase side-effects are honored and all test_plus
TestCase assertion methods work with `CBVTestCase.get()`.

**NOTE:** This method bypasses Django's middleware, and therefore context
variables created by middleware are not available. If this affects your
template/context testing, you should use TestCase instead of CBVTestCase.

### `post(cls, data=None, initkwargs=None, *args, **kwargs)`

Invokes `cls.post()` and returns the response, rendering template if possible.
Builds on the `CBVTestCase.get_instance()` foundation.

Example:

```python
response = self.post(MyClass, data={'search_term': 'revsys'})
self.response_200(response)
self.assertContext('company_name', 'RevSys')
```

All test_plus TestCase side-effects are honored and all test_plus
TestCase assertion methods work with `CBVTestCase.post()`.

**NOTE:** This method bypasses Django's middleware, and therefore context
variables created by middleware are not available. If this affects your
template/context testing you should use TestCase instead of CBVTestCase.

### `get_check_200(cls, initkwargs=None, *args, **kwargs)`

Works just like `TestCase.get_check_200()`.
Caller must provide a view class instead of a URL name or path parameter.

All test_plus TestCase side-effects are honored and all test_plus
TestCase assertion methods work with `CBVTestCase.post()`.

### `assertGoodView(cls, initkwargs=None, *args, **kwargs)`

Works just like `TestCase.assertGoodView()`.
Caller must provide a view class instead of a URL name or path parameter.

All test_plus TestCase side-effects are honored and all test_plus
TestCase assertion methods work with `CBVTestCase.post()`.

## Development

To work on django-test-plus itself, clone this repository and run the following command:

```shell
$ pip install -e .
$ pip install -e .[test]
```

## To run all tests:

```shell
$ nox
```

**NOTE**: You will also need to ensure that the `test_project` directory, located
at the root of this repo, is in your virtualenv's path.

## Keep in touch!

If you have a question about this project, please open a GitHub issue. If you love us and want to keep track of our goings-on, here's where you can find us online:

<a href="https://revsys.com?utm_medium=github&utm_source=django-test-plus"><img src="https://pbs.twimg.com/profile_images/915928618840285185/sUdRGIn1_400x400.jpg" height="50" /></a>
<a href="https://twitter.com/revsys"><img src="https://cdn1.iconfinder.com/data/icons/new_twitter_icon/256/bird_twitter_new_simple.png" height="43" /></a>
<a href="https://www.facebook.com/revsysllc/"><img src="https://cdn3.iconfinder.com/data/icons/picons-social/57/06-facebook-512.png" height="50" /></a>

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/revsys/django-test-plus/",
    "name": "django-test-plus",
    "maintainer": "",
    "docs_url": null,
    "requires_python": ">=3.6",
    "maintainer_email": "",
    "keywords": "",
    "author": "Frank Wiles",
    "author_email": "frank@revsys.com",
    "download_url": "https://files.pythonhosted.org/packages/85/c7/23219e9d9dcdbb9298f13db3fe1a36dcfc7f49ea165a4cd3b7a2c11b0abe/django-test-plus-2.2.3.tar.gz",
    "platform": null,
    "description": "# django-test-plus\n\nUseful additions to Django's default TestCase from [REVSYS](https://www.revsys.com/)\n\n[![pypi](https://img.shields.io/pypi/v/django-test-plus.svg)](https://pypi.org/project/django-test-plus/)\n[![build matrix demo](https://github.com/revsys/django-test-plus/actions/workflows/actions.yml/badge.svg)](https://github.com/revsys/django-test-plus/actions/workflows/actions.yml)\n\n## Rationale\n\nLet's face it, writing tests isn't always fun. Part of the reason for\nthat is all of the boilerplate you end up writing. django-test-plus is\nan attempt to cut down on some of that when writing Django tests. We\nguarantee it will increase the time before you get carpal tunnel by at\nleast 3 weeks!\n\nIf you would like to get started testing your Django apps or improve how your\nteam is testing we offer [TestStart](https://www.revsys.com/teststart/)\nto help your team dramatically improve your productivity.\n\n## Support\n\nSupports: Python 3.6, 3.7, 3.8, 3.9, 3.10, and 3.11.\n\nSupports Django Versions: 2.0, 2.1, 2.2, 3.0, 3.1, 3.2, 4.0, 4.1, and 4.2.\n\n## Documentation\n\nFull documentation is available at http://django-test-plus.readthedocs.org\n\n## Installation\n\n```shell\n$ pip install django-test-plus\n```\n\n## Usage\n\nTo use django-test-plus, have your tests inherit from test_plus.test.TestCase rather than the normal django.test.TestCase::\n\n```python\nfrom test_plus.test import TestCase\n\nclass MyViewTests(TestCase):\n    ...\n```\n\nThis is sufficient to get things rolling, but you are encouraged to\ncreate *your own* sub-classes for your projects. This will allow you\nto add your own project-specific helper methods.\n\nFor example, if you have a django project named 'myproject', you might\ncreate the following in `myproject/test.py`:\n\n```python\nfrom test_plus.test import TestCase as PlusTestCase\n\nclass TestCase(PlusTestCase):\n    pass\n```\n\nAnd then in your tests use:\n\n```python\nfrom myproject.test import TestCase\n\nclass MyViewTests(TestCase):\n    ...\n```\n\nThis import, which is similar to the way you would import Django's TestCase,\nis also valid:\n\n```python\nfrom test_plus import TestCase\n```\n\n## pytest Usage\n\nYou can get a TestCase like object as a pytest fixture now by asking for `tp`. All of the methods below would then work in pytest functions. For\nexample:\n\n```python\ndef test_url_reverse(tp):\n    expected_url = '/api/'\n    reversed_url = tp.reverse('api')\n    assert expected_url == reversed_url\n```\n\nThe `tp_api` fixture will provide a `TestCase` that uses django-rest-framework's `APIClient()`:\n\n```python\ndef test_url_reverse(tp_api):\n    response = tp_api.client.post(\"myapi\", format=\"json\")\n    assert response.status_code == 200\n```\n\n## Methods\n\n### `reverse(url_name, *args, **kwargs)`\n\nWhen testing views you often find yourself needing to reverse the URL's name. With django-test-plus there is no need for the `from django.core.urlresolvers import reverse` boilerplate. Instead, use:\n\n```python\ndef test_something(self):\n    url = self.reverse('my-url-name')\n    slug_url = self.reverse('name-takes-a-slug', slug='my-slug')\n    pk_url = self.reverse('name-takes-a-pk', pk=12)\n```\n\nAs you can see our reverse also passes along any args or kwargs you need\nto pass in.\n\n## `get(url_name, follow=True, *args, **kwargs)`\n\nAnother thing you do often is HTTP get urls. Our `get()` method\nassumes you are passing in a named URL with any args or kwargs necessary\nto reverse the url_name.\nIf needed, place kwargs for `TestClient.get()` in an 'extra' dictionary.:\n\n```python\ndef test_get_named_url(self):\n    response = self.get('my-url-name')\n    # Get XML data via AJAX request\n    xml_response = self.get(\n        'my-url-name',\n        extra={'HTTP_X_REQUESTED_WITH': 'XMLHttpRequest'})\n```\n\nWhen using this get method two other things happen for you: we store the\nlast response in `self.last_response` and the response's Context in `self.context`.\n\nSo instead of:\n\n```python\ndef test_default_django(self):\n    response = self.client.get(reverse('my-url-name'))\n    self.assertTrue('foo' in response.context)\n    self.assertEqual(response.context['foo'], 12)\n```\n\nYou can write:\n\n```python\ndef test_testplus_get(self):\n    self.get('my-url-name')\n    self.assertInContext('foo')\n    self.assertEqual(self.context['foo'], 12)\n```\n\nIt's also smart about already reversed URLs, so you can be lazy and do:\n\n```python\ndef test_testplus_get(self):\n    url = self.reverse('my-url-name')\n    self.get(url)\n    self.response_200()\n```\n\nIf you need to pass query string parameters to your url name, you can do so like this. Assuming the name 'search' maps to '/search/' then:\n\n```python\ndef test_testplus_get_query(self):\n    self.get('search', data={'query': 'testing'})\n```\n\nWould GET `/search/?query=testing`.\n\n## `post(url_name, data, follow=True, *args, **kwargs)`\n\nOur `post()` method takes a named URL, an optional dictionary of data you wish\nto post and any args or kwargs necessary to reverse the url_name.\nIf needed, place kwargs for `TestClient.post()` in an 'extra' dictionary.:\n\n```python\ndef test_post_named_url(self):\n    response = self.post('my-url-name', data={'coolness-factor': 11.0},\n                         extra={'HTTP_X_REQUESTED_WITH': 'XMLHttpRequest'})\n```\n\n*NOTE* Along with the frequently used get and post, we support all of the HTTP verbs such as put, patch, head, trace, options, and delete in the same fashion.\n\n## `get_context(key)`\n\nOften you need to get things out of the template context:\n\n```python\ndef test_context_data(self):\n    self.get('my-view-with-some-context')\n    slug = self.get_context('slug')\n```\n\n## `assertInContext(key)`\n\nYou can ensure a specific key exists in the last response's context by\nusing:\n\n```python\ndef test_in_context(self):\n    self.get('my-view-with-some-context')\n    self.assertInContext('some-key')\n```\n\n## `assertContext(key, value)`\n\nWe can get context values and ensure they exist, but we can also test\nequality while we're at it. This asserts that key == value:\n\n```python\ndef test_in_context(self):\n    self.get('my-view-with-some-context')\n    self.assertContext('some-key', 'expected value')\n```\n\n## `assert_http_###_<status_name>(response, msg=None)` - status code checking\n\nAnother test you often need to do is check that a response has a certain\nHTTP status code. With Django's default TestCase you would write:\n\n```python\nfrom django.core.urlresolvers import reverse\n\ndef test_status(self):\n    response = self.client.get(reverse('my-url-name'))\n    self.assertEqual(response.status_code, 200)\n```\n\nWith django-test-plus you can shorten that to be:\n\n```python\ndef test_better_status(self):\n    response = self.get('my-url-name')\n    self.assert_http_200_ok(response)\n```\n\nDjango-test-plus provides a majority of the status codes assertions for you. The status assertions\ncan be found in their own [mixin](https://github.com/revsys/django-test-plus/blob/main/test_plus/status_codes.py)\nand should be searchable if you're using an IDE like pycharm. It should be noted that in previous\nversions, django-test-plus had assertion methods in the pattern of `response_###()`, which are still\navailable but have since been deprecated. See below for a list of those methods.\n\nEach of the assertion methods takes an optional Django test client `response` and a string `msg` argument\nthat, if specified, is used as the error message when a failure occurs. The methods,\n`assert_http_301_moved_permanently` and `assert_http_302_found` also take an optional `url` argument that\nif passed, will check to make sure the `response.url` matches.\n\nIf it's available, the `assert_http_###_<status_name>` methods will use the last response. So you\ncan do:\n\n```python\ndef test_status(self):\n    self.get('my-url-name')\n    self.assert_http_200_ok()\n```\n\nWhich is a bit shorter.\n\nThe `response_###()` methods that are deprecated, but still available for use, include:\n\n- `response_200()`\n- `response_201()`\n- `response_204()`\n- `response_301()`\n- `response_302()`\n- `response_400()`\n- `response_401()`\n- `response_403()`\n- `response_404()`\n- `response_405()`\n- `response_409()`\n- `response_410()`\n\nAll of which take an optional Django test client response and a str msg argument that, if specified, is used as the error message when a failure occurs. Just like the `assert_http_###_<status_name>()` methods, these methods will use the last response if it's available.\n\n## `get_check_200(url_name, *args, **kwargs)`\n\nGETing and checking views return status 200 is a common test. This method makes it more convenient::\n\n```python\ndef test_even_better_status(self):\n    response = self.get_check_200('my-url-name')\n```\n\n## make_user(username='testuser', password='password', perms=None)\n\nWhen testing out views you often need to create various users to ensure\nall of your logic is safe and sound. To make this process easier, this\nmethod will create a user for you:\n\n```python\ndef test_user_stuff(self)\n    user1 = self.make_user('u1')\n    user2 = self.make_user('u2')\n```\n\nIf creating a User in your project is more complicated, say for example\nyou removed the `username` field from the default Django Auth model,\nyou can provide a [Factory\nBoy](https://factoryboy.readthedocs.org/en/latest/) factory to create\nit or override this method on your own sub-class.\n\nTo use a Factory Boy factory, create your class like this::\n\n```python\nfrom test_plus.test import TestCase\nfrom .factories import UserFactory\n\n\nclass MySpecialTest(TestCase):\n    user_factory = UserFactory\n\n    def test_special_creation(self):\n        user1 = self.make_user('u1')\n```\n\n**NOTE:** Users created by this method will have their password\nset to the string 'password' by default, in order to ease testing.\nIf you need a specific password, override the `password` parameter.\n\nYou can also pass in user permissions by passing in a string of\n'`<app_name>.<perm name>`' or '`<app_name>.*`'.  For example:\n\n```python\nuser2 = self.make_user(perms=['myapp.create_widget', 'otherapp.*'])\n```\n\n## `print_form_errors(response_or_form=None)`\n\nWhen debugging a failing test for a view with a form, this method helps you\nquickly look at any form errors.\n\nExample usage:\n\n```python\nclass MyFormTest(TestCase):\n\n    self.post('my-url-name', data={})\n    self.print_form_errors()\n\n    # or\n\n    resp = self.post('my-url-name', data={})\n    self.print_form_errors(resp)\n\n    # or\n\n    form = MyForm(data={})\n    self.print_form_errors(form)\n```\n\n## Authentication Helpers\n\n### `assertLoginRequired(url_name, *args, **kwargs)`\n\nThis method helps you test that a given named URL requires authorization:\n\n```python\ndef test_auth(self):\n    self.assertLoginRequired('my-restricted-url')\n    self.assertLoginRequired('my-restricted-object', pk=12)\n    self.assertLoginRequired('my-restricted-object', slug='something')\n```\n\n### `login()` context\n\nAlong with ensuring a view requires login and creating users, the next\nthing you end up doing is logging in as various users to test your\nrestriction logic:\n\n```python\ndef test_restrictions(self):\n    user1 = self.make_user('u1')\n    user2 = self.make_user('u2')\n\n    self.assertLoginRequired('my-protected-view')\n\n    with self.login(username=user1.username, password='password'):\n        response = self.get('my-protected-view')\n        # Test user1 sees what they should be seeing\n\n    with self.login(username=user2.username, password='password'):\n        response = self.get('my-protected-view')\n        # Test user2 see what they should be seeing\n```\n\nSince we're likely creating our users using `make_user()` from above,\nthe login context assumes the password is 'password' unless specified\notherwise. Therefore you you can do:\n\n```python\ndef test_restrictions(self):\n    user1 = self.make_user('u1')\n\n    with self.login(username=user1.username):\n        response = self.get('my-protected-view')\n```\n\nWe can also derive the username if we're using `make_user()` so we can\nshorten that up even further like this:\n\n```python\ndef test_restrictions(self):\n    user1 = self.make_user('u1')\n\n    with self.login(user1):\n        response = self.get('my-protected-view')\n```\n\n## Ensuring low query counts\n\n### `assertNumQueriesLessThan(number)` - context\n\nDjango provides\n[`assertNumQueries`](https://docs.djangoproject.com/en/1.8/topics/testing/tools/#django.test.TransactionTestCase.assertNumQueries)\nwhich is great when your code generates a specific number of\nqueries. However, if this number varies due to the nature of your data, with\nthis method you can still test to ensure the code doesn't start producing a ton\nmore queries than you expect:\n\n```python\ndef test_something_out(self):\n\n    with self.assertNumQueriesLessThan(7):\n        self.get('some-view-with-6-queries')\n```\n\n### `assertGoodView(url_name, *args, **kwargs)`\n\nThis method does a few things for you. It:\n\n- Retrieves the name URL\n- Ensures the view does not generate more than 50 queries\n- Ensures the response has status code 200\n- Returns the response\n\nOften a wide, sweeping test like this is better than no test at all. You\ncan use it like this:\n\n```python\ndef test_better_than_nothing(self):\n    response = self.assertGoodView('my-url-name')\n```\n\n## Testing DRF views\n\nTo take advantage of the convenience of DRF's test client, you can create a subclass of `TestCase` and set the `client_class` property:\n\n```python\nfrom test_plus import TestCase\nfrom rest_framework.test import APIClient\n\n\nclass APITestCase(TestCase):\n    client_class = APIClient\n```\n\nFor convenience, `test_plus` ships with `APITestCase`, which does just that:\n\n```python\nfrom test_plus import APITestCase\n\n\nclass MyAPITestCase(APITestCase):\n\n    def test_post(self):\n        data = {'testing': {'prop': 'value'}}\n        self.post('view-json', data=data, extra={'format': 'json'})\n        self.assert_http_200_ok()\n```\n\nNote that using `APITestCase` requires Django >= 1.8 and having installed `django-rest-framework`.\n\n## Testing class-based \"generic\" views\n\nThe TestCase methods `get()` and `post()` work for both function-based\nand class-based views. However, in doing so they invoke Django's\nURL resolution, middleware, template processing, and decorator systems.\nFor integration testing this is desirable, as you want to ensure your\nURLs resolve properly, view permissions are enforced, etc.\nFor unit testing this is costly because all these Django request/response\nsystems are invoked in addition to your method, and they typically do not\naffect the end result.\n\nClass-based views (derived from Django's `generic.models.View` class)\ncontain methods and mixins which makes granular unit testing (more) feasible.\nQuite often your usage of a generic view class comprises an override\nof an existing method. Invoking the entire view and the Django request/response\nstack is a waste of time when you really want to call the overridden\nmethod directly and test the result.\n\nCBVTestCase to the rescue!\n\nAs with TestCase above, have your tests inherit\nfrom test_plus.test.CBVTestCase rather than TestCase like so:\n\n```python\nfrom test_plus.test import CBVTestCase\n\nclass MyViewTests(CBVTestCase):\n```\n\n## Methods\n\n### `get_instance(cls, initkwargs=None, request=None, *args, **kwargs)`\n\nThis core method simplifies the instantiation of your class, giving you\na way to invoke class methods directly.\n\nReturns an instance of `cls`, initialized with `initkwargs`.\nSets `request`, `args`, and `kwargs` attributes on the class instance.\n`args` and `kwargs` are the same values you would pass to `reverse()`.\n\nSample usage:\n\n```python\nfrom django.views import generic\nfrom test_plus.test import CBVTestCase\n\nclass MyClass(generic.DetailView)\n\n    def get_context_data(self, **kwargs):\n        kwargs['answer'] = 42\n        return kwargs\n\nclass MyTests(CBVTestCase):\n\n    def test_context_data(self):\n        my_view = self.get_instance(MyClass, {'object': some_object})\n        context = my_view.get_context_data()\n        self.assertEqual(context['answer'], 42)\n```\n\n### `get(cls, initkwargs=None, *args, **kwargs)`\n\nInvokes `cls.get()` and returns the response, rendering template if possible.\nBuilds on the `CBVTestCase.get_instance()` foundation.\n\nAll test_plus.test.TestCase methods are valid, so the following works:\n\n```python\nresponse = self.get(MyClass)\nself.assertContext('my_key', expected_value)\n```\n\nAll test_plus TestCase side-effects are honored and all test_plus\nTestCase assertion methods work with `CBVTestCase.get()`.\n\n**NOTE:** This method bypasses Django's middleware, and therefore context\nvariables created by middleware are not available. If this affects your\ntemplate/context testing, you should use TestCase instead of CBVTestCase.\n\n### `post(cls, data=None, initkwargs=None, *args, **kwargs)`\n\nInvokes `cls.post()` and returns the response, rendering template if possible.\nBuilds on the `CBVTestCase.get_instance()` foundation.\n\nExample:\n\n```python\nresponse = self.post(MyClass, data={'search_term': 'revsys'})\nself.response_200(response)\nself.assertContext('company_name', 'RevSys')\n```\n\nAll test_plus TestCase side-effects are honored and all test_plus\nTestCase assertion methods work with `CBVTestCase.post()`.\n\n**NOTE:** This method bypasses Django's middleware, and therefore context\nvariables created by middleware are not available. If this affects your\ntemplate/context testing you should use TestCase instead of CBVTestCase.\n\n### `get_check_200(cls, initkwargs=None, *args, **kwargs)`\n\nWorks just like `TestCase.get_check_200()`.\nCaller must provide a view class instead of a URL name or path parameter.\n\nAll test_plus TestCase side-effects are honored and all test_plus\nTestCase assertion methods work with `CBVTestCase.post()`.\n\n### `assertGoodView(cls, initkwargs=None, *args, **kwargs)`\n\nWorks just like `TestCase.assertGoodView()`.\nCaller must provide a view class instead of a URL name or path parameter.\n\nAll test_plus TestCase side-effects are honored and all test_plus\nTestCase assertion methods work with `CBVTestCase.post()`.\n\n## Development\n\nTo work on django-test-plus itself, clone this repository and run the following command:\n\n```shell\n$ pip install -e .\n$ pip install -e .[test]\n```\n\n## To run all tests:\n\n```shell\n$ nox\n```\n\n**NOTE**: You will also need to ensure that the `test_project` directory, located\nat the root of this repo, is in your virtualenv's path.\n\n## Keep in touch!\n\nIf you have a question about this project, please open a GitHub issue. If you love us and want to keep track of our goings-on, here's where you can find us online:\n\n<a href=\"https://revsys.com?utm_medium=github&utm_source=django-test-plus\"><img src=\"https://pbs.twimg.com/profile_images/915928618840285185/sUdRGIn1_400x400.jpg\" height=\"50\" /></a>\n<a href=\"https://twitter.com/revsys\"><img src=\"https://cdn1.iconfinder.com/data/icons/new_twitter_icon/256/bird_twitter_new_simple.png\" height=\"43\" /></a>\n<a href=\"https://www.facebook.com/revsysllc/\"><img src=\"https://cdn3.iconfinder.com/data/icons/picons-social/57/06-facebook-512.png\" height=\"50\" /></a>\n",
    "bugtrack_url": null,
    "license": "",
    "summary": "\"django-test-plus provides useful additions to Django's default TestCase\"",
    "version": "2.2.3",
    "project_urls": {
        "Homepage": "https://github.com/revsys/django-test-plus/"
    },
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "41485626b3b75e1b845a84ee2deac230a78b8bbe6f01db3415882237259e8fc7",
                "md5": "d23ec56bf6d861a381d48aadc0fea857",
                "sha256": "5a8e26c9bf8eab092012c2cce9c605e0dba5a15879771feeb992c424504a18fe"
            },
            "downloads": -1,
            "filename": "django_test_plus-2.2.3-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "d23ec56bf6d861a381d48aadc0fea857",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.6",
            "size": 17684,
            "upload_time": "2023-07-11T11:43:46",
            "upload_time_iso_8601": "2023-07-11T11:43:46.852123Z",
            "url": "https://files.pythonhosted.org/packages/41/48/5626b3b75e1b845a84ee2deac230a78b8bbe6f01db3415882237259e8fc7/django_test_plus-2.2.3-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "85c723219e9d9dcdbb9298f13db3fe1a36dcfc7f49ea165a4cd3b7a2c11b0abe",
                "md5": "580765e70678db20d6072c3ca6972fd9",
                "sha256": "72e1ca5dcaaf4ad73c9c796ad6e0dc165db39f706c3ad822074d961f72eed743"
            },
            "downloads": -1,
            "filename": "django-test-plus-2.2.3.tar.gz",
            "has_sig": false,
            "md5_digest": "580765e70678db20d6072c3ca6972fd9",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.6",
            "size": 19103,
            "upload_time": "2023-07-11T11:43:48",
            "upload_time_iso_8601": "2023-07-11T11:43:48.725649Z",
            "url": "https://files.pythonhosted.org/packages/85/c7/23219e9d9dcdbb9298f13db3fe1a36dcfc7f49ea165a4cd3b7a2c11b0abe/django-test-plus-2.2.3.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-07-11 11:43:48",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "revsys",
    "github_project": "django-test-plus",
    "travis_ci": false,
    "coveralls": true,
    "github_actions": true,
    "lcname": "django-test-plus"
}
        
Elapsed time: 0.08722s