Testing EMail sending in Django » History » Version 2
Alex V Koval, 04/30/2014 08:04 PM
1 | 1 | Alex V Koval | h1. Testing EMail sending in Django |
---|---|---|---|
2 | |||
3 | <pre> |
||
4 | <code class="python"> |
||
5 | class TestOnboardingEmails(TestCase): |
||
6 | MSG1 = 'Congratulations! You have now set your first '\ |
||
7 | 'assignment' |
||
8 | MSG2 = 'You have been using product for a week now' |
||
9 | |||
10 | def setUp(self): |
||
11 | self.teacher = factories.TeacherFactory.create() |
||
12 | self.teacher.email = 'test@test.yacapaca.com' |
||
13 | self.teacher.save() |
||
14 | self.student = factories.StudentFactory.create() |
||
15 | self.studentset = factories.StudentSetFactory.create(owner=self.teacher) |
||
16 | self.studentset.join_student(self.student) |
||
17 | self.studentset.join_teacher(self.teacher) |
||
18 | self.quick = factories.QuickFactory.create() |
||
19 | |||
20 | self.original_backend = settings.EMAIL_BACKEND |
||
21 | settings.EMAIL_BACKEND = 'django.core.mail.backends.locmem.EmailBackend' |
||
22 | |||
23 | def tearDown(self): |
||
24 | settings.EMAIL_BACKEND = self.original_backend |
||
25 | |||
26 | |||
27 | def test_new_assignment(self): |
||
28 | aset = AssignmentSet.create(teacher=self.teacher, |
||
29 | assign_date=datetime.now(), |
||
30 | studentset=self.studentset, |
||
31 | students_list=[self.student], |
||
32 | content_list=[{'obj': self.quick, |
||
33 | 'attempt_max':1}]) |
||
34 | cmd = process_events.Command() |
||
35 | cmd.handle(no_celery=True, debug=False, name=None, date=None, |
||
36 | quiet=False) |
||
37 | self.assertTrue(len(mail.outbox)==1) |
||
38 | self.assertTrue(self.MSG1 in |
||
39 | mail.outbox[0].message().as_string()) |
||
40 | self.assertTrue(self.MSG2 not in |
||
41 | mail.outbox[0].message().as_string()) |
||
42 | |||
43 | after_1_week_plus = datetime.now() + relativedelta(days=8) |
||
44 | |||
45 | cmd.handle(no_celery=True, debug=False, name=None, |
||
46 | date=after_1_week_plus.strftime(DATE_FORMAT), |
||
47 | quiet=False) |
||
48 | self.assertTrue(len(mail.outbox)==2) |
||
49 | self.assertTrue(self.MSG1 not in |
||
50 | mail.outbox[1].message().as_string()) |
||
51 | self.assertTrue(self.MSG2 in |
||
52 | mail.outbox[1].message().as_string()) |
||
53 | |||
54 | |||
55 | if __name__ == '__main__': |
||
56 | unittest.main() |
||
57 | </code></pre> |
||
58 | 2 | Alex V Koval | |
59 | |||
60 | The important lines in setUp and tearDown: |
||
61 | <pre> |
||
62 | <code class="python"> |
||
63 | def setUp(self): |
||
64 | self.original_backend = settings.EMAIL_BACKEND |
||
65 | settings.EMAIL_BACKEND = 'django.core.mail.backends.locmem.EmailBackend' |
||
66 | |||
67 | def tearDown(self): |
||
68 | settings.EMAIL_BACKEND = self.original_backend |
||
69 | </code></pre> |