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)
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')
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')
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 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/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
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 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 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 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(): 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 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 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 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/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 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
############################## ## 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 ## ############################## ############################## ## ADD PROJECT TESTING ## ############################## data = dict(name = "Build an In-House Messaging Service",
# 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)
# 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
# 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')
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/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 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
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
# 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)