Skip to content

Commit d305c3d

Browse files
Chapter 15: Unit tests with the Flask test client (15b)
1 parent 01c4f97 commit d305c3d

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed

config.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ class TestingConfig(Config):
3232
TESTING = True
3333
SQLALCHEMY_DATABASE_URI = os.environ.get('TEST_DATABASE_URL') or \
3434
'sqlite:///' + os.path.join(basedir, 'data-test.sqlite')
35+
WTF_CSRF_ENABLED = False
3536

3637

3738
class ProductionConfig(Config):

tests/test_client.py

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
import re
2+
import unittest
3+
from flask import url_for
4+
from app import create_app, db
5+
from app.models import User, Role
6+
7+
class FlaskClientTestCase(unittest.TestCase):
8+
def setUp(self):
9+
self.app = create_app('testing')
10+
self.app_context = self.app.app_context()
11+
self.app_context.push()
12+
db.create_all()
13+
Role.insert_roles()
14+
self.client = self.app.test_client(use_cookies=True)
15+
16+
def tearDown(self):
17+
db.session.remove()
18+
db.drop_all()
19+
self.app_context.pop()
20+
21+
def test_home_page(self):
22+
response = self.client.get(url_for('main.index'))
23+
self.assertTrue(b'Stranger' in response.data)
24+
25+
def test_register_and_login(self):
26+
# register a new account
27+
response = self.client.post(url_for('auth.register'), data={
28+
'email': 'john@example.com',
29+
'username': 'john',
30+
'password': 'cat',
31+
'password2': 'cat'
32+
})
33+
self.assertTrue(response.status_code == 302)
34+
35+
# login with the new account
36+
response = self.client.post(url_for('auth.login'), data={
37+
'email': 'john@example.com',
38+
'password': 'cat'
39+
}, follow_redirects=True)
40+
self.assertTrue(re.search(b'Hello,\s+john!', response.data))
41+
self.assertTrue(
42+
b'You have not confirmed your account yet' in response.data)
43+
44+
# send a confirmation token
45+
user = User.query.filter_by(email='john@example.com').first()
46+
token = user.generate_confirmation_token()
47+
response = self.client.get(url_for('auth.confirm', token=token),
48+
follow_redirects=True)
49+
self.assertTrue(
50+
b'You have confirmed your account' in response.data)
51+
52+
# log out
53+
response = self.client.get(url_for('auth.logout'), follow_redirects=True)
54+
self.assertTrue(b'You have been logged out' in response.data)

0 commit comments

Comments
 (0)