Rietveld Code Review Tool
Help | Bug tracker | Discussion group | Source code

Side by Side Diff: sitescripts/formmail/test/test_formmail2.py

Issue 29374647: Issue 4814 - Adds csv log to formmail2 (Closed) Base URL: https://hg.adblockplus.org/sitescripts
Patch Set: address comments, now encodes user input to utf8 Created Feb. 28, 2017, 4 p.m.
Left:
Right:
Use n/p to move between diff chunks; N/P to move between comments.
Jump to:
View unified diff | Download patch
OLDNEW
1 # This file is part of the Adblock Plus web scripts, 1 # This file is part of the Adblock Plus web scripts,
2 # Copyright (C) 2006-2016 Eyeo GmbH 2 # Copyright (C) 2006-2016 Eyeo GmbH
3 # 3 #
4 # Adblock Plus is free software: you can redistribute it and/or modify 4 # Adblock Plus is free software: you can redistribute it and/or modify
5 # it under the terms of the GNU General Public License version 3 as 5 # it under the terms of the GNU General Public License version 3 as
6 # published by the Free Software Foundation. 6 # published by the Free Software Foundation.
7 # 7 #
8 # Adblock Plus is distributed in the hope that it will be useful, 8 # Adblock Plus is distributed in the hope that it will be useful,
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of 9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # GNU General Public License for more details. 11 # GNU General Public License for more details.
12 # 12 #
13 # You should have received a copy of the GNU General Public License 13 # You should have received a copy of the GNU General Public License
14 # along with Adblock Plus. If not, see <http://www.gnu.org/licenses/>. 14 # along with Adblock Plus. If not, see <http://www.gnu.org/licenses/>.
15
16 import datetime
17 from csv import DictReader
15 from urllib import urlencode 18 from urllib import urlencode
16 from urllib2 import urlopen, HTTPError 19 from urllib2 import urlopen, HTTPError
17 20
18 import pytest 21 import pytest
19 from wsgi_intercept import (urllib_intercept, add_wsgi_intercept, 22 from wsgi_intercept import (urllib_intercept, add_wsgi_intercept,
20 remove_wsgi_intercept) 23 remove_wsgi_intercept)
21 24
22 from sitescripts.formmail.web import formmail2 25 from sitescripts.formmail.web import formmail2
23 26
24 27
25 @pytest.fixture() 28 @pytest.fixture
26 def form_config(): 29 def form_config():
27 return formmail2.conf_parse(formmail2.get_config_items())['test'] 30 return formmail2.conf_parse(formmail2.get_config_items())['test']
28 31
29 32
30 @pytest.fixture() 33 @pytest.fixture
31 def form_handler(form_config): 34 def form_handler(form_config, log_path):
35 # override configured path to log file with tmpdir path
36 form_config['csv_log'].value = log_path
32 return formmail2.make_handler('test', form_config)[1] 37 return formmail2.make_handler('test', form_config)[1]
33 38
34 39
40 @pytest.fixture
41 def log_path(form_config, tmpdir):
42 return str(tmpdir.join('test.csv_log'))
43
44
35 # We make this a fixture instead of a constant so we can modify it in each 45 # We make this a fixture instead of a constant so we can modify it in each
36 # test as needed without affecting other tests. 46 # test as needed without affecting other tests.
37 @pytest.fixture 47 @pytest.fixture
38 def form_data(): 48 def form_data():
39 return { 49 return {
40 'email': 'john_doe@gmail.com', 50 'email': 'john_doe@gmail.com',
41 'mandatory': 'john_doe@gmail.com', 51 'mandatory': 'john_doe@gmail.com',
42 'non_mandatory_message': 'Once upon a time\nthere lived a king.', 52 'non_mandatory_message': 'Once upon a time\nthere lived a king.',
43 'non_mandatory_email': 'test@test.com' 53 'non_mandatory_email': 'test@test.com',
44 } 54 }
45 55
46 56
47 @pytest.fixture() 57 @pytest.fixture
48 def response_for(form_handler): 58 def utf8_form_data():
59 return {
60 'email': 'john_doe@gmail.com',
61 'mandatory': 'john_doe@gmail.com',
62 'non_mandatory_message': '\xc3\xb6',
Vasily Kuznetsov 2017/02/28 18:38:49 Perhaps we could make this by just taking `form_da
Jon Sonesen 2017/03/07 12:11:23 Yes, I agree
63 'non_mandatory_email': 'test@test.com',
64 }
65
66
67 @pytest.fixture
68 def response_for(form_handler, log_path):
49 host, port = 'test.local', 80 69 host, port = 'test.local', 80
50 urllib_intercept.install_opener() 70 urllib_intercept.install_opener()
51 add_wsgi_intercept(host, port, lambda: form_handler) 71 add_wsgi_intercept(host, port, lambda: form_handler)
52 url = 'http://{}:{}'.format(host, port) 72 url = 'http://{}:{}'.format(host, port)
53 73
54 def response_for(data): 74 def response_for(data):
55 if data is None: 75 if data is None:
56 response = urlopen(url) 76 response = urlopen(url)
57 else: 77 else:
58 response = urlopen(url, urlencode(data)) 78 response = urlopen(url, urlencode(data))
(...skipping 11 matching lines...) Expand all
70 def test_success(response_for, form_data, mocker): 90 def test_success(response_for, form_data, mocker):
71 sm_mock = mocker.patch('sitescripts.formmail.web.formmail2.sendMail') 91 sm_mock = mocker.patch('sitescripts.formmail.web.formmail2.sendMail')
72 assert response_for(form_data) == (200, '') 92 assert response_for(form_data) == (200, '')
73 assert sm_mock.call_count == 1 93 assert sm_mock.call_count == 1
74 params = sm_mock.call_args[0][1]['fields'] 94 params = sm_mock.call_args[0][1]['fields']
75 assert set(params.keys()) == set(form_data.keys()) 95 assert set(params.keys()) == set(form_data.keys())
76 for key, value in form_data.items(): 96 for key, value in form_data.items():
77 assert params[key] == value 97 assert params[key] == value
78 98
79 99
100 def test_utf8_success(response_for, utf8_form_data, mocker):
101 sm_mock = mocker.patch('sitescripts.formmail.web.formmail2.sendMail')
102 assert response_for(utf8_form_data) == (200, '')
103 assert sm_mock.call_count == 1
104 params = sm_mock.call_args[0][1]['fields']
105 assert set(params.keys()) == set(utf8_form_data.keys())
106 for key, value in utf8_form_data.items():
107 assert params[key] == value
108
109
80 def test_non_mandatory_no_msg(response_for, form_data, mocker): 110 def test_non_mandatory_no_msg(response_for, form_data, mocker):
81 mocker.patch('sitescripts.formmail.web.formmail2.sendMail') 111 mocker.patch('sitescripts.formmail.web.formmail2.sendMail')
82 form_data['non_mandatory'] = '' 112 form_data['non_mandatory'] = ''
83 assert response_for(form_data) == (200, '') 113 assert response_for(form_data) == (200, '')
84 114
85 115
86 def test_invalid_email_cstm_msg(response_for, form_data, mocker, form_config): 116 def test_invalid_email_cstm_msg(response_for, form_data, mocker, form_config):
87 mocker.patch('sitescripts.formmail.web.formmail2.sendMail') 117 mocker.patch('sitescripts.formmail.web.formmail2.sendMail')
88 form_data['email'] = 'bademail' 118 form_data['email'] = 'bademail'
89 with pytest.raises(HTTPError) as error: 119 with pytest.raises(HTTPError) as error:
(...skipping 11 matching lines...) Expand all
101 del form_data['non_mandatory_email'] 131 del form_data['non_mandatory_email']
102 assert response_for(form_data) == (200, '') 132 assert response_for(form_data) == (200, '')
103 133
104 134
105 def test_mandatory_fail_dflt_msg(response_for, form_data, mocker): 135 def test_mandatory_fail_dflt_msg(response_for, form_data, mocker):
106 mocker.patch('sitescripts.formmail.web.formmail2.sendMail') 136 mocker.patch('sitescripts.formmail.web.formmail2.sendMail')
107 del form_data['mandatory'] 137 del form_data['mandatory']
108 with pytest.raises(HTTPError) as error: 138 with pytest.raises(HTTPError) as error:
109 response_for(form_data) 139 response_for(form_data)
110 assert error.value.read() == 'No mandatory entered' 140 assert error.value.read() == 'No mandatory entered'
141
142
143 def test_collect_with_tmpl(log_path, form_data):
144 form_data['time'] = 'test'
145 formmail2.collect_formdata(form_data, log_path)
146 with open(log_path) as csvfile:
147 assert DictReader(csvfile).next() == form_data
148
149
150 def test_collect_no_tmpl(log_path, form_data, form_config):
151 del(form_config['template'])
152 form_data['time'] = 'test'
153 formmail2.collect_formdata(form_data, log_path)
154 with open(log_path) as csvfile:
155 assert DictReader(csvfile).next() == form_data
156
157
158 def test_fieldnames(log_path, form_data):
159 form_data['time'] = str(datetime.datetime.now())
160 formmail2.collect_formdata(form_data, log_path)
161 with open(log_path) as csvfile:
162 for field in DictReader(csvfile).fieldnames:
163 assert field in tuple(form_data.keys())
164
165
166 def test_field_err(form_config, form_data, log_path):
167 """
168 Submits a form that does not have the dame fields as previous submissions
169 that have the same form name, asserts that proper message is returned and
170 the row was properly written
171 """
172 formmail2.collect_formdata(form_data, log_path)
173 del(form_config['fields']['email'])
174 del(form_data['email'])
175 try:
176 formmail2.collect_formdata(form_data, log_path)
177 except Exception as e:
178 assert e.message == ('Field names have changed, error log '
179 'written to {}_error').format(log_path)
180
181 with open(log_path+'_error') as error_log:
182 assert DictReader(error_log).next() == form_data
183
184
185 def test_append_field_err(form_config, form_data, log_path):
186 """
187 Submits two identical forms that do not match the previous fields
188 found in the log file, triggering two rows to be added to the error
189 log and asserting the proper message is returned and that the rows
190 were written as expected
191 """
192 formmail2.collect_formdata(form_data, log_path)
193 del(form_config['fields']['email'])
194 del(form_data['email'])
195 try:
196 formmail2.collect_formdata(form_data, log_path)
197 except Exception:
198 pass
199 try:
200 formmail2.collect_formdata(form_data, log_path)
201 except Exception as e:
202 assert e.message == ('Field names have changed, error log'
203 ' appended to {}_error').format(log_path)
204
205 with open(log_path+'_error') as error_log:
206 reader = DictReader(error_log)
207 # two identical rows should be in the error log
208 assert reader.next() == form_data
209 assert reader.next() == form_data
210
211
212 def test_append_log(form_data, log_path):
213 """
214 collect data twice, altering a field in the second call
215 assert that the 2nd row is equal to the resulting form data
216 """
217 form_data['time'] = str(datetime.datetime.now())
218 formmail2.collect_formdata(form_data, log_path)
219 form_data['email'] = 'test@foo.com'
220 formmail2.collect_formdata(form_data, log_path)
221 with open(log_path) as csvfile:
222 reader = DictReader(csvfile, fieldnames=form_data.keys())
223 # header
224 reader.next()
225 row1 = reader.next()
226 row2 = reader.next()
227
228 assert row2['email'] == form_data['email']
229 assert row2['email'] != row1['email']
OLDNEW

Powered by Google App Engine
This is Rietveld