Repository navigation
Expand file tree
/
Copy pathtest_form.py
More file actions
354 lines (300 loc) · 11.8 KB
/
Copy pathtest_form.py
File metadata and controls
354 lines (300 loc) · 11.8 KB
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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
import setpath # noqa:F401, must come before 'import mechanicalsoup'
import mechanicalsoup
from utils import setup_mock_browser
import sys
import pytest
def test_submit_online(httpbin):
"""Complete and submit the pizza form at http://httpbin.org/forms/post """
browser = mechanicalsoup.Browser()
page = browser.get(httpbin + "/forms/post")
form = mechanicalsoup.Form(page.soup.form)
input_data = {"custname": "Philip J. Fry"}
form.input(input_data)
check_data = {"size": "large", "topping": ["cheese"]}
form.check(check_data)
check_data = {"size": "medium", "topping": "onion"}
form.check(check_data)
form.textarea({"comments": "warm"})
form.textarea({"comments": "actually, no, not warm"})
form.textarea({"comments": "freezer"})
response = browser.submit(form, page.url)
# helpfully the form submits to http://httpbin.org/post which simply
# returns the request headers in json format
json = response.json()
data = json["form"]
assert data["custname"] == "Philip J. Fry"
assert data["custtel"] == "" # web browser submits "" for input left blank
assert data["size"] == "medium"
assert data["topping"] == ["cheese", "onion"]
assert data["comments"] == "freezer"
def test_submit_set(httpbin):
"""Complete and submit the pizza form at http://httpbin.org/forms/post """
browser = mechanicalsoup.Browser()
page = browser.get(httpbin + "/forms/post")
form = mechanicalsoup.Form(page.soup.form)
form["custname"] = "Philip J. Fry"
form["size"] = "medium"
form["topping"] = ("cheese", "onion")
form["comments"] = "freezer"
response = browser.submit(form, page.url)
# helpfully the form submits to http://httpbin.org/post which simply
# returns the request headers in json format
json = response.json()
data = json["form"]
assert data["custname"] == "Philip J. Fry"
assert data["custtel"] == "" # web browser submits "" for input left blank
assert data["size"] == "medium"
assert data["topping"] == ["cheese", "onion"]
assert data["comments"] == "freezer"
@pytest.mark.parametrize("expected_post", [
pytest.param(
[
('comment', 'Testing preview page'),
('preview', 'Preview Page'),
('text', 'Setting some text!')
], id='preview'),
pytest.param(
[
('comment', 'Created new page'),
('save', 'Submit changes'),
('text', '= Heading =\n\nNew page here!\n')
], id='save'),
pytest.param(
[
('comment', 'Testing choosing cancel button'),
('cancel', 'Cancel'),
('text', '= Heading =\n\nNew page here!\n')
], id='cancel'),
])
def test_choose_submit(expected_post):
browser, url = setup_mock_browser(expected_post=expected_post)
browser.open(url)
form = browser.select_form('#choose-submit-form')
browser['text'] = expected_post[2][1]
browser['comment'] = expected_post[0][1]
form.choose_submit(expected_post[1][0])
res = browser.submit_selected()
assert(res.status_code == 200 and res.text == 'Success!')
choose_submit_fail_form = '''
<html>
<form id="choose-submit-form">
<input type="submit" name="test_submit" value="Test Submit" />
</form>
</html>
'''
@pytest.mark.parametrize("select_name", [
pytest.param({'name': 'does_not_exist', 'fails': True}, id='not found'),
pytest.param({'name': 'test_submit', 'fails': False}, id='found'),
])
def test_choose_submit_fail(select_name):
browser = mechanicalsoup.StatefulBrowser()
browser.open_fake_page(choose_submit_fail_form)
form = browser.select_form('#choose-submit-form')
if select_name['fails']:
with pytest.raises(mechanicalsoup.utils.LinkNotFoundError):
form.choose_submit(select_name['name'])
else:
form.choose_submit(select_name['name'])
choose_submit_multiple_match_form = '''
<html>
<form id="choose-submit-form">
<input type="submit" name="test_submit" value="First Submit" />
<input type="submit" name="test_submit" value="Second Submit" />
</form>
</html>
'''
def test_choose_submit_multiple_match():
browser = mechanicalsoup.StatefulBrowser()
browser.open_fake_page(choose_submit_multiple_match_form)
form = browser.select_form('#choose-submit-form')
with pytest.raises(mechanicalsoup.utils.LinkNotFoundError):
form.choose_submit('test_submit')
submit_form_noaction = '''
<html>
<body>
<form id="choose-submit-form">
<input type="text" name="text1" value="someValue1" />
<input type="text" name="text2" value="someValue2" />
<input type="submit" name="save" />
</form>
</body>
</html>
'''
def test_form_noaction():
browser, url = setup_mock_browser()
browser.open_fake_page(submit_form_noaction, url=url)
form = browser.select_form('#choose-submit-form')
form['text1'] = 'newText1'
res = browser.submit_selected()
assert(res.status_code == 200 and browser.get_url() == url)
submit_form_action = '''
<html>
<body>
<form id="choose-submit-form" action="mock://form.com">
<input type="text" name="text1" value="someValue1" />
<input type="text" name="text2" value="someValue2" />
<input type="submit" name="save" />
</form>
</body>
</html>
'''
def test_form_action():
browser, url = setup_mock_browser()
# for info about example.com see: https://tools.ietf.org/html/rfc2606
browser.open_fake_page(submit_form_action,
url="http://example.com/invalid/")
form = browser.select_form('#choose-submit-form')
form['text1'] = 'newText1'
res = browser.submit_selected()
assert(res.status_code == 200 and browser.get_url() == url)
set_select_form = '''
<html>
<form method="post" action="mock://form.com/post">
<select name="entree">
<option value="tofu" selected="selected">Tofu Stir Fry</option>
<option value="curry">Red Curry</option>
<option value="tempeh">Tempeh Tacos</option>
</select>
<input type="submit" value="Select" />
</form>
</html>
'''
@pytest.mark.parametrize("option", [
pytest.param({'result': [('entree', 'tofu')], 'default': True},
id='default'),
pytest.param({'result': [('entree', 'curry')], 'default': False},
id='selected'),
])
def test_set_select(option):
'''Test the branch of Form.set that finds "select" elements.'''
browser, url = setup_mock_browser(expected_post=option['result'],
text=set_select_form)
browser.open(url)
browser.select_form('form')
if not option['default']:
browser[option['result'][0][0]] = option['result'][0][1]
res = browser.submit_selected()
assert(res.status_code == 200 and res.text == 'Success!')
set_select_multiple_form = '''
<form method="post" action="mock://form.com/post">
<select name="instrument" multiple>
<option value="piano">Piano</option>
<option value="bass">Bass</option>
<option value="violin">Violin</option>
</select>
<input type="submit" value="Select Multiple" />
</form>
'''
@pytest.mark.parametrize("options", [
pytest.param('bass', id='select one (str)'),
pytest.param(('bass',), id='select one (tuple)'),
pytest.param(('piano', 'violin'), id='select two'),
])
def test_set_select_multiple(options):
"""Test a <select multiple> element."""
# When a browser submits multiple selections, the qsl looks like:
# name=option1&name=option2
if not isinstance(options, list) and not isinstance(options, tuple):
expected = (('instrument', options),)
else:
expected = (('instrument', option) for option in options)
browser, url = setup_mock_browser(expected_post=expected,
text=set_select_multiple_form)
browser.open(url)
form = browser.select_form('form')
form.set_select({'instrument': options})
res = browser.submit_selected()
assert(res.status_code == 200 and res.text == 'Success!')
def test_form_not_found():
browser = mechanicalsoup.StatefulBrowser()
browser.open_fake_page(page_with_various_fields)
form = browser.select_form('form')
with pytest.raises(mechanicalsoup.utils.LinkNotFoundError):
form.input({'foo': 'bar', 'nosuchname': 'nosuchval'})
with pytest.raises(mechanicalsoup.utils.LinkNotFoundError):
form.check({'foo': 'bar', 'nosuchname': 'nosuchval'})
with pytest.raises(mechanicalsoup.utils.LinkNotFoundError):
form.check({'entree': 'cheese'})
with pytest.raises(mechanicalsoup.utils.LinkNotFoundError):
form.check({'topping': 'tofu'})
with pytest.raises(mechanicalsoup.utils.LinkNotFoundError):
form.textarea({'bar': 'value', 'foo': 'nosuchval'})
with pytest.raises(mechanicalsoup.utils.LinkNotFoundError):
form.set_radio({'size': 'tiny'})
with pytest.raises(mechanicalsoup.utils.LinkNotFoundError):
form.set_select({'entree': ('no_multiple', 'no_multiple')})
page_with_radio = '''
<html>
<form method="post">
<input type=checkbox name="foo" value="bacon"> This is a checkbox
</form>
</html>
'''
def test_form_check_uncheck():
browser = mechanicalsoup.StatefulBrowser()
browser.open_fake_page(page_with_radio, url="http://example.com/invalid/")
form = browser.select_form('form')
assert "checked" not in form.form.find("input", {"name": "foo"}).attrs
form["foo"] = True
assert form.form.find("input", {"name": "foo"}).attrs["checked"] == ""
# Test explicit unchecking (skipping the call to Form.uncheck_all)
form.set_checkbox({"foo": False}, uncheck_other_boxes=False)
assert "checked" not in form.form.find("input", {"name": "foo"}).attrs
page_with_various_fields = '''
<html>
<form method="post">
<input name="foo">
<textarea name="bar">
</textarea>
<select name="entree">
<option value="tofu" selected="selected"> Tofu Stir Fry </option>
<option value="curry"> Red Curry</option>
<option value="tempeh">Tempeh Tacos </option>
</select>
<fieldset>
<legend> Pizza Toppings </legend>
<p><label> <input type=checkbox name="topping"
value="bacon"> Bacon </label></p>
<p><label> <input type=checkbox name="topping"
value="cheese" checked>Extra Cheese </label></p>
<p><label> <input type=checkbox name="topping"
value="onion" checked> Onion </label></p>
<p><label> <input type=checkbox name="topping"
value="mushroom"> Mushroom </label></p>
</fieldset>
<p><input name="size" type=radio value="small">Small</p>
<p><input name="size" type=radio value="medium">Medium</p>
<p><input name="size" type=radio value="large">Large</p>
<input type="submit" value="Select" />
</form>
</html>
'''
def test_form_print_summary(capsys):
browser = mechanicalsoup.StatefulBrowser()
browser.open_fake_page(page_with_various_fields,
url="http://example.com/invalid/")
browser.select_form("form")
browser.get_current_form().print_summary()
out, err = capsys.readouterr()
# Different versions of bs4 show either <input></input> or
# <input/>. Normalize before comparing.
out = out.replace('></input>', '/>')
assert out == """<input name="foo"/>
<textarea name="bar"></textarea>
<select name="entree">
<option selected="selected" value="tofu">Tofu Stir Fry</option>
<option value="curry">Red Curry</option>
<option value="tempeh">Tempeh Tacos</option>
</select>
<input name="topping" type="checkbox" value="bacon"/>
<input checked="" name="topping" type="checkbox" value="cheese"/>
<input checked="" name="topping" type="checkbox" value="onion"/>
<input name="topping" type="checkbox" value="mushroom"/>
<input name="size" type="radio" value="small"/>
<input name="size" type="radio" value="medium"/>
<input name="size" type="radio" value="large"/>
<input type="submit" value="Select"/>
"""
assert err == ""
if __name__ == '__main__':
pytest.main(sys.argv)