forked from mjhea0/flaskr-tdd
-
Notifications
You must be signed in to change notification settings - Fork 140
/
Copy pathapp-test.py
87 lines (68 loc) · 2.8 KB
/
app-test.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import unittest
import os
import json
from app import app, db
TEST_DB = 'test.db'
class BasicTestCase(unittest.TestCase):
def test_index(self):
"""initial test. ensure flask was set up correctly"""
tester = app.test_client(self)
response = tester.get('/', content_type='html/text')
self.assertEqual(response.status_code, 200)
def test_database(self):
"""initial test. ensure that the database exists"""
tester = os.path.exists("flaskr.db")
self.assertTrue(tester)
class FlaskrTestCase(unittest.TestCase):
def setUp(self):
"""Set up a blank temp database before each test"""
basedir = os.path.abspath(os.path.dirname(__file__))
app.config['TESTING'] = True
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + \
os.path.join(basedir, TEST_DB)
self.app = app.test_client()
db.create_all()
def tearDown(self):
"""Destroy blank temp database after each test"""
db.drop_all()
def login(self, username, password):
"""Login helper function"""
return self.app.post('/login', data=dict(
username=username,
password=password
), follow_redirects=True)
def logout(self):
"""Logout helper function"""
return self.app.get('/logout', follow_redirects=True)
# assert functions
def test_empty_db(self):
"""Ensure database is blank"""
rv = self.app.get('/')
self.assertIn(b'No entries yet. Add some!', rv.data)
def test_login_logout(self):
"""Test login and logout using helper functions"""
rv = self.login(app.config['USERNAME'], app.config['PASSWORD'])
self.assertIn(b'You were logged in', rv.data)
rv = self.logout()
self.assertIn(b'You were logged out', rv.data)
rv = self.login(app.config['USERNAME'] + 'x', app.config['PASSWORD'])
self.assertIn(b'Invalid username', rv.data)
rv = self.login(app.config['USERNAME'], app.config['PASSWORD'] + 'x')
self.assertIn(b'Invalid password', rv.data)
def test_messages(self):
"""Ensure that user can post messages"""
self.login(app.config['USERNAME'], app.config['PASSWORD'])
rv = self.app.post('/add', data=dict(
title='<Hello>',
text='<strong>HTML</strong> allowed here'
), follow_redirects=True)
self.assertNotIn(b'No entries here so far', rv.data)
self.assertIn(b'<Hello>', rv.data)
self.assertIn(b'<strong>HTML</strong> allowed here', rv.data)
def test_delete_message(self):
"""Ensure the messages are being deleted"""
rv = self.app.get('/delete/1')
data = json.loads(rv.data)
self.assertEqual(data['status'], 1)
if __name__ == '__main__':
unittest.main()