====== Django Testing ====== class YourTestClass(TestCase): @classmethod def setUpTestData(cls): print("setUpTestData: Run once to set up non-modified data for all class methods.") pass def setUp(self): print("setUp: Run once for every test method to setup clean data.") pass def test_false_is_false(self): print("Method: test_false_is_false.") self.assertFalse(False) def test_false_is_true(self): print("Method: test_false_is_true.") self.assertTrue(False) def test_one_plus_one_equals_two(self): print("Method: test_one_plus_one_equals_two.") self.assertEqual(1 + 1, 2) ====== RequestFactory ====== from django.test import TestCase, RequestFactory from django.contrib.auth.models import AnonymousUser from ..views import signup ... self.req_factory = RequestFactory() ... req = self.req_factory.get('/users/signup') req.user = AnonymousUser() # Test my_view() as if it were deployed at /customer/details response = my_view(request) # Use this syntax for class-based views. response = MyView.as_view()(request) self.assertEqual(response.status_code, 200) ====== self.client ====== res = self.client.get('/users/signup') self.client.force_login(User.objects.get_or_create(username='testuser')[0]) self.client.login(... ====== Mail ====== from django.core import mail def test_send_mail_on_signup(self): """ When a user signs up should receive an email """ email = 'test@test.com' self.client.post('/users/signup', { 'username': 'usertest1', 'email': email, 'password1': 'prueb4PRUEB4', 'password2': 'prueb4PRUEB4' }) self.assertEqual(len(mail.outbox), 1) self.assertEqual(mail.outbox[0].to[0], email) ====== Articles ====== ===== N+1 Queries ===== Lets imagine you are creating a view for returning all the courses with some of their authors data. If you run a code like this: queryset = Course.objects.all() courses = [] for course in queryset: courses.append({"title": course.title, "author": course.author.name}) This is executing one query (for bringing all courses) and N queries more (one for each author). There is the library [[https://github.com/jmcarp/nplusone|nplusone]] to detect this. * {{ :wiki2:python:django:automating_performance_testing_in_django.zip |}}