|
| 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