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 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)
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 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
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 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
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 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)
# 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 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 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
# 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)
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 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)
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 ## ##############################
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
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/
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