-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_journal.py
228 lines (171 loc) · 5.9 KB
/
test_journal.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
# -*- coding: utf-8 -*-
from contextlib import closing
from pyramid import testing
import pytest
import datetime
import os
from cryptacular.bcrypt import BCRYPTPasswordManager
from journal import connect_db
from journal import DB_SCHEMA
from journal import INSERT_ENTRY
TEST_DSN = 'dbname=test_learning_journal user=jwarren'
INPUT_BTN = '<input type="submit" value="Share" name="Share"/>'
def init_db(settings):
with closing(connect_db(settings)) as db:
db.cursor().execute(DB_SCHEMA)
db.commit()
def clear_db(settings):
with closing(connect_db(settings)) as db:
db.cursor().execute("DROP TABLE entries")
db.commit()
def clear_entries(settings):
with closing(connect_db(settings)) as db:
db.cursor().execute("DELETE FROM entries")
db.commit()
def run_query(db, query, params=(), get_results=True):
cursor = db.cursor()
cursor.execute(query, params)
db.commit()
results = None
if get_results:
results = cursor.fetchall()
return results
def login_helper(username, password, app):
"""encapsulates app login for reuse in tests
Accept all status codes so that we can make assertions in tests
"""
login_data = {'username': username, 'password': password}
return app.post('/login', params=login_data, status='*')
@pytest.fixture(scope='session')
def db(request):
"""set up and tear down a database"""
settings = {'db': TEST_DSN}
init_db(settings)
def cleanup():
clear_db(settings)
request.addfinalizer(cleanup)
return settings
@pytest.yield_fixture(scope='function')
def req_context(db, request):
"""mock a request with a database attached"""
settings = db
req = testing.DummyRequest()
with closing(connect_db(settings)) as db:
req.db = db
req.exception = None
yield req
clear_entries(settings)
@pytest.fixture(scope='function')
def app(db):
from journal import main
from webtest import TestApp
os.environ['DATABASE_URL'] = TEST_DSN
app = main()
return TestApp(app)
@pytest.fixture(scope='function')
def auth_req(request):
manager = BCRYPTPasswordManager()
settings = {
'auth.username': 'admin',
'auth.password': manager.encode('secret'),
}
testing.setUp(settings=settings)
req = testing.DummyRequest()
def cleanup():
testing.tearDown()
request.addfinalizer(cleanup)
return req
def test_write_entry(req_context):
from journal import write_entry
fields = ('title', 'text')
expected = ('Test Title', 'Test Text')
req_context.params = dict(zip(fields, expected))
# assert no entries when we start
rows = run_query(req_context.db, "SELECT * FROM entries")
assert len(rows) == 0
result = write_entry(req_context)
# manually commit so we can see entry on query
req_context.db.commit()
rows = run_query(req_context.db, "SELECT title, text FROM entries")
assert len(rows) == 1
actual = rows[0]
for idx, val in enumerate(expected):
assert val == actual[idx]
def test_read_entries_empty(req_context):
from journal import read_entries
result = read_entries(req_context)
assert 'entries' in result
assert len(result['entries']) == 0
def test_read_entries(req_context):
now = datetime.datetime.utcnow()
expected = ('Test Title', 'Test Text', now)
run_query(req_context.db, INSERT_ENTRY, expected, False)
from journal import read_entries
result = read_entries(req_context)
assert 'entries' in result
assert len(result['entries']) == 1
for entry in result['entries']:
assert expected[0] == entry['title']
assert expected[1] == entry['text']
for key in 'id', 'created':
assert key in entry
def test_empty_listing(app):
response = app.get('/')
assert response.status_code == 200
actual = response.body
expected = 'No entries here so far'
assert expected in actual
def test_post_to_add_view(app):
entry_data = {
'title': 'Hello there',
'text': 'This is a post',
}
response = app.post('/add', params=entry_data, status='3*')
redirected = response.follow()
actual = redirected.body
for expected in entry_data.values():
assert expected in actual
def test_do_login_success(auth_req):
from journal import do_login
auth_req.params = {'username': 'admin', 'password': 'secret'}
assert do_login(auth_req)
def test_do_login_bad_pass(auth_req):
from journal import do_login
auth_req.params = {'username': 'admin', 'password': 'wrong'}
assert not do_login(auth_req)
def test_do_login_bad_user(auth_req):
from journal import do_login
auth_req.params = {'username': 'bad', 'password': 'secret'}
assert not do_login(auth_req)
def test_do_login_missing_params(auth_req):
from journal import do_login
for params in ({'username': 'admin'}, {'password': 'secret'}):
auth_req.params = params
with pytest.raises(ValueError):
do_login(auth_req)
def test_start_as_anonymouse(app):
response = app.get('/', status=200)
actual = response.body
assert INPUT_BTN not in actual
def test_login_success(app):
username, password = ('admin', 'secret')
redirect = login_helper(username, password, app)
assert redirect.status_code == 302
response = redirect.follow()
assert response.status_code == 200
actual = response.body
assert INPUT_BTN in actual
def test_login_fails(app):
username, password = ('admin', 'wrong')
response = login_helper(username, password, app)
assert response.status_code == 200
actual = response.body
assert "Login Failed" in actual
assert INPUT_BTN not in actual
def test_logout(app):
test_login_success(app)
redirect = app.get('/logout', status="3*")
response = redirect.follow()
assert response.status_code == 200
actual = response.body
assert INPUT_BTN not in actual