Best Python code snippet using lettuce_webdriver_python
test_form.py
Source:test_form.py  
1import setpath  # noqa:F401, must come before 'import mechanicalsoup'2import mechanicalsoup3from utils import setup_mock_browser4import sys5import pytest6def test_submit_online(httpbin):7    """Complete and submit the pizza form at http://httpbin.org/forms/post """8    browser = mechanicalsoup.Browser()9    page = browser.get(httpbin + "/forms/post")10    form = mechanicalsoup.Form(page.soup.form)11    input_data = {"custname": "Philip J. Fry"}12    form.input(input_data)13    check_data = {"size": "large", "topping": ["cheese"]}14    form.check(check_data)15    check_data = {"size": "medium", "topping": "onion"}16    form.check(check_data)17    form.textarea({"comments": "warm"})18    form.textarea({"comments": "actually, no, not warm"})19    form.textarea({"comments": "freezer"})20    response = browser.submit(form, page.url)21    # helpfully the form submits to http://httpbin.org/post which simply22    # returns the request headers in json format23    json = response.json()24    data = json["form"]25    assert data["custname"] == "Philip J. Fry"26    assert data["custtel"] == ""  # web browser submits "" for input left blank27    assert data["size"] == "medium"28    assert data["topping"] == ["cheese", "onion"]29    assert data["comments"] == "freezer"30def test_submit_set(httpbin):31    """Complete and submit the pizza form at http://httpbin.org/forms/post """32    browser = mechanicalsoup.Browser()33    page = browser.get(httpbin + "/forms/post")34    form = mechanicalsoup.Form(page.soup.form)35    form["custname"] = "Philip J. Fry"36    form["size"] = "medium"37    form["topping"] = ("cheese", "onion")38    form["comments"] = "freezer"39    response = browser.submit(form, page.url)40    # helpfully the form submits to http://httpbin.org/post which simply41    # returns the request headers in json format42    json = response.json()43    data = json["form"]44    assert data["custname"] == "Philip J. Fry"45    assert data["custtel"] == ""  # web browser submits "" for input left blank46    assert data["size"] == "medium"47    assert data["topping"] == ["cheese", "onion"]48    assert data["comments"] == "freezer"49@pytest.mark.parametrize("expected_post", [50    pytest.param(51        [52            ('comment', 'Testing preview page'),53            ('preview', 'Preview Page'),54            ('text', 'Setting some text!')55        ], id='preview'),56    pytest.param(57        [58            ('comment', 'Created new page'),59            ('save', 'Submit changes'),60            ('text', '= Heading =\n\nNew page here!\n')61        ], id='save'),62    pytest.param(63        [64            ('comment', 'Testing choosing cancel button'),65            ('cancel', 'Cancel'),66            ('text', '= Heading =\n\nNew page here!\n')67        ], id='cancel'),68])69def test_choose_submit(expected_post):70    browser, url = setup_mock_browser(expected_post=expected_post)71    browser.open(url)72    form = browser.select_form('#choose-submit-form')73    browser['text'] = expected_post[2][1]74    browser['comment'] = expected_post[0][1]75    form.choose_submit(expected_post[1][0])76    res = browser.submit_selected()77    assert(res.status_code == 200 and res.text == 'Success!')78choose_submit_fail_form = '''79<html>80  <form id="choose-submit-form">81    <input type="submit" name="test_submit" value="Test Submit" />82  </form>83</html>84'''85@pytest.mark.parametrize("select_name", [86    pytest.param({'name': 'does_not_exist', 'fails': True}, id='not found'),87    pytest.param({'name': 'test_submit', 'fails': False}, id='found'),88])89def test_choose_submit_fail(select_name):90    browser = mechanicalsoup.StatefulBrowser()91    browser.open_fake_page(choose_submit_fail_form)92    form = browser.select_form('#choose-submit-form')93    if select_name['fails']:94        with pytest.raises(mechanicalsoup.utils.LinkNotFoundError):95            form.choose_submit(select_name['name'])96    else:97        form.choose_submit(select_name['name'])98choose_submit_multiple_match_form = '''99<html>100  <form id="choose-submit-form">101    <input type="submit" name="test_submit" value="First Submit" />102    <input type="submit" name="test_submit" value="Second Submit" />103  </form>104</html>105'''106def test_choose_submit_multiple_match():107    browser = mechanicalsoup.StatefulBrowser()108    browser.open_fake_page(choose_submit_multiple_match_form)109    form = browser.select_form('#choose-submit-form')110    with pytest.raises(mechanicalsoup.utils.LinkNotFoundError):111        form.choose_submit('test_submit')112submit_form_noaction = '''113<html>114  <body>115    <form id="choose-submit-form">116      <input type="text" name="text1" value="someValue1" />117      <input type="text" name="text2" value="someValue2" />118      <input type="submit" name="save" />119    </form>120  </body>121</html>122'''123def test_form_noaction():124    browser, url = setup_mock_browser()125    browser.open_fake_page(submit_form_noaction, url=url)126    form = browser.select_form('#choose-submit-form')127    form['text1'] = 'newText1'128    res = browser.submit_selected()129    assert(res.status_code == 200 and browser.get_url() == url)130submit_form_action = '''131<html>132  <body>133    <form id="choose-submit-form" action="mock://form.com">134      <input type="text" name="text1" value="someValue1" />135      <input type="text" name="text2" value="someValue2" />136      <input type="submit" name="save" />137    </form>138  </body>139</html>140'''141def test_form_action():142    browser, url = setup_mock_browser()143    # for info about example.com see: https://tools.ietf.org/html/rfc2606144    browser.open_fake_page(submit_form_action,145                           url="http://example.com/invalid/")146    form = browser.select_form('#choose-submit-form')147    form['text1'] = 'newText1'148    res = browser.submit_selected()149    assert(res.status_code == 200 and browser.get_url() == url)150set_select_form = '''151<html>152  <form method="post" action="mock://form.com/post">153    <select name="entree">154      <option value="tofu" selected="selected">Tofu Stir Fry</option>155      <option value="curry">Red Curry</option>156      <option value="tempeh">Tempeh Tacos</option>157    </select>158    <input type="submit" value="Select" />159  </form>160</html>161'''162@pytest.mark.parametrize("option", [163    pytest.param({'result': [('entree', 'tofu')], 'default': True},164                 id='default'),165    pytest.param({'result': [('entree', 'curry')], 'default': False},166                 id='selected'),167])168def test_set_select(option):169    '''Test the branch of Form.set that finds "select" elements.'''170    browser, url = setup_mock_browser(expected_post=option['result'],171                                      text=set_select_form)172    browser.open(url)173    browser.select_form('form')174    if not option['default']:175        browser[option['result'][0][0]] = option['result'][0][1]176    res = browser.submit_selected()177    assert(res.status_code == 200 and res.text == 'Success!')178set_select_multiple_form = '''179<form method="post" action="mock://form.com/post">180  <select name="instrument" multiple>181    <option value="piano">Piano</option>182    <option value="bass">Bass</option>183    <option value="violin">Violin</option>184  </select>185  <input type="submit" value="Select Multiple" />186</form>187'''188@pytest.mark.parametrize("options", [189    pytest.param('bass', id='select one (str)'),190    pytest.param(('bass',), id='select one (tuple)'),191    pytest.param(('piano', 'violin'), id='select two'),192])193def test_set_select_multiple(options):194    """Test a <select multiple> element."""195    # When a browser submits multiple selections, the qsl looks like:196    #  name=option1&name=option2197    if not isinstance(options, list) and not isinstance(options, tuple):198        expected = (('instrument', options),)199    else:200        expected = (('instrument', option) for option in options)201    browser, url = setup_mock_browser(expected_post=expected,202                                      text=set_select_multiple_form)203    browser.open(url)204    form = browser.select_form('form')205    form.set_select({'instrument': options})206    res = browser.submit_selected()207    assert(res.status_code == 200 and res.text == 'Success!')208def test_form_not_found():209    browser = mechanicalsoup.StatefulBrowser()210    browser.open_fake_page(page_with_various_fields)211    form = browser.select_form('form')212    with pytest.raises(mechanicalsoup.utils.LinkNotFoundError):213        form.input({'foo': 'bar', 'nosuchname': 'nosuchval'})214    with pytest.raises(mechanicalsoup.utils.LinkNotFoundError):215        form.check({'foo': 'bar', 'nosuchname': 'nosuchval'})216    with pytest.raises(mechanicalsoup.utils.LinkNotFoundError):217        form.check({'entree': 'cheese'})218    with pytest.raises(mechanicalsoup.utils.LinkNotFoundError):219        form.check({'topping': 'tofu'})220    with pytest.raises(mechanicalsoup.utils.LinkNotFoundError):221        form.textarea({'bar': 'value', 'foo': 'nosuchval'})222    with pytest.raises(mechanicalsoup.utils.LinkNotFoundError):223        form.set_radio({'size': 'tiny'})224    with pytest.raises(mechanicalsoup.utils.LinkNotFoundError):225        form.set_select({'entree': ('no_multiple', 'no_multiple')})226page_with_radio = '''227<html>228  <form method="post">229    <input type=checkbox name="foo" value="bacon"> This is a checkbox230  </form>231</html>232'''233def test_form_check_uncheck():234    browser = mechanicalsoup.StatefulBrowser()235    browser.open_fake_page(page_with_radio, url="http://example.com/invalid/")236    form = browser.select_form('form')237    assert "checked" not in form.form.find("input", {"name": "foo"}).attrs238    form["foo"] = True239    assert form.form.find("input", {"name": "foo"}).attrs["checked"] == ""240    # Test explicit unchecking (skipping the call to Form.uncheck_all)241    form.set_checkbox({"foo": False}, uncheck_other_boxes=False)242    assert "checked" not in form.form.find("input", {"name": "foo"}).attrs243page_with_various_fields = '''244<html>245  <form method="post">246    <input name="foo">247    <textarea name="bar">248    </textarea>249    <select name="entree">250      <option value="tofu" selected="selected">  Tofu Stir Fry </option>251      <option value="curry">    Red Curry</option>252      <option value="tempeh">Tempeh Tacos    </option>253    </select>254    <fieldset>255     <legend> Pizza Toppings </legend>256     <p><label> <input type=checkbox name="topping"257      value="bacon"> Bacon </label></p>258     <p><label> <input type=checkbox name="topping"259      value="cheese" checked>Extra Cheese   </label></p>260     <p><label> <input type=checkbox name="topping"261      value="onion" checked> Onion </label></p>262     <p><label> <input type=checkbox name="topping"263      value="mushroom"> Mushroom </label></p>264    </fieldset>265    <p><input name="size" type=radio value="small">Small</p>266    <p><input name="size" type=radio value="medium">Medium</p>267    <p><input name="size" type=radio value="large">Large</p>268    <input type="submit" value="Select" />269  </form>270</html>271'''272def test_form_print_summary(capsys):273    browser = mechanicalsoup.StatefulBrowser()274    browser.open_fake_page(page_with_various_fields,275                           url="http://example.com/invalid/")276    browser.select_form("form")277    browser.get_current_form().print_summary()278    out, err = capsys.readouterr()279    # Different versions of bs4 show either <input></input> or280    # <input/>. Normalize before comparing.281    out = out.replace('></input>', '/>')282    assert out == """<input name="foo"/>283<textarea name="bar"></textarea>284<select name="entree">285<option selected="selected" value="tofu">Tofu Stir Fry</option>286<option value="curry">Red Curry</option>287<option value="tempeh">Tempeh Tacos</option>288</select>289<input name="topping" type="checkbox" value="bacon"/>290<input checked="" name="topping" type="checkbox" value="cheese"/>291<input checked="" name="topping" type="checkbox" value="onion"/>292<input name="topping" type="checkbox" value="mushroom"/>293<input name="size" type="radio" value="small"/>294<input name="size" type="radio" value="medium"/>295<input name="size" type="radio" value="large"/>296<input type="submit" value="Select"/>297"""298    assert err == ""299def test_issue180():300    """Test that a KeyError is not raised when Form.choose_submit is called301    on a form where a submit element is missing its name-attribute."""302    browser = mechanicalsoup.StatefulBrowser()303    html = '''304<form>305  <input type="submit" value="Invalid" />306  <input type="submit" name="valid" value="Valid" />307</form>308'''309    browser.open_fake_page(html)310    form = browser.select_form()311    with pytest.raises(mechanicalsoup.utils.LinkNotFoundError):312        form.choose_submit('not_found')313if __name__ == '__main__':...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
