Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def open_legacy_httpbin(browser, httpbin):
"""Opens the start page of httpbin (given as a fixture). Tries the
legacy page (available only on recent versions of httpbin), and if
it fails fall back to the main page (which is JavaScript-only in
recent versions of httpbin hence usable for us only on old
versions).
"""
try:
response = browser.open(httpbin + "/legacy")
if response.status_code == 404:
# The line above may or may not have raised the exception
# depending on raise_on_404. Raise it unconditionally now.
raise mechanicalsoup.LinkNotFoundError()
except mechanicalsoup.LinkNotFoundError:
browser.open(httpbin.url)
def test_select_form_nr():
"""Test the nr option of select_form."""
forms = """<form id="a"></form><form id="b"></form><form id="c"></form>"""
with mechanicalsoup.StatefulBrowser() as browser:
browser.open_fake_page(forms)
form = browser.select_form()
assert form.form['id'] == "a"
form = browser.select_form(nr=1)
assert form.form['id'] == "b"
form = browser.select_form(nr=2)
assert form.form['id'] == "c"
with pytest.raises(mechanicalsoup.LinkNotFoundError):
browser.select_form(nr=3)
def test_launch_browser(mocker):
browser = mechanicalsoup.StatefulBrowser()
browser.set_debug(True)
browser.open_fake_page('')
mocker.patch('webbrowser.open')
with pytest.raises(mechanicalsoup.LinkNotFoundError):
browser.follow_link('nosuchlink')
# mock.assert_called_once() not available on some versions :-(
assert webbrowser.open.call_count == 1
mocker.resetall()
with pytest.raises(mechanicalsoup.LinkNotFoundError):
browser.select_form('nosuchlink')
# mock.assert_called_once() not available on some versions :-(
assert webbrowser.open.call_count == 1
def _MFACheck(br, email, soup):
Log('MFA, DCQ or Captcha form')
uni_soup = soup.__unicode__()
try:
form = br.select_form('form[name="signIn"]')
except mechanicalsoup.LinkNotFoundError:
form = br.select_form()
if 'auth-mfa-form' in uni_soup:
msg = soup.find('form', attrs={'id': 'auth-mfa-form'})
msgtxt = msg.p.get_text(strip=True)
kb = xbmc.Keyboard('', msgtxt)
kb.doModal()
if kb.isConfirmed() and kb.getText():
br['otpCode'] = kb.getText()
else:
return None
elif 'ap_dcq_form' in uni_soup:
msg = soup.find('div', attrs={'id': 'message_warning'})
g.dialog.ok(g.__plugin__, msg.p.get_text(strip=True))
dcq = soup.find('div', attrs={'id': 'ap_dcq1a_pagelet'})
dcq_title = dcq.find('div', attrs={'id': 'ap_dcq1a_pagelet_title'}).get_text(strip=True)
def test_404(httpbin):
browser = mechanicalsoup.Browser(raise_on_404=True)
with pytest.raises(mechanicalsoup.LinkNotFoundError):
resp = browser.get(httpbin + "/nosuchpage")
resp = browser.get(httpbin.url)
assert resp.status_code == 200
form['lastname'] = self._settings.get('user', "lastname")
form['email'] = self._change_email_provider(self._settings.get('user', "email"), '@gmail.com')
form['phonenumber'] = self._settings.get('user', "phonenumber")
form['companyname'] = self._settings.get('user', "companyname")
form['address1'] = self._settings.get('address', "address")
form['city'] = self._settings.get('address', "city")
form['state'] = self._settings.get('address', "state")
form['postcode'] = self._settings.get('address', "zipcode")
form['country'] = self._settings.get('address', 'countrycode')
form['password'] = self._settings.get('user', "password")
form['password2'] = self._settings.get('user', "password")
form['paymentmethod'] = payment_method.lower()
try:
form['accepttos'] = True # Attempt to accept the terms and conditions
except LinkNotFoundError:
pass
page = self._browser.submit_selected()
# Error handling
if 'checkout' in page.url:
soup = BeautifulSoup(page.text, 'lxml')
errors = soup.find('div', {'class': errorbox_class}).text
print((errors.strip()))
sys.exit(2)
return page
def server_form(self, user_settings):
"""
Fills in the form containing server configuration.
:param user_settings: settings
:return:
"""
self.select_form_id(self.br, 'frmConfigureProduct')
self.fill_in_server_form(self.br.form, user_settings, nameservers=False)
try:
self.br.form['configoption[20]'] = ['53'] # Paris
self.br.form['configoption[2]'] = ['13']
except LinkNotFoundError:
self.br.form['configoption[19]'] = ['51'] # Paris
self.br.form['configoption[16]'] = ['41'] # Ubuntu 14.04
self.br.submit()
xbmc.executebuiltin('Addon.OpenSettings({})'.format(var.addon.getAddonInfo('id')))
return False
if password:
cj = requests.cookies.RequestsCookieJar()
br = mechanicalsoup.StatefulBrowser(soup_config={'features': 'html.parser'})
br.set_cookiejar(cj)
br.session.verify = var.verifySsl
caperr = -5
while caperr:
Log('Connect to SignIn Page {} attempts left'.format(-caperr))
br.session.headers.update({'User-Agent': getConfig('UserAgent')})
br.open(BaseUrl + '/gp/aw/si.html')
try:
form = br.select_form('form[name="signIn"]')
except mechanicalsoup.LinkNotFoundError:
getUA(True)
caperr += 1
WriteLog(str(br.get_current_page()), 'login-si')
xbmc.sleep(randint(750, 1500))
else:
break
else:
Dialog.ok(getString(30200), getString(30213))
return False
form.set_input({'email': email, 'password': password})
br.session.headers.update({'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'Accept-Encoding': 'gzip, deflate',
'Accept-Language': 'de,en-US;q=0.8,en;q=0.6',
'Cache-Control': 'max-age=0',
form.form['action'] = 'https://crowncloud.net/clients/cart.php'
print("Frm1")
# form.form['method'] = 'post'
except LinkNotFoundError:
print("Frm2")
form = self._browser.select_form('form#frmConfigureProduct')
self._fill_server_form()
form['billingcycle'] = 'monthly'
form['configoption[1]'] = '56'
form['configoption[8]'] = '52'
try: # The extra bandwidth option is not always available
form['configoption[9]'] = '0'
except LinkNotFoundError:
pass
return self._browser.submit_selected()