Skip to content

Commit d84bc0a

Browse files
committed
Add test for forms
1 parent 0317526 commit d84bc0a

File tree

1 file changed

+97
-0
lines changed

1 file changed

+97
-0
lines changed

blog/tests/test_forms.py

Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
from django.test import TestCase
2+
from django.core import mail
3+
4+
from blog.forms import CommentForm, EmailPostForm
5+
from .blog_factories import PostFactory
6+
7+
8+
class BlogFormTests(TestCase):
9+
"""
10+
Test class for blog Forms
11+
"""
12+
13+
def test_comment_form_with_invalid_data(self):
14+
"""
15+
Test comment form with invalid data
16+
"""
17+
form = CommentForm({
18+
'name': 'John Doe',
19+
'email': 'Invalid Email'
20+
})
21+
self.assertFalse(form.is_valid())
22+
23+
def test_comment_form_with_valid_data(self):
24+
"""
25+
Test comment form with valid data
26+
"""
27+
form = CommentForm({
28+
'name': 'John Doe',
29+
'email': 'johndoe@gmail.com',
30+
'body': 'Some Comment'
31+
})
32+
self.assertTrue(form.is_valid())
33+
34+
def test_comment_saved_into_database(self):
35+
"""
36+
Test valid comment is saving into database
37+
"""
38+
form = CommentForm({
39+
'name': 'John Doe',
40+
'email': 'johndoe@gmail.com',
41+
'body': 'Some Comment'
42+
})
43+
comment = form.save(commit=False)
44+
comment.post = PostFactory()
45+
self.assertEqual(comment.name, 'John Doe')
46+
self.assertEqual(comment.email, 'johndoe@gmail.com')
47+
self.assertEqual(comment.body, 'Some Comment')
48+
49+
def test_email_post_form_with_invaild_data(self):
50+
"""
51+
Test email post form with invalid data
52+
"""
53+
form = EmailPostForm({
54+
'name': 'John Doe',
55+
'email': 'invalidemail',
56+
'to': 'invalidemail'
57+
})
58+
self.assertFalse(form.is_valid())
59+
60+
def test_email_post_form_with_vaild_data(self):
61+
"""
62+
Test email post form with valid data
63+
"""
64+
form = EmailPostForm({
65+
'name': 'John Doe',
66+
'email': 'jdoe@gmail.com',
67+
'to': 'missdoe@gmail.com',
68+
'comments': 'some comments'
69+
})
70+
self.assertTrue(form.is_valid())
71+
72+
def test_send_email_with_email_post_form(self):
73+
"""
74+
Test sharing post with EmailPostForm
75+
"""
76+
post = PostFactory.create()
77+
78+
form = EmailPostForm({
79+
'name': 'John Doe',
80+
'email': 'jdoe@gmail.com',
81+
'to': 'missdoe@gmail.com',
82+
'comments': 'some comments'
83+
})
84+
85+
post_url = post.get_absolute_url()
86+
87+
if form.is_valid():
88+
cd = form.cleaned_data
89+
subject = f"{cd['name']} recommends you read {post.title}"
90+
message = f"Read {post.title} at {post_url}\n\n" \
91+
f"{cd['name']}\'s comments: {cd['comments']}"
92+
mail.send_mail(subject, message, 'admin@myblog.com', [cd['to']])
93+
94+
self.assertEqual(len(mail.outbox), 1)
95+
self.assertEqual(mail.outbox[0].subject, subject)
96+
else:
97+
self.assertTrue(form.is_valid)

0 commit comments

Comments
 (0)