def testSoap(self): # test soap server implementation from gluon.contrib.pysimplesoap.client import SoapClient, SoapFault url = 'http://127.0.0.1:8000/examples/soap_examples/call/soap?WSDL' client = SoapClient(wsdl=url) ret = client.SubIntegers(a=3, b=2) # check that the value returned is ok assert ('SubResult' in ret) assert (ret['SubResult'] == 1) try: ret = client.Division(a=3, b=0) except SoapFault as sf: # verify the exception value is ok # assert(sf.faultstring == "float division by zero") # true only in 2.7 assert (sf.faultcode == "Server.ZeroDivisionError") # store sent and received xml for low level test xml_request = client.xml_request xml_response = client.xml_response # do a low level raw soap request (using s = WebClient('http://127.0.0.1:8000/') try: s.post('examples/soap_examples/call/soap', data=xml_request, method="POST") except urllib2.HTTPError as e: assert (e.msg == 'INTERNAL SERVER ERROR') # check internal server error returned (issue 153) assert (s.status == 500) assert (s.text == xml_response)
def testSoap(self): # test soap server implementation from gluon.contrib.pysimplesoap.client import SoapClient, SoapFault url = 'http://127.0.0.1:8000/examples/soap_examples/call/soap?WSDL' client = SoapClient(wsdl=url) ret = client.SubIntegers(a=3, b=2) # check that the value returned is ok self.assertIn('SubResult', ret) self.assertEqual(ret['SubResult'], 1) try: ret = client.Division(a=3, b=0) except SoapFault as sf: # verify the exception value is ok # self.assertEqual(sf.faultstring, "float division by zero") # true only in 2.7 self.assertEqual(sf.faultcode, "Server.ZeroDivisionError") # store sent and received xml for low level test xml_request = client.xml_request xml_response = client.xml_response # do a low level raw soap request (using s = WebClient('http://127.0.0.1:8000/') try: s.post('examples/soap_examples/call/soap', data=xml_request, method="POST") except urllib2.HTTPError as e: self.assertEqual(e.msg, 'INTERNAL SERVER ERROR') # check internal server error returned (issue 153) self.assertEqual(s.status, 500) self.assertEqual(s.text, xml_response)
def testStaticCache(self): s = WebClient('http://127.0.0.1:8000/welcome/') s.get('static/js/web2py.js') assert('expires' not in s.headers) assert(not s.headers['cache-control'].startswith('max-age')) text = s.text s.get('static/_1.2.3/js/web2py.js') assert(text == s.text) assert('expires' in s.headers) assert(s.headers['cache-control'].startswith('max-age'))
def testStaticCache(self): s = WebClient("http://127.0.0.1:8000/%s/" % test_app_name) s.get('static/js/web2py.js') self.assertNotIn('expires', s.headers) self.assertFalse(s.headers['cache-control'].startswith('max-age')) text = s.text s.get('static/_1.2.3/js/web2py.js') self.assertEqual(text, s.text) self.assertIn('expires', s.headers) self.assertTrue(s.headers['cache-control'].startswith('max-age'))
def __init__( self, application, username, password, login_employee_id=0, url='', postbacks=True, login_required=True, db=None, dump=False, ): """Constructor Args: application: string, name of web2py application username: string, application login username password: string, application login password employee_id: integer, id of employee record. If non-zero, the session employee is set using this employee. url: string, application url root postbacks: see WebClient login_required: If true, login to application before accessing pages. db: gluon.dal.DAL instance dump: If true, dump page contents """ # C0103: *Invalid name "%%s" (should match %%s)* # pylint: disable=C0103 self.application = application self.username = username self.password = password self.login_employee_id = login_employee_id self.url = url self.postbacks = postbacks self.login_required = login_required self.db = db self.dump = dump self.errors = [] headers = dict(webclient_default_headers) headers['user-agent'] = ' '.join(( 'Mozilla/5.0', '(X11; U; Linux i686; en-US; rv:1.9.2.10)', 'Gecko/20100928', 'Firefox/3.5.7' )) WebClient.__init__( self, self.url, postbacks=self.postbacks, default_headers=headers ) self._soup = None # page as soup self._flash = None # flash message
def __init__( self, application, username, password, login_employee_id=0, url='', postbacks=True, login_required=True, db=None, dump=False, ): """Constructor Args: application: string, name of web2py application username: string, application login username password: string, application login password employee_id: integer, id of employee record. If non-zero, the session employee is set using this employee. url: string, application url root postbacks: see WebClient login_required: If true, login to application before accessing pages. db: gluon.dal.DAL instance dump: If true, dump page contents """ # C0103: *Invalid name "%%s" (should match %%s)* # pylint: disable=C0103 self.application = application self.username = username self.password = password self.login_employee_id = login_employee_id self.url = url if url else 'https://jimk.zsw.ca' self.postbacks = postbacks self.login_required = login_required self.db = db self.dump = dump headers = dict(webclient_default_headers) headers['user-agent'] = ' '.join( ('Mozilla/5.0', '(X11; U; Linux i686; en-US; rv:1.9.2.10)', 'Gecko/20100928', 'Firefox/3.5.7')) WebClient.__init__(self, self.url, postbacks=self.postbacks, default_headers=headers) self._soup = None # page as soup self._flash = None # flash message
def get(self, url, cookies=None, headers=None, auth=None): """Override base class method. Args: See WebClient.get() Differences from base class method. * Clears _soup property. * Issues a db.commit(). Why this is needed is a bit foggy but, the module running tests and the script run by webclient urllib2 calls have two distinct database handles. Changes on one may not be available on the other until a commit() is called. """ self._soup = None result = WebClient.get( self, url, cookies=None, headers=None, auth=None ) if self.db: self.db.commit() return result
def post(self, url, data=None, cookies=None, headers=None, auth=None, method='auto'): """Override base class method. Args: See WebClient.post() Differences from base class method. * Clears _soup property. """ self._soup = None result = WebClient.post(self, url, data=data, cookies=None, headers=None, auth=None, method=method) if self.db: self.db.commit() return result
def client(baseurl): '''Create a new WebClient instance once per session. ''' from gluon.contrib.webclient import WebClient webclient = WebClient(baseurl) return webclient
class TestDefaultController(unittest.TestCase): def setUp(self): self.client = WebClient('http://127.0.0.1:8000/fogger/default/', postbacks=True) def testRetrievePeopleFromDatabase(self): # login again data = dict(username='******', password='******', _formkey='login') self.client.post('user/login', data=data) print self.client.text # check registration and login were successful self.client.get('people') print self.client.text
def post( self, url, data=None, cookies=None, headers=None, auth=None, method='auto'): """Override base class method. Args: See WebClient.post() Differences from base class method. * Clears _soup property. """ self._soup = None result = WebClient.post( self, url, data=data, cookies=None, headers=None, auth=None, method=method ) if self.db: self.db.commit() return result
def client(baseurl, fixture_create_testfile_for_application): ''' Create a new WebClient instance once per module. ''' from gluon.contrib.webclient import WebClient webclient = WebClient(baseurl) return webclient
def run_test(self, test_num, test): print "num: " + test_num, test url_parts = [self.web_url, self.web_application, test.get("controller")] request_url = test.get("function") for arg in test.get("arguments"): url_parts.append(arg) url = self.make_w2py_url(test) print "RUN TEST FOR url=" + url try: client = WebClient(url, postbacks=True) client.get("") except Exception as e: print e print "Test failed!" print client.text print client.status
def startwebserver(context): """ starts the default webserver on given port """ startargs = [sys.executable, os.path.join(context.web2py_path, "web2py.py")] startargs.extend(["-i", HOST, "-p", str(PORT), "-a", "testpass"]) webserverprocess = subprocess.Popen(startargs) print "Sleeping before web2py starts ..." for i in xrange(1, 5): print i, "..." time.sleep(1) try: c = WebClient("http://%s:%s" % (HOST, PORT)) c.get("/") break except: continue return webserverprocess
def startwebserver(context): """ starts the default webserver on port 8000 """ startargs = [sys.executable, os.path.join(context.web2py_path, 'web2py.py')] startargs.extend(['-i', HOST, '-p', str(PORT), '-a', 'testpass']) webserverprocess = subprocess.Popen(startargs) print 'Sleeping before web2py starts...' for i in range(1, 5): time.sleep(1) print i, '...' try: c = WebClient('http://%s:%s' % (HOST, PORT)) c.get('/') break except: continue return webserverprocess
def testParseMultipleEquals(self): """ Test for issue #1500. Ensure that a cookie containing one or more '=' is correctly parsed """ client = WebClient() client.headers['set-cookie'] = "key = value with one =;" client._parse_headers_in_cookies() self.assertIn("key", client.cookies) self.assertEqual(client.cookies['key'], "value with one =") client.headers['set-cookie'] = "key = value with one = and another one =;" client._parse_headers_in_cookies() client._parse_headers_in_cookies() self.assertIn("key", client.cookies) self.assertEqual(client.cookies['key'], "value with one = and another one =")
def startwebserver(): global webserverprocess path = path = os.path.dirname(os.path.abspath(__file__)) if not os.path.isfile(os.path.join(path, 'web2py.py')): i = 0 while i < 10: i += 1 if os.path.exists(os.path.join(path, 'web2py.py')): break path = os.path.abspath(os.path.join(path, '..')) web2py_exec = os.path.join(path, 'web2py.py') webserverprocess = subprocess.Popen([sys.executable, web2py_exec, '-a', 'testpass']) print('Sleeping before web2py starts...') for a in range(1, 11): time.sleep(1) print("%d..." % a) try: c = WebClient('http://127.0.0.1:8000/') c.get(test_app_name) break except: continue print('')
def startwebserver(): global webserverprocess path = path = os.path.dirname(os.path.abspath(__file__)) if not os.path.isfile(os.path.join(path, 'web2py.py')): i = 0 while i < 10: i += 1 if os.path.exists(os.path.join(path, 'web2py.py')): break path = os.path.abspath(os.path.join(path, '..')) web2py_exec = os.path.join(path, 'web2py.py') webserverprocess = subprocess.Popen([sys.executable, web2py_exec, '-a', 'testpass']) print('Sleeping before web2py starts...') for a in range(1, 11): time.sleep(1) print(a, '...') try: c = WebClient('http://127.0.0.1:8000') c.get('/') break except: continue print('')
def testStaticCache(self): s = WebClient('http://127.0.0.1:8000/welcome/') s.get('static/js/web2py.js') assert ('expires' not in s.headers) assert (not s.headers['cache-control'].startswith('max-age')) text = s.text s.get('static/_1.2.3/js/web2py.js') assert (text == s.text) assert ('expires' in s.headers) assert (s.headers['cache-control'].startswith('max-age'))
def get(self, url, cookies=None, headers=None, auth=None): """Override base class method. Args: See WebClient.get() Differences from base class method. * Clears _soup property. * Issues a db.commit(). Why this is needed is a bit foggy but, the module running tests and the script run by webclient urllib2 calls have two distinct database handles. Changes on one may not be available on the other until a commit() is called. """ self._soup = None result = WebClient.get(self, url, cookies=None, headers=None, auth=None) if self.db: self.db.commit() return result
def login(acc): data = dict(source='MENU', login=acc.acc, password=acc.skey) if TTT == 'lib': h = urllib2.Request(URL + URL_LOG, urllib.urlencode(data), headers) r = urllib2.urlopen(h) r = json.load(r) elif TTT == 'wcl': from gluon.contrib.webclient import WebClient client = WebClient(URL, postbacks=True) client.post(URL_LOG, data=data, headers=headers) print client.status, client.text, '\n headers:', client.headers, '\n cookies: ', client.cookies, '\n sessions:', client.sessions r = json.loads(client.text) code = r.get('code') code = code and code.get('value') if not code or code != '7': return 'error on first request', r d = r.get('data') token = d and d.get('token') #acc.update_record( pkey = token ) data['loginToken'] = token if TTT == 'lib': h = urllib2.Request(URL + URL_LOG, urllib.urlencode(data), headers) r = urllib2.urlopen(h) # , URL_LOG + '?' + urllib.urlencode(data)) r = json.load(r) elif TTT == 'wcl': client.post(URL_LOG, data=data, headers=headers) print client.status, client.text, '\n headers:', client.headers, '\n cookies: ', client.cookies, '\n sessions:', client.sessions r = json.loads(client.text) code = r.get('code') code = code and code.get('value') if not code or code != '0': return 'error on second request', r d = r.get('data') token = d and d.get('token') #acc.update_record( pkey = token ) return None, r
# coding: utf-8 from gluon.contrib.webclient import WebClient client = WebClient('http://127.0.0.1:8000/M2L/', postbacks=True) client.get('default/index') data = dict(email='*****@*****.**', password='******', _formname='login') client.post('default/user/login', data=data) # Vérifie que la connexion est un succès try: assert 'Bienvenue Lucille' in client.text print "Test connexion OK" except Exception as e: print "Echec test de connexion" # DEBUG ------- #print '\ncontenu:\n', client.text #print '\nsessions:\n', client.sessions #print '\nheaders:\n', client.headers #print '\ncookies:\n', client.cookies #print '\nforms:\n', client.forms #print #for method, url, status, t in client.history: # print method, url, status, t
def validate( self, # The relative URL to validate. url, # An optional string that, if provided, must be in the text returned by the server. If this is a list of strings, at least one of the provided strings but be in the text returned by the server. expected_string='', # The number of validation errors expected. If None, no validation is performed. expected_errors=None, # The expected status code from the request. expected_status=200, # All additional keyword arguments are passed to the ``post`` method. **kwargs): try: try: self.post(url, **kwargs) except HTTPError as e: # If this was the expected result, return. if e.code == expected_status: # Since this is an error of some type, these paramets must be empty, since they can't be checked. assert not expected_string assert not expected_errors return '' else: raise assert self.status == expected_status if expected_string: if isinstance(expected_string, str): assert expected_string in self.text else: # Assume ``expected_string`` is a list of strings. assert all(string in self.text for string in expected_string) if expected_errors is not None: vld = HTMLValidator() vld.validate_fragment(self.text) if len(vld.errors) != expected_errors: print('Errors for {}: {}'.format(url, len(vld.errors))) pprint(vld.errors) assert False if vld.warnings: print('Warnings for {}: {}'.format(url, len(vld.warnings))) pprint(vld.warnings) return self.text except AssertionError: # Save the HTML to make fixing the errors easier. Note that ``self.text`` is already encoded as utf-8. validation_file = url.replace('/', '-') + '.html' with open(validation_file, 'wb') as f: f.write(_html_prep(self.text)) print('Validation failure saved to {}.'.format(validation_file)) raise except RuntimeError as e: # Provide special handling for web2py exceptions by saving the # resulting traceback. if e.args[0].startswith('ticket '): # Create a client to access the admin interface. admin_client = WebClient('{}/admin/'.format( self.web2py_server_address), postbacks=True) # Log in. admin_client.post( '', data={'password': self.web2py_server.password}) assert admin_client.status == 200 # Get the error. error_code = e.args[0][len('ticket '):] admin_client.get('default/ticket/' + error_code) assert admin_client.status == 200 # Save it to a file. traceback_file = url.replace('/', '-') + '_traceback.html' with open(traceback_file, 'wb') as f: f.write(_html_prep(admin_client.text)) print('Traceback saved to {}.'.format(traceback_file)) raise
from gluon.contrib.webclient import WebClient import xmlrpclib import urllib import xmlrpclib #import simplejson #import gluon.contrib.jsonrpclib ############################## ## LOGIN TESTING ## ############################## client = WebClient('http://127.0.0.1:8000/to_do/default/', postbacks=True) client.post('user/logout') data = dict(email='*****@*****.**', password='******', _formname = 'login') client.post('user/login', data = data) # Check the login was successful client.get('index') assert('Welcome Neil' in client.text) ############################## ## END LOGIN TESTING ## ##############################
def setUp(self): self.client = WebClient('http://127.0.0.1:8000/fogger/default/', postbacks=True)
def validate( self, # The relative URL to validate. url, # An optional string that, if provided, must be in the text returned by the server. If this is a sequence of strings, all of the provided strings must be in the text returned by the server. expected_string="", # The number of validation errors expected. If None, no validation is performed. expected_errors=None, # The expected status code from the request. expected_status=200, # All additional keyword arguments are passed to the ``post`` method. **kwargs, ): try: try: self.post(url, **kwargs) except HTTPError as e: # If this was the expected result, return. if e.code == expected_status: # Since this is an error of some type, these paramets must be empty, since they can't be checked. assert not expected_string assert not expected_errors return "" else: raise assert self.status == expected_status if expected_string: if isinstance(expected_string, str): assert expected_string in self.text else: # Assume ``expected_string`` is a sequence of strings. assert all(string in self.text for string in expected_string) if expected_errors is not None and not self.pytestconfig.getoption( "skip_w3_validate"): # Redo this section using html5validate command line vld = Validator(errors_only=True, stack_size=2048) tmpname = self.tmp_path / "tmphtml.html" with open(tmpname, "w", encoding="utf8") as f: f.write(self.text) errors = vld.validate([str(tmpname)]) assert errors <= expected_errors return self.text except AssertionError: # Save the HTML to make fixing the errors easier. Note that ``self.text`` is already encoded as utf-8. validation_file = url.replace("/", "-") + ".html" with open(validation_file, "wb") as f: f.write(_html_prep(self.text)) print("Validation failure saved to {}.".format(validation_file)) raise except RuntimeError as e: # Provide special handling for web2py exceptions by saving the # resulting traceback. if e.args[0].startswith("ticket "): # Create a client to access the admin interface. admin_client = WebClient("{}/admin/".format( self.web2py_server_address), postbacks=True) # Log in. admin_client.post( "", data={"password": self.web2py_server.password}) assert admin_client.status == 200 # Get the error. error_code = e.args[0][len("ticket "):] admin_client.get("default/ticket/" + error_code) assert admin_client.status == 200 # Save it to a file. traceback_file = ("".join(c if c not in r"\/:*?<>|" else "_" for c in url) + "_traceback.html") with open(traceback_file, "wb") as f: f.write(_html_prep(admin_client.text)) print("Traceback saved to {}.".format(traceback_file)) raise
def testRegisterAndLogin(self): client = WebClient("http://127.0.0.1:8000/%s/default/" % test_app_name) client.get('index') # register data = dict(first_name='Homer', last_name='Simpson', email='*****@*****.**', password='******', password_two='test', _formname='register') client.post('user/register', data=data) # logout client.get('user/logout') # login again data = dict(email='*****@*****.**', password='******', _formname='login') client.post('user/login', data=data) self.assertIn('Homer', client.text) # check registration and login were successful client.get('index') self.assertIn('Homer', client.text) client = WebClient('http://127.0.0.1:8000/admin/default/') client.post('index', data=dict(password='******')) client.get('site') client.get('design/' + test_app_name)
# add gluon to path so it can be included easily # this si done because web2py wasn't installed and isn't in the pythonpath import sys sys.path.append('../../..') # web2py root from gluon.contrib.webclient import WebClient client = WebClient('http://127.0.0.1:8000/tuxymat/vending_machines/', postbacks=True) client.get('index') assert('ABCDE' in client.text) # uses dev DB ! (incl. already existing data) data = dict(serial_number = 'ABCDE', purchase_price = 10.3 ) client.post('new',data = data) data = dict(serial_number = 'ABCDE', purchase_price = 10.3 ) client.post('new',data = data) # doesn't raise error on duplicate record (even though it isn't created due to validation) data = dict(serial_number = 'ABCDEZZZ', purchase_price = 10.3 ) client.post('new',data = data) client.get('index') assert('ABCDEZZZ' in client.text)
# in MS Windows, create en environment variable (if not exists) # PYTHONPATH containing the path to web2py from gluon.contrib.webclient import WebClient import dommartin25 client = WebClient('http://www.dommartin25.fr') #Home page client.get('') assert ('Welcome on' in client.text) #test each page db = DAL('mysql://*****:*****@vps20356.ovh.net/dommartin25') for tablename in db.tables: print tablename # pages = db().select(db.page.ALL) # for page in pages: # client.get('pages/show_page/%s' %page.url) # assert(page.title in client.text) # # register # data = dict(first_name = 'Homer', # last_name = 'Simpson', # email = '*****@*****.**', # password = '******', # password_two = 'test', # _formname = 'register') # client.post('user/register',data = data)
from gluon.contrib.webclient import WebClient client = WebClient('http://127.0.0.1:8000/Proyecto_Fase_I/default/') client.get('index') # register data = dict(first_name='Homer', last_name='Simpson', email='*****@*****.**', password='******', password_two='test', _formname='register') client.post('user/register', data=data) # logout client.get('user/logout') # login data = dict(email='*****@*****.**', password='******', _formname='login') client.post('user/login', data=data) # check registration and login were successful client.get('user/profile') assert 'Welcome danigay' in client.text # Prueba funcional para la funcion Agregar Especialidad # Detalle='especialidad' Detalle es el atributo como lo defini en dbwizard, si hay mas atributos se agregan con "," # _formname='registro' Esto se queda asi # data1 es el nombre del objeto que tiene los mismo atributos que mi tabla # client.post('especializacion', data=data1) especializacion es el nombre de la pagina html, que va despues de default/
def testWebClient(self): client = WebClient('http://127.0.0.1:8000/welcome/default/') client.get('index') # register data = dict(first_name = 'Homer', last_name = 'Simpson', email = '*****@*****.**', password = '******', password_two = 'test', _formname = 'register') client.post('user/register',data = data) # logout client.get('user/logout') # login again data = dict(email='*****@*****.**', password='******', _formname = 'login') client.post('user/login',data = data) # check registration and login were successful client.get('index') self.assertTrue('Welcome Homer' in client.text) client = WebClient('http://127.0.0.1:8000/admin/default/') client.post('index',data=dict(password='******')) client.get('site') client.get('design/welcome')
# in MS Windows, create en environment variable (if not exists) # PYTHONPATH containing the path to web2py from gluon.contrib.webclient import WebClient import dommartin25 client = WebClient('http://www.dommartin25.fr') #Home page client.get('') assert('Welcome on' in client.text) #test each page db = DAL('mysql://*****:*****@vps20356.ovh.net/dommartin25') for tablename in db.tables: print tablename # pages = db().select(db.page.ALL) # for page in pages: # client.get('pages/show_page/%s' %page.url) # assert(page.title in client.text) # # register # data = dict(first_name = 'Homer', # last_name = 'Simpson', # email = '*****@*****.**', # password = '******', # password_two = 'test', # _formname = 'register')
import unittest from gluon.contrib.webclient import WebClient client = WebClient('http://127.0.0.1:8080/', postbacks=True) class IntegrationTest(unittest.TestCase): def test_index(self): client.get('index') assert 200 == client.response.status if __name__ == '__main__': unittest.main()
from gluon.contrib.webclient import WebClient client = WebClient('http://127.0.0.1:8000/Proyecto_Fase_I/default/') client.get('index') # register data = dict(first_name='Homer', last_name='Simpson', email='*****@*****.**', password='******', password_two='test', _formname='register') client.post('user/register', data=data) # logout client.get('user/logout') # login data = dict(email='*****@*****.**', password='******', _formname='login') client.post('user/login', data=data) # check registration and login were successful client.get('user/profile') assert 'Welcome Homer' in client.text # logout client.get('user/logout') # print some variables print for method, url, status, t in client.history: if status == 200:
def validate(self, # The relative URL to validate. url, # An optional string that, if provided, must be in the text returned by the server. If this is a list of strings, at least one of the provided strings but be in the text returned by the server. expected_string='', # The number of validation errors expected. If None, no validation is performed. expected_errors=None, # The expected status code from the request. expected_status=200, # All additional keyword arguments are passed to the ``post`` method. **kwargs): try: try: self.post(url, **kwargs) except HTTPError as e: # If this was the expected result, return. if e.code == expected_status: # Since this is an error of some type, these paramets must be empty, since they can't be checked. assert not expected_string assert not expected_errors return '' else: raise assert self.status == expected_status if expected_string: if isinstance(expected_string, str): assert expected_string in self.text else: # Assume ``expected_string`` is a list of strings. assert all(string in self.text for string in expected_string) if expected_errors is not None: vld = HTMLValidator() vld.validate_fragment(self.text) if len(vld.errors) != expected_errors: print('Errors for {}: {}'.format(url, len(vld.errors))) pprint(vld.errors) assert False if vld.warnings: print('Warnings for {}: {}'.format(url, len(vld.warnings))) pprint(vld.warnings) return self.text if six.PY3 else self.text.decode('utf-8') except AssertionError: # Save the HTML to make fixing the errors easier. Note that ``self.text`` is already encoded as utf-8. validation_file = url.replace('/', '-') + '.html' with open(validation_file, 'wb') as f: f.write(_html_prep(self.text)) print('Validation failure saved to {}.'.format(validation_file)) raise except RuntimeError as e: # Provide special handling for web2py exceptions by saving the # resulting traceback. if e.args[0].startswith('ticket '): # Create a client to access the admin interface. admin_client = WebClient('http://127.0.0.1:8000/admin/', postbacks=True) # Log in. admin_client.post('', data={'password': self.web2py_server.password}) assert admin_client.status == 200 # Get the error. error_code = e.args[0][len('ticket '):] admin_client.get('default/ticket/' + error_code) assert admin_client.status == 200 # Save it to a file. traceback_file = url.replace('/', '-') + '_traceback.html' with open(traceback_file, 'wb') as f: f.write(_html_prep(admin_client.text)) print('Traceback saved to {}.'.format(traceback_file)) raise
from gluon.contrib.webclient import WebClient client = WebClient("http://127.0.0.1:8000/Proyecto_Fase_I/default/") client.get("index") # register data = dict( first_name="Homer", last_name="Simpson", email="*****@*****.**", password="******", password_two="test", _formname="register", ) client.post("user/register", data=data) # logout client.get("user/logout") # login data = dict(email="*****@*****.**", password="******", _formname="login") client.post("user/login", data=data) # check registration and login were successful client.get("user/profile") assert "Welcome Homer" in client.text # logout client.get("user/logout") # print some variables
def validate( self, # The relative URL to validate. url, # An optional string that, if provided, must be in the text returned by the server expected_string='', # The number of validation errors expected. If None, no validation is performed. expected_errors=None, # An optional dictionary of query parameters. params=None, # The expected status code from the request. expected_status=200, # All additional keyword arguments are passed to the ``post`` method. **kwargs): try: self.post(url, **kwargs) assert self.status == expected_status if expected_string: assert expected_string in self.text if expected_errors is not None: vld = HTMLValidator() vld.validate_fragment(self.text) if len(vld.errors) != expected_errors: print('Errors for {}: {}'.format(url, len(vld.errors))) pprint(vld.errors) assert False if vld.warnings: print('Warnings for {}: {}'.format(url, len(vld.warnings))) pprint(vld.warnings) except AssertionError: # Save the HTML to make fixing the errors easier. Note that ``self.text`` is already encoded as utf-8. validation_file = url.replace('/', '-') + '.html' with open(validation_file, 'wb') as f: f.write(self.text.replace('\r\n', '\n')) print('Validation failure saved to {}.'.format(validation_file)) raise except RuntimeError as e: # Provide special handling for web2py exceptions by saving the # resulting traceback. if e.args[0].startswith('ticket '): # Create a client to access the admin interface. admin_client = WebClient('http://127.0.0.1:8000/admin/', postbacks=True) # Log in. admin_client.post( '', data={'password': self.web2py_server.password}) assert admin_client.status == 200 # Get the error. error_code = e.args[0][len('ticket '):] admin_client.get('default/ticket/' + error_code) assert admin_client.status == 200 # Save it to a file. traceback_file = url.replace('/', '-') + '_traceback.html' with open(traceback_file, 'wb') as f: f.write(admin_client.text.replace('\r\n', '\n')) print('Traceback saved to {}.'.format(traceback_file)) raise
from gluon.contrib.webclient import WebClient client = WebClient('http://127.0.0.1:8000/circi/default/', postbacks=True) client.get('index') # register data = dict(first_name='John', last_name='Sample', email='*****@*****.**', password='******', password_two='test', _formname='register') client.post('user/register', data=data) # logout client.get('user/logout') # login again data = dict(email='*****@*****.**', password='******', _formname='login') client.post('user/login', data=data) # check registration and login were successful client.get('index') assert('Welcome John' in client.text)
def testWebClient(self): client = WebClient('http://127.0.0.1:8000/welcome/default/') client.get('index') # register data = dict(first_name='Homer', last_name='Simpson', email='*****@*****.**', password='******', password_two='test', _formname='register') client.post('user/register', data=data) # logout client.get('user/logout') # login again data = dict(email='*****@*****.**', password='******', _formname='login') client.post('user/login', data=data) # check registration and login were successful client.get('index') self.assertTrue('Welcome Homer' in client.text) client = WebClient('http://127.0.0.1:8000/admin/default/') client.post('index', data=dict(password='******')) client.get('site') client.get('design/welcome')
# coding: utf8 # import WebClient from Gluon from gluon.contrib.webclient import WebClient # connect to tracker app client = WebClient('http://127.0.0.1:8000/tracker/default/', postbacks=True) # this runs all tests and returns them as a list def run_tests(): results = [] results.append(test1()) results.append(test2()) results.append(test3()) results.append(test4()) results.append(test5()) return results # test 1 is a basic test of the title def test1(): # get the first page and test title client.get('index') assert ('Project Tracker' in client.text) return 'Test 1 passed.' # db table to use to store whether the user has been registered yet or not db.define_table('testuser', Field('name', 'string'), Field('registered', 'boolean', default=False))