本文整理汇总了Python中robot.libraries.BuiltIn.BuiltIn.convert_to_boolean方法的典型用法代码示例。如果您正苦于以下问题:Python BuiltIn.convert_to_boolean方法的具体用法?Python BuiltIn.convert_to_boolean怎么用?Python BuiltIn.convert_to_boolean使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类robot.libraries.BuiltIn.BuiltIn
的用法示例。
在下文中一共展示了BuiltIn.convert_to_boolean方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: RequestsLibrary
# 需要导入模块: from robot.libraries.BuiltIn import BuiltIn [as 别名]
# 或者: from robot.libraries.BuiltIn.BuiltIn import convert_to_boolean [as 别名]
class RequestsLibrary(object):
ROBOT_LIBRARY_SCOPE = 'Global'
def __init__(self):
self._cache = robot.utils.ConnectionCache('No sessions created')
self.builtin = BuiltIn()
def _utf8_urlencode(self, data):
if not type(data) is dict:
return data
utf8_data = {}
for k, v in data.iteritems():
utf8_data[k] = unicode(v).encode('utf-8')
return urlencode(utf8_data)
def create_session(self, alias, url, headers={}, cookies=None,
auth=None, timeout=None, proxies=None,
verify=False):
""" Create Session: create a HTTP session to a server
`url` Base url of the server
`alias` Robot Framework alias to identify the session
`headers` Dictionary of default headers
`auth` Dictionary of username & password for HTTP Basic Auth
`timeout` connection timeout
`proxies` proxy server url
`verify` set to True if Requests should verify the certificate
"""
self.builtin.log('Creating session: %s' % alias, 'DEBUG')
auth = requests.auth.HTTPBasicAuth(*auth) if auth else None
s = session = requests.Session()
s.headers.update(headers)
s.auth = auth if auth else s.auth
s.proxies = proxies if proxies else s.proxies
s.verify = self.builtin.convert_to_boolean(verify)
# cant pass these into the Session anymore
self.timeout = timeout
self.cookies = cookies
self.verify = verify
# cant use hooks :(
s.url = url
self._cache.register(session, alias=alias)
return session
def delete_all_sessions(self):
"""Removes all the session objects"""
self._cache.empty_cache()
def to_json(self, content):
"""Convert a string to a JSON object
`content` String content to convert into JSON
"""
return json.loads(content)
def _get_url(self, session, uri):
"""Helpere method to get the full url"""
url = session.url
if uri:
slash = '' if uri.startswith('/') else '/'
url = "%s%s%s" % (session.url, slash, uri)
return url
def get(self, alias, uri, headers=None):
"""Send a GET request on the session object found using the given `alias`
`alias` that will be used to identify the Session object in the cache
`uri` to send the GET request to
`headers` a dictionary of headers to use with the request
"""
session = self._cache.switch(alias)
resp = session.get(self._get_url(session, uri),
headers=headers,
cookies=self.cookies, timeout=self.timeout)
# store the last response object
session.last_resp = resp
return resp
def post(self, alias, uri, data={}, headers=None, files={}):
"""Send a POST request on the session object found using the given `alias`
`alias` that will be used to identify the Session object in the cache
#.........这里部分代码省略.........
示例2: RequestsKeywords
# 需要导入模块: from robot.libraries.BuiltIn import BuiltIn [as 别名]
# 或者: from robot.libraries.BuiltIn.BuiltIn import convert_to_boolean [as 别名]
class RequestsKeywords(object):
ROBOT_LIBRARY_SCOPE = 'Global'
def __init__(self):
self._cache = robot.utils.ConnectionCache('No sessions created')
self.builtin = BuiltIn()
self.debug = 0
def _create_session(
self,
alias,
url,
headers,
cookies,
auth,
timeout,
max_retries,
backoff_factor,
proxies,
verify,
debug,
disable_warnings):
""" Create Session: create a HTTP session to a server
`url` Base url of the server
`alias` Robot Framework alias to identify the session
`headers` Dictionary of default headers
`auth` List of username & password for HTTP Basic Auth
`timeout` Connection timeout
`max_retries` The maximum number of retries each connection should attempt.
`backoff_factor` The pause between for each retry
`proxies` Dictionary that contains proxy urls for HTTP and HTTPS communication
`verify` Whether the SSL cert will be verified. A CA_BUNDLE path can also be provided.
`debug` Enable http verbosity option more information
https://docs.python.org/2/library/httplib.html#httplib.HTTPConnection.set_debuglevel
`disable_warnings` Disable requests warning useful when you have large number of testcases
"""
self.builtin.log('Creating session: %s' % alias, 'DEBUG')
s = session = requests.Session()
s.headers.update(headers)
s.auth = auth if auth else s.auth
s.proxies = proxies if proxies else s.proxies
max_retries = self.builtin.convert_to_integer(max_retries)
if max_retries > 0:
http = requests.adapters.HTTPAdapter(max_retries=Retry(total=max_retries, backoff_factor=backoff_factor))
https = requests.adapters.HTTPAdapter(max_retries=Retry(total=max_retries, backoff_factor=backoff_factor))
# Disable requests warnings, useful when you have large number of testcase
# you will observe drastical changes in Robot log.html and output.xml files size
if disable_warnings:
logging.basicConfig() # you need to initialize logging, otherwise you will not see anything from requests
logging.getLogger().setLevel(logging.ERROR)
requests_log = logging.getLogger("requests")
requests_log.setLevel(logging.ERROR)
requests_log.propagate = True
# Replace the session's original adapters
s.mount('http://', http)
s.mount('https://', https)
# verify can be a Boolean or a String
if isinstance(verify, bool):
s.verify = verify
elif isinstance(verify, unicode) or isinstance(verify, str):
if verify.lower() == 'true' or verify.lower() == 'false':
s.verify = self.builtin.convert_to_boolean(verify)
else:
# not a Boolean nor a String
s.verify = verify
# cant pass these into the Session anymore
self.timeout = float(timeout) if timeout is not None else None
self.cookies = cookies
self.verify = verify
s.url = url
# Enable http verbosity
if debug >= 1:
self.debug = int(debug)
httplib.HTTPConnection.debuglevel = self.debug
self._cache.register(session, alias=alias)
return session
def create_session(self, alias, url, headers={}, cookies=None,
#.........这里部分代码省略.........
示例3: RequestsKeywords
# 需要导入模块: from robot.libraries.BuiltIn import BuiltIn [as 别名]
# 或者: from robot.libraries.BuiltIn.BuiltIn import convert_to_boolean [as 别名]
class RequestsKeywords(object):
ROBOT_LIBRARY_SCOPE = 'Global'
def __init__(self):
self._cache = robot.utils.ConnectionCache('No sessions created')
self.builtin = BuiltIn()
def _utf8_urlencode(self, data):
if type(data) is unicode:
return data.encode('utf-8')
if not type(data) is dict:
return data
utf8_data = {}
for k,v in data.iteritems():
utf8_data[k] = unicode(v).encode('utf-8')
return urlencode(utf8_data)
def _create_session(self, alias, url, headers, cookies, auth,
timeout, proxies, verify):
""" Create Session: create a HTTP session to a server
`url` Base url of the server
`alias` Robot Framework alias to identify the session
`headers` Dictionary of default headers
`auth` List of username & password for HTTP Basic Auth
`timeout` connection timeout
`proxies` proxy server url
`verify` set to True if Requests should verify the certificate
"""
self.builtin.log('Creating session: %s' % alias, 'DEBUG')
s = session = requests.Session()
s.headers.update(headers)
s.auth = auth if auth else s.auth
s.proxies = proxies if proxies else s.proxies
s.verify = self.builtin.convert_to_boolean(verify)
# cant pass these into the Session anymore
self.timeout = timeout
self.cookies = cookies
self.verify = verify
# cant use hooks :(
s.url = url
self._cache.register(session, alias=alias)
return session
def create_session(self, alias, url, headers={}, cookies=None,
auth=None, timeout=None, proxies=None,
verify=False):
""" Create Session: create a HTTP session to a server
`url` Base url of the server
`alias` Robot Framework alias to identify the session
`headers` Dictionary of default headers
`auth` List of username & password for HTTP Basic Auth
`timeout` connection timeout
`proxies` proxy server url
`verify` set to True if Requests should verify the certificate
"""
auth = requests.auth.HTTPBasicAuth(*auth) if auth else None
return self._create_session(alias, url, headers, cookies, auth,
timeout, proxies, verify)
def create_ntlm_session(self, alias, url, auth, headers={}, cookies=None,
timeout=None, proxies=None, verify=False):
""" Create Session: create a HTTP session to a server
`url` Base url of the server
`alias` Robot Framework alias to identify the session
`headers` Dictionary of default headers
`auth` ['DOMAIN', 'username', 'password'] for NTLM Authentication
`timeout` connection timeout
`proxies` proxy server url
#.........这里部分代码省略.........
示例4: RestKeywords
# 需要导入模块: from robot.libraries.BuiltIn import BuiltIn [as 别名]
# 或者: from robot.libraries.BuiltIn.BuiltIn import convert_to_boolean [as 别名]
class RestKeywords(object):
def __init__(self):
self._cache = ConnectionCache()
self._builtin = BuiltIn()
@staticmethod
def _normalize(d):
if type(d) is dict:
return dict((k, RestKeywords._normalize(v)) for k, v in d.iteritems() if v and RestKeywords._normalize(v))
elif type(d) is list:
return [RestKeywords._normalize(v) for v in d if v and RestKeywords._normalize(v)]
else:
return d
@staticmethod
def convert_to_json(strings, normalize="False"):
if type(strings) is list:
json_ = map(lambda s: json.loads(s), strings)
else:
json_ = json.loads(strings)
if normalize.upper() == "TRUE":
if type(json_) is list:
json_ = map(lambda x: RestKeywords._normalize(x), json_)
else:
json_ = RestKeywords._normalize(json_)
return json_
@staticmethod
def convert_to_multipart_encoded_files(files):
mpe_files = []
for f in files:
form_field_name = f[0]
file_name = path.basename(f[1])
file_path = f[1]
mime_type = f[2]
mpe_files.append((form_field_name, (file_name, open(file_path, "rb"), mime_type)))
return mpe_files
def create_session(self, alias, headers=None, auth=None, verify="False", cert=None):
session = Session()
if headers:
session.headers.update(headers)
if auth:
session.auth = tuple(auth)
session.verify = self._builtin.convert_to_boolean(verify)
session.cert = cert
self._cache.register(session, alias)
def head(self, alias, url, params=None, headers=None, cookies=None, timeout=10):
logger.info("Sending HEAD request to: '" + url + "', session: '" + alias + "'")
session = self._cache.switch(alias)
resp = session.head(url, params=params, headers=headers, cookies=cookies, timeout=timeout)
return {"status": resp.status_code, "headers": resp.headers}
def get(self, alias, url, params=None, headers=None, cookies=None, timeout=10):
logger.info("Sending GET request to: '" + url + "', session: '" + alias + "'")
session = self._cache.switch(alias)
resp = session.get(url, params=params, headers=headers, cookies=cookies, timeout=timeout)
try:
return {"status": resp.status_code, "headers": resp.headers, "body": resp.json()}
except ValueError:
return {"status": resp.status_code, "headers": resp.headers, "body": resp.content}
def post(self, alias, url, headers=None, data=None, files=None, cookies=None, timeout=10):
logger.info("Sending POST request to: '" + url + "', session: '" + alias + "'")
session = self._cache.switch(alias)
resp = session.post(url, headers=headers, cookies=cookies, data=data.encode("utf-8"), files=files, timeout=timeout)
try:
return {"status": resp.status_code, "headers": resp.headers, "body": resp.json()}
except ValueError:
return {"status": resp.status_code, "headers": resp.headers, "body": resp.content}
def put(self, alias, url, headers=None, data=None, cookies=None, timeout=10):
logger.info("Sending PUT request to: '" + url + "', session: '" + alias + "'")
session = self._cache.switch(alias)
resp = session.put(url, headers=headers, cookies=cookies, data=data.encode("utf-8"), timeout=timeout)
try:
return {"status": resp.status_code, "headers": resp.headers, "body": resp.json()}
except ValueError:
return {"status": resp.status_code, "headers": resp.headers, "body": resp.content}
def delete(self, alias, url, headers=None, data=None, cookies=None, timeout=10):
logger.info("Sending DELETE request to: '" + url + "', session: '" + alias + "'")
session = self._cache.switch(alias)
resp = session.delete(url, headers=headers, cookies=cookies, data=data.encode("utf-8"), timeout=timeout)
try:
return {"status": resp.status_code, "headers": resp.headers, "body": resp.json()}
except ValueError:
return {"status": resp.status_code, "headers": resp.headers, "body": resp.content}
def close_all_sessions(self):
self._cache.empty_cache()
示例5: RequestsKeywords
# 需要导入模块: from robot.libraries.BuiltIn import BuiltIn [as 别名]
# 或者: from robot.libraries.BuiltIn.BuiltIn import convert_to_boolean [as 别名]
#.........这里部分代码省略.........
s.headers.update(headers)
s.auth = auth if auth else s.auth
s.proxies = proxies if proxies else s.proxies
try:
max_retries = int(max_retries)
except ValueError as err:
raise ValueError("Error converting max_retries parameter: %s" % err)
if max_retries > 0:
http = requests.adapters.HTTPAdapter(max_retries=Retry(total=max_retries, backoff_factor=backoff_factor))
https = requests.adapters.HTTPAdapter(max_retries=Retry(total=max_retries, backoff_factor=backoff_factor))
# Replace the session's original adapters
s.mount('http://', http)
s.mount('https://', https)
# Disable requests warnings, useful when you have large number of testcase
# you will observe drastical changes in Robot log.html and output.xml files size
if disable_warnings:
logging.basicConfig() # you need to initialize logging, otherwise you will not see anything from requests
logging.getLogger().setLevel(logging.ERROR)
requests_log = logging.getLogger("requests")
requests_log.setLevel(logging.ERROR)
requests_log.propagate = True
if not verify:
requests.packages.urllib3.disable_warnings()
# verify can be a Boolean or a String
if isinstance(verify, bool):
s.verify = verify
elif isinstance(verify, str) or isinstance(verify, unicode):
if verify.lower() == 'true' or verify.lower() == 'false':
s.verify = self.builtin.convert_to_boolean(verify)
else:
# String for CA_BUNDLE, not a Boolean String
s.verify = verify
else:
# not a Boolean nor a String
s.verify = verify
# cant pass these into the Session anymore
self.timeout = float(timeout) if timeout is not None else None
self.cookies = cookies
self.verify = verify if self.builtin.convert_to_boolean(verify) != True else None
s.url = url
# Enable http verbosity
if int(debug) >= 1:
self.debug = int(debug)
httplib.HTTPConnection.debuglevel = self.debug
self._cache.register(session, alias=alias)
return session
def create_session(self, alias, url, headers={}, cookies={},
auth=None, timeout=None, proxies=None,
verify=False, debug=0, max_retries=3, backoff_factor=0.10, disable_warnings=0):
""" Create Session: create a HTTP session to a server
``url`` Base url of the server
``alias`` Robot Framework alias to identify the session
``headers`` Dictionary of default headers
示例6: DiffKeywords
# 需要导入模块: from robot.libraries.BuiltIn import BuiltIn [as 别名]
# 或者: from robot.libraries.BuiltIn.BuiltIn import convert_to_boolean [as 别名]
#.........这里部分代码省略.........
self.builtin.fail(output)
else:
if diff_func == '_getdiff':
if rc == 2 or len(lines) == 1:
self.builtin.fail(output)
# remove the temp file afterwards
if tempfile: os.remove(tempfile.name)
# filter the diff output
if filter: lines = filter(output.splitlines())
# if there is no differences there will still be some lines remaining
# because the filter will remove the timestap diff's
lines_to_skip = diff_lines.get(diff_func, '_getdiff')
if lines and len(lines) > lines_to_skip:
print('\n'.join(lines))
self.builtin.fail(
"differences found between %s and %s" % (actfile, reffile))
def diff_files(self, file1, file2, fail=True):
''' Diff two text files
``file1``: absolute path to the first first file
``file2``: absolute path to the first second file
``fail``: If there are differences it will throw an exception and
test will fail defaults to True, if False test's will continue
'''
self.builtin.log("file1: %s" %file1)
self.builtin.log("file2: %s" %file2)
fail = self.builtin.convert_to_boolean(fail)
if fail:
self._newdiff(file1, file2)
else:
try:
self._newdiff(file1, file2)
except Exception as e:
self.builtin.log(e)
def _run(self, cmd):
''' internal run command '''
if not cmd: return
self.builtin.log(cmd)
#cmd = process_cmd(cmd)
# run the given command in a child shell process
# (cmd.exe on win and sh/bash on *nix)
self.cmd = subprocess.Popen(cmd + ' 2>&1', shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
# it will block here and try to read everything into memory
output = self.cmd.communicate()[0]
if PY3:
if isinstance(output, bytes):
output = output.decode(encoding='utf-8')
return output, self.cmd.wait()
def diff_outputs(self, text1, text2, fail=True):
''' Diff between target and source texts
``text1``: Target output
``text2``: Source output
``fail``: If there are differences it will throw an exception and
test will fail defaults to True, if False test's will continue
'''
file1 = tempfile.NamedTemporaryFile(mode='w', suffix='.txt',
delete=False)
file1.write(text1)
file1.close()
file2 = tempfile.NamedTemporaryFile(mode='w', suffix='.txt',
delete=False)
file2.write(text2)
file2.close()
self.builtin.log("file1: %s" % file1.name)
self.builtin.log("file2: %s" % file2.name)
fail = self.builtin.convert_to_boolean(fail)
if fail:
self._newdiff(file1.name, file2.name)
else:
try:
self._newdiff(file1, file2)
except Exception as e:
self.builtin.log(e)
os.remove(file1.name)
os.remove(file2.name)
示例7: RequestsKeywords
# 需要导入模块: from robot.libraries.BuiltIn import BuiltIn [as 别名]
# 或者: from robot.libraries.BuiltIn.BuiltIn import convert_to_boolean [as 别名]
class RequestsKeywords(object):
ROBOT_LIBRARY_SCOPE = 'Global'
def __init__(self):
self._cache = robot.utils.ConnectionCache('No sessions created')
self.builtin = BuiltIn()
def _utf8_urlencode(self, data):
if type(data) is unicode:
return data.encode('utf-8')
if not type(data) is dict:
return data
utf8_data = {}
for k,v in data.iteritems():
utf8_data[k] = unicode(v).encode('utf-8')
return urlencode(utf8_data)
def _create_session(self, alias, url, headers, cookies, auth,
timeout, proxies, verify):
""" Create Session: create a HTTP session to a server
`url` Base url of the server
`alias` Robot Framework alias to identify the session
`headers` Dictionary of default headers
`auth` List of username & password for HTTP Basic Auth
`timeout` connection timeout
`proxies` proxy server url
`verify` set to True if Requests should verify the certificate
"""
self.builtin.log('Creating session: %s' % alias, 'DEBUG')
s = session = requests.Session()
s.headers.update(headers)
s.auth = auth if auth else s.auth
s.proxies = proxies if proxies else s.proxies
s.verify = self.builtin.convert_to_boolean(verify)
# cant pass these into the Session anymore
self.timeout = timeout
self.cookies = cookies
self.verify = verify
# cant use hooks :(
s.url = url
self._cache.register(session, alias=alias)
return session
def create_session(self, alias, url, headers={}, cookies=None,
auth=None, timeout=None, proxies=None,
verify=False):
""" Create Session: create a HTTP session to a server
`url` Base url of the server
`alias` Robot Framework alias to identify the session
`headers` Dictionary of default headers
`auth` List of username & password for HTTP Basic Auth
`timeout` connection timeout
`proxies` proxy server url
`verify` set to True if Requests should verify the certificate
"""
auth = requests.auth.HTTPBasicAuth(*auth) if auth else None
return self._create_session(alias, url, headers, cookies, auth,
timeout, proxies, verify)
def create_ntlm_session(self, alias, url, auth, headers={}, cookies=None,
timeout=None, proxies=None, verify=False):
""" Create Session: create a HTTP session to a server
`url` Base url of the server
`alias` Robot Framework alias to identify the session
`headers` Dictionary of default headers
`auth` ['DOMAIN', 'username', 'password'] for NTLM Authentication
`timeout` connection timeout
`proxies` proxy server url
#.........这里部分代码省略.........
示例8: RequestsKeywords
# 需要导入模块: from robot.libraries.BuiltIn import BuiltIn [as 别名]
# 或者: from robot.libraries.BuiltIn.BuiltIn import convert_to_boolean [as 别名]
class RequestsKeywords(object):
ROBOT_LIBRARY_SCOPE = 'Global'
def __init__(self):
self._cache = robot.utils.ConnectionCache('No sessions created')
self.builtin = BuiltIn()
def _utf8_urlencode(self, data):
if type(data) is unicode:
return data.encode('utf-8')
if not type(data) is dict:
return data
utf8_data = {}
for k,v in data.iteritems():
utf8_data[k] = unicode(v).encode('utf-8')
return urlencode(utf8_data)
def _create_session(self, alias, url, headers, cookies, auth,
timeout, proxies, verify):
""" Create Session: create a HTTP session to a server
`url` Base url of the server
`alias` Robot Framework alias to identify the session
`headers` Dictionary of default headers
`auth` List of username & password for HTTP Basic Auth
`timeout` connection timeout
`proxies` proxy server url
`verify` set to True if Requests should verify the certificate
"""
self.builtin.log('Creating session: %s' % alias, 'DEBUG')
s = session = requests.Session()
s.headers.update(headers)
s.auth = auth if auth else s.auth
s.proxies = proxies if proxies else s.proxies
s.verify = self.builtin.convert_to_boolean(verify)
# cant pass these into the Session anymore
self.timeout = timeout
self.cookies = cookies
self.verify = verify
# cant use hooks :(
s.url = url
self._cache.register(session, alias=alias)
return session
def create_session(self, alias, url, headers={}, cookies=None,
auth=None, timeout=None, proxies=None,
verify=False):
""" Create Session: create a HTTP session to a server
`url` Base url of the server
`alias` Robot Framework alias to identify the session
`headers` Dictionary of default headers
`auth` List of username & password for HTTP Basic Auth
`timeout` connection timeout
`proxies` proxy server url
`verify` set to True if Requests should verify the certificate
"""
auth = requests.auth.HTTPBasicAuth(*auth) if auth else None
return self._create_session(alias, url, headers, cookies, auth,
timeout, proxies, verify)
def create_ntlm_session(self, alias, url, auth, headers={}, cookies=None,
timeout=None, proxies=None, verify=False):
""" Create Session: create a HTTP session to a server
`url` Base url of the server
`alias` Robot Framework alias to identify the session
`headers` Dictionary of default headers
`auth` ['DOMAIN', 'username', 'password'] for NTLM Authentication
`timeout` connection timeout
`proxies` proxy server url
#.........这里部分代码省略.........
示例9: SOAP
# 需要导入模块: from robot.libraries.BuiltIn import BuiltIn [as 别名]
# 或者: from robot.libraries.BuiltIn.BuiltIn import convert_to_boolean [as 别名]
class SOAP(object):
def __init__(self):
self._xml = XML()
self._builtin = BuiltIn()
self._cache = ConnectionCache()
def create_soap_client(self, alias, wsdl=None, endpoint=None):
"""
Creates SOAP client with specified alias.
Arguments:
| alias | client alias |
| wsdl | path or url to service wsdl |
| endpoint | url for service under test |
Example usage:
| Create Soap Client | client_alias | wsdl=path_to_wsdl${/}ws_example.wsdl | endpoint=http://localhost:8080/ |
"""
session = Session()
session.verify = False
if wsdl:
wsdl = self._get_wsdl(session, wsdl)
client = SOAPClient(session, wsdl, endpoint)
self._cache.register(client, alias)
def call_soap_method(self, alias, name, message, replace=None, endpoint=None, expect_fault=False, xml=True):
"""
Call SOAP method.
Arguments:
| alias | client alias |
| name | method name |
| message | path to SOAP message or SOAP message |
| replace | dictionary of old_value: new_value pairs for replace in message |
| endpoint | url for service under test, rewrites client endpoint |
| expect_fault | if True, not raise exception when receive fault |
| xml | return type, if True - return xml object (XML library format), False - string |
Example usage:
| ${replace} | Create Dictionary | _id_ | 64 |
| ${response} | Call Soap Method | client_alias | getUserName | path_to_soap_message${/}example.xml | replace=${replace} | expect_fault=False | xml=True |
| Element Should Exist | ${response} | .//{http://www.example.ru/example}requestResult |
"""
client = self._cache.switch(alias)
if endpoint:
client.endpoint = endpoint
try:
ET.fromstring(message)
except ET.ParseError:
if not path.isfile(message):
raise IOError("File not found or message is not well-formed" % message)
message = open(message, mode="r", encoding="utf-8").read()
if replace:
for k, v in replace.items():
message = message.replace(k, v)
status_code, response = self._call(client, name, message)
expect_fault = self._builtin.convert_to_boolean(expect_fault)
is_fault = self._is_fault(status_code)
if is_fault and not expect_fault:
raise AssertionError("The server did not raise a fault")
elif expect_fault and not is_fault:
raise AssertionError("The server not raise a fault")
if self._builtin.convert_to_boolean(xml):
return self._xml.parse_xml(response, keep_clark_notation=True)
else:
return response
@staticmethod
def _get_wsdl(session, url_or_path):
if not urlparse(url_or_path).scheme:
if not path.isfile(url_or_path):
raise IOError("File '%s' not found" % url_or_path)
wsdl = open(url_or_path, mode="r", encoding="utf-8").read()
else:
response = session.get(url_or_path)
if response.status_code != 200:
raise ConnectionError("Server not found or resource '%s' is not available" % url_or_path)
wsdl = response.content.decode("utf-8")
return wsdl
@staticmethod
def _is_fault(status_code):
if status_code == 200:
return False
else:
return True
def _get_soap_action(self, wsdl, name):
root = self._xml.parse_xml(wsdl)
xpath = ".//*[@name='%s']/operation" % name
return self._xml.get_element_attribute(root, "soapAction", xpath=xpath)
def _call(self, client, name, message):
if client.wsdl:
action = self._get_soap_action(client.wsdl, name)
else:
action = ""
headers = {"Accept-Encoding": "gzip,deflate", "Content-Type": "text/xml;charset=UTF-8",
"Connection": "Keep-Alive", "SOAPAction": action}
#.........这里部分代码省略.........
示例10: RequestsKeywords
# 需要导入模块: from robot.libraries.BuiltIn import BuiltIn [as 别名]
# 或者: from robot.libraries.BuiltIn.BuiltIn import convert_to_boolean [as 别名]
class RequestsKeywords(object):
ROBOT_LIBRARY_SCOPE = "Global"
def __init__(self):
self._cache = robot.utils.ConnectionCache("No sessions created")
self.builtin = BuiltIn()
self.debug = 0
self.mretries = 0
self.mdelay = 0.0
self.mbackoff = 0.0
def _utf8_urlencode(self, data):
if type(data) is unicode:
return data.encode("utf-8")
if not type(data) is dict:
return data
utf8_data = {}
for k, v in data.iteritems():
utf8_data[k] = unicode(v).encode("utf-8")
return urlencode(utf8_data)
def _create_session(
self, alias, url, headers, cookies, auth, timeout, proxies, verify, debug, max_retries, max_delay, max_backoff
):
""" Create Session: create a HTTP session to a server
`url` Base url of the server
`alias` Robot Framework alias to identify the session
`headers` Dictionary of default headers
`auth` List of username & password for HTTP Basic Auth
`timeout` connection timeout
`proxies` Dictionary that contains proxy urls for HTTP and HTTPS communication
`verify` set to True if Requests should verify the certificate
`debug` enable http verbosity option more information
https://docs.python.org/2/library/httplib.html#httplib.HTTPConnection.set_debuglevel
`max_retries` The maximum number of retries each connection should attempt.
`max_delay` The maximum number of delay each connection should attempt.
"""
# Type casting since robot vars unicode
self.mretries = int(max_retries)
self.mdelay = float(max_delay)
self.mbackoff = float(max_backoff)
self.builtin.log("Creating session: %s" % alias, "DEBUG")
s = session = requests.Session()
s.headers.update(headers)
s.auth = auth if auth else s.auth
s.proxies = proxies if proxies else s.proxies
s.verify = self.builtin.convert_to_boolean(verify)
# cant pass these into the Session anymore
self.timeout = timeout
self.cookies = cookies
self.verify = verify
# cant use hooks :(
self.host = urlparse.urlparse(url).netloc
s.url = url
# Enable http verbosity
if debug >= 1:
self.debug = int(debug)
httplib.HTTPConnection.debuglevel = self.debug
self._cache.register(session, alias=alias)
return session
def create_session(
self,
alias,
url,
headers={},
cookies=None,
auth=None,
timeout=None,
proxies=None,
verify=False,
debug=0,
max_retries=3,
max_delay=1.0,
max_backoff=0.10,
):
""" Create Session: create a HTTP session to a server
`url` Base url of the server
#.........这里部分代码省略.........
示例11: DiffKeywords
# 需要导入模块: from robot.libraries.BuiltIn import BuiltIn [as 别名]
# 或者: from robot.libraries.BuiltIn.BuiltIn import convert_to_boolean [as 别名]
#.........这里部分代码省略.........
#save_md5_hashes = False
#try:
# save_md5_hashes = self.builtin.replace_variables('${SAVE_MD5_HASH}')
#except:
# pass
## write out the md5sum to the correct file ?
#if self.builtin.convert_to_boolean(save_md5_hashes):
# try:
# fmd5 = open(act_md5, 'w')
# # have we already calculated md5 hash ?
# if not new_md5hash:
# new_md5hash, rc = self._run(md5_cmd)
# if new_md5hash[0] == '\\': new_md5hash = new_md5hash[1:]
# fmd5.write(new_md5hash)
# fmd5.close()
# except Exception, e:
# print "*WARN*: Failed to create md5 file"
# print "*INFO* "
# raise
## reference md5 hash file exists
#if os.path.exists(act_md5):
# ref_md5hash = open(act_md5).read().split()[0]
# if not new_md5hash: new_md5hash, rc = self._run(md5_cmd)
# if new_md5hash[0] == '\\': new_md5hash = new_md5hash[1:]
# # md5 hashes match no need to do the diff
# if ref_md5hash == new_md5hash.split()[0]:
# print 'md5 hashes match\n%s\n%s' %(ref_md5hash, new_md5hash.split()[0])
# return
# the reference file is gzip'ed
tempfile = None
#if reffile.endswith('gz'):
# # unzip the gzip file into a temporary file
# tempfile = NamedTemporaryFile(delete=False, dir=self.get_temp_dir())
# for l in gzip.open(reffile).readlines():
# tempfile.write(l.replace('\r\n', '\n'))
# tempfile.close()
# print "tempfile: ", tempfile.name
# reffile = tempfile.name
# construct the diff command
diff_function = diff_types.get(diff_func, '_getdiff')
if diff_params != None:
diff_cmd = '%s %s "%s" "%s"' %(diff_function(), diff_params, actfile, reffile)
else:
diff_cmd = '%s "%s" "%s"' %(diff_function(), actfile, reffile)
output, rc = self._run(diff_cmd)
lines = output.splitlines()
# code 127 shows that shell hasn't found the command
if rc == 127:
self.builtin.fail(output)
else:
if diff_func == '_getdiff':
if rc == 2 or len(lines) == 1:
self.builtin.fail(output)
# remove the temp file afterwards
if tempfile: os.remove(tempfile.name)
# filter the diff output
if filter: lines = filter(output.splitlines())
# if there is no differences there will still be some lines remaining
# because the filter will remove the timestap diff's
lines_to_skip = diff_lines.get(diff_func, '_getdiff')
if lines and len(lines) > lines_to_skip:
print '\n'.join(lines)
self.builtin.fail("differences found between %s and %s" %(actfile, reffile))
def diff_files(self, file1, file2, fail=True):
''' Diff two text files
`file1`: absolute path to the first first file
`file2`: absolute path to the first second file
`fail`: If there are differences it will throw an exception and test will fail
defaults to True, if False test's will continue '''
self.builtin.log("file1: %s" %file1)
self.builtin.log("file2: %s" %file2)
fail = self.builtin.convert_to_boolean(fail)
if fail:
self._newdiff(file1, file2)
else:
try:
self._newdiff(file1, file2)
except Exception, e:
self.builtin.log(e)
示例12: RestKeywords
# 需要导入模块: from robot.libraries.BuiltIn import BuiltIn [as 别名]
# 或者: from robot.libraries.BuiltIn.BuiltIn import convert_to_boolean [as 别名]
class RestKeywords():
ROBOT_LIBRARY_SCOPE = 'Global'
def __init__(self):
self._cache = robot.utils.ConnectionCache(u'未创建Sessions')
self.builtin = BuiltIn()
def _utf8_urlencode(self, data):
if isinstance(data, unicode):
return data.encode('utf-8')
if not isinstance(data, dict):
return data
utf8_data = {}
for k, v in data.iteritems():
utf8_data[k] = unicode(v).encode('utf-8')
return urlencode(utf8_data)
def _create_session(self, alias, url, headers, cookies,
auth, timeout, proxies, verify):
""" Create Session: 创建一个连接server的HTTP会话
`url` 服务器基本的URL地址
`alias` Robot Framework 对当前创建的HTTP会话指定的别名
`headers` 默认的headers字典
`auth` 对于HTTP基本身份验证词典的用户名和密码
`timeout` 连接超时
`proxies` 代理服务器URL
`verify` 如果请求验证证书,该值设置为True
"""
self.builtin.log(u'创建Session:%s' % alias, 'DEBUG')
session = requests.Session()
session.headers.update(headers)
session.auth = auth if auth else session.auth
session.proxies = proxies if proxies else session.proxies
session.verify = self.builtin.convert_to_boolean(verify)
# 通过传递进入说请求
# cant pass these into the Session anymore
self.timeout = timeout
self.cookies = cookies
self.verify = verify
# cant use hooks:(
session.url = url
self._cache.register(session, alias=alias)
return session
def create_session(self, alias, url, headers={}, cookies=None,
auth=None, timeout=None, proxies=None, verify=False):
""" Create Session: 创建一个连接server的HTTP会话
`url` 服务器基本的URL地址
`alias` Robot Framework 对当前创建的HTTP会话指定的别名
`headers` 默认的headers字典
`auth` 对于HTTP基本身份验证词典的['DOMAIN', '用户名', '密码']
`timeout` 连接超时
`proxies` 代理服务器URL
`verify` 如果请求验证证书,该值设置为True
"""
auth = requests.auth.HTTPBasicAuth(*auth) if auth else None
return self._create_session(alias, url, headers, cookies, auth,
timeout, proxies, verify)
def create_ntln_session(self, alias, url, headers={}, cookies=None,
auth=None, timeout=None, proxies=None, verify=False):
""" Create Session: 创建一个连接server的HTTP会话
`url` 服务器基本的URL地址
`alias` Robot Framework 对当前创建的HTTP会话指定的别名
`headers` 默认的headers字典
`auth` 对于HTTP基本身份验证词典的['DOMAIN', '用户名', '密码']
`timeout` 连接超时
`proxies` 代理服务器URL
#.........这里部分代码省略.........
示例13: keywords
# 需要导入模块: from robot.libraries.BuiltIn import BuiltIn [as 别名]
# 或者: from robot.libraries.BuiltIn.BuiltIn import convert_to_boolean [as 别名]
class keywords(object):
rootDiffDir = os.path.abspath(os.path.join(__file__, '..'))
def __init__(self):
self.builtin = BuiltIn()
def _getdiff(self):
''' returns path to diff depending on platform '''
diff = 'diff --strip-trailing-cr'
if sys.platform[:3] == 'win':
diff = (("%s --strip-trailing-cr ") %
(os.path.join(self.rootDiffDir, 'bin', 'diff.exe')))
return diff
def _newdiff(self, actfile, reffile, diff_params=None,
diff_func='_getdiff'):
''' compare two files
*actfile:* sxv4dump file created in latest build
*reffile:* reference sxv4dump file, gzipped
*diff_cmd:* custom diff command'''
diff_types = {'_getdiff': self._getdiff}
diff_lines = {'_getdiff': 2}
for diffFiles in (actfile, reffile):
if not os.path.exists(diffFiles):
self.builtin.fail("%s doesn't exist" % diffFiles)
# construct the diff command
diff_function = diff_types.get(diff_func, '_getdiff')
if diff_params != None:
diff_cmd = '%s %s "%s" "%s"' % (diff_function(),
diff_params, actfile, reffile)
else:
diff_cmd = '%s "%s" "%s"' % (diff_function(),
actfile, reffile)
output, rc = self._run(diff_cmd)
lines = output.splitlines()
# code 127 shows that shell hasn't found the command
if rc == 127:
self.builtin.fail(output)
else:
if diff_func == '_getdiff':
if rc == 2 or len(lines) == 1:
self.builtin.fail(output)
# if there is no differences there will still be some lines remaining
# because the filter will remove the timestap diff's
lines_to_skip = diff_lines.get(diff_func, '_getdiff')
if lines and len(lines) > lines_to_skip:
print '\n'.join(lines)
self.builtin.fail("differences found between %s and %s" %
(actfile, reffile))
def diff_files(self, file1, file2, diff_params=None, fail=True):
''' Diff two text files
`file1`: absolute path to the first first file
`file2`: absolute path to the first second file
`diff_params`: Parameters that can be passed to the diff program
specific to your OS.
`fail`: If there are differences it will throw an exception and test
will fail defaults to True, if False test's will continue
'''
self.builtin.log("file1: %s" % file1)
self.builtin.log("file2: %s" % file2)
fail = self.builtin.convert_to_boolean(fail)
if fail:
self._newdiff(file1, file2, diff_params)
else:
try:
self._newdiff(file1, file2, diff_params)
except Exception, e:
self.builtin.log(e)
示例14: REST
# 需要导入模块: from robot.libraries.BuiltIn import BuiltIn [as 别名]
# 或者: from robot.libraries.BuiltIn.BuiltIn import convert_to_boolean [as 别名]
class REST(object):
def __init__(self):
self._builtin = BuiltIn()
self._cache = ConnectionCache()
def create_rest_session(self, alias, headers=None, auth=None, verify=False, cert=None):
"""
Creates REST session with specified alias.
Arguments:
| alias | session alias |
| headers | custom headers for all requests |
| auth | basic auth |
| verify | SSL verification |
| cert | path to SSL certificate file |
Example usage:
| ${headers} | Create Dictionary | Content-Type | application/json |
| @{service_basic_auth} | Set Variable | username | password |
| Create Rest Session | session_alias | headers=${headers} | auth=${service_basic_auth} | verify=False |
"""
session = Session()
if headers:
session.headers.update(headers)
if auth:
session.auth = tuple(auth)
session.verify = self._builtin.convert_to_boolean(verify)
session.cert = cert
self._cache.register(session, alias)
def head(self, alias, url, params=None, headers=None, cookies=None, timeout=10):
"""
Sends HEAD request.
Arguments:
| alias | session alias |
| url | service url |
| params | request parameters |
| headers | custom headers for request, rewrites session headers |
| cookies | custom request cookies |
| timeout | response timeout in seconds, raise exception on request timeout |
Example usage:
| ${payload} | Create Dictionary | param1 | value1 | param2 | value2 |
| ${cookies} | Create Dictionary | sessionid | session12345 |
| ${response} | Head | session_alias | http://localhost/service | params=${payload} | cookies=${cookies} | timeout=5 |
"""
logger.info("Sending HEAD request to: '%s', session: '%s'" % (url, alias))
session = self._cache.switch(alias)
response = session.head(url, params=params, headers=headers, cookies=cookies, timeout=int(timeout))
return {"status": response.status_code, "headers": response.headers}
def get(self, alias, url, params=None, headers=None, cookies=None, timeout=10):
"""
Sends GET request. See arguments description in `Head` keyword.
"""
logger.info("Sending GET request to: '%s', session: '%s'" % (url, alias))
session = self._cache.switch(alias)
response = session.get(url, params=params, headers=headers, cookies=cookies, timeout=int(timeout))
try:
return {"status": response.status_code, "headers": response.headers, "body": response.json()}
except ValueError:
return {"status": response.status_code, "headers": response.headers, "body": response.content}
def post(self, alias, url, headers=None, cookies=None, data=None, files=None, timeout=10):
"""
Sends POST request.
Arguments:
| alias | session alias |
| url | service url |
| headers | custom headers for request, rewrites session headers |
| cookies | custom request cookies |
| data | dictionary, bytes, or file-like object to send in the body of the request |
| files | dictionary of 'name': file-like-objects (or {'name': ('filename', fileobj)}) for multipart encoding upload |
| timeout | response timeout in seconds, raise exception on request timeout |
Example usage:
| @{files} | Set Variable | path_to_file_1 | path_to_file_2 |
| ${mpe_files} | Convert To Multipart Encoded Files | ${files} |
| ${payload} | Set Variable | {"id": "34","doc_type": "history"} |
| ${response} | Post | service_alias | http://localhost/service | data=${payload} |
| ${response} | Post | service_alias | http://localhost/service | files=${mpe_files} |
"""
logger.info("Sending POST request to: '%s', session: '%s'" % (url, alias))
session = self._cache.switch(alias)
response = session.post(url, headers=headers, cookies=cookies, data=data.encode("utf-8"), files=files,
timeout=int(timeout))
try:
return {"status": response.status_code, "headers": response.headers, "body": response.json()}
except ValueError:
return {"status": response.status_code, "headers": response.headers, "body": response.content}
def put(self, alias, url, headers=None, data=None, cookies=None, timeout=10):
"""
Sends PUT request. See arguments description in `Post` keyword.
"""
logger.info("Sending PUT request to: '%s', session: '%s'" % (url, alias))
session = self._cache.switch(alias)
#.........这里部分代码省略.........