7👍
The client.get
method takes a follow
argument which allows it to follow redirects:
response = self.client.get('/contact/', follow=True)
25👍
None of the above worked for me (Django1.9, Python3.4). Found this solution here:
from django.test import TestCase
from http.cookies import SimpleCookie
class TestViewWithCookies(TestCase):
def test_votes(self):
self.client.cookies = SimpleCookie({'name': 'bla'})
response = self.client.get('/vote/2')
self.assertEqual(response.status_code, 200)
- Override save_model on Django InlineModelAdmin
- How is pip install using git different than just cloning a repository?
- Django 3.1: StreamingHttpResponse with an async generator
- Django-autocomplete-light simple usage
11👍
While the accepted answer is the right approach for this problem, I just want to point out that you can set cookies directly (i.e. approach number (i) as you call it), but not via the test client. Instead you need to use a RequestFactory
to construct a request which you can set the cookie on, then pass that directly to the view in question.
So instead of:
response = self.client.get('/contact/')
you do:
request = RequestFactory().get('/contact/')
request.COOKIES['thing'] = 'whatever'
response = contact_view(request)
where contact_view
is the view serving /contact/
.
- Docker Django 404 for web static files, but fine for admin static files
- TypeError: create_superuser() missing 1 required positional argument: 'profile_picture'
- Adding forgot-password feature to Django admin site
- How do I get the django HttpRequest from a django rest framework Request?
- Installing django 1.5(development version) in virtualenv
10👍
You can set cookies for test client by calling load on cookies
attribute which is SimpleCookie object.
from django.core import signing
self.client.cookies.load({
'example': '123',
'signed_example': signing.get_cookie_signer('signed_example').sign('123')
})
Django’s test client is stateful – will persist cookies between tests and will ignore expire dates. For removal, you need to manually remove cookie or create a new client. – See docs
— For Python 3 and Django 2+
3👍
This is an old question but maybe this is handy for someone:
from http.cookies import SimpleCookie
from django.test import TestCase, Client
class CookieClientTests(TestCase):
def test_cookie(self):
cookies = SimpleCookie()
cookies["cookie_key"] = "something"
client = Client(HTTP_COOKIE=cookies.output(header='', sep='; '))
resp = client.get("/")
self.assertEqual(200, resp.status_code)
- TypeError: create_superuser() missing 1 required positional argument: 'profile_picture'
- Django template tag: How to send next_page in {url auth_logout}?
- Django. Error message for login form
- Django update on queryset to change ID of ForeignKey
- Uwsgi http is ambiguous