Package tlib :: Package base :: Module TestHelper
[hide private]
[frames] | no frames]

Source Code for Module tlib.base.TestHelper

  1  import os 
  2  import socket 
  3  import subprocess 
  4  import pytest 
  5  import logging 
  6  import json 
  7  import tempfile 
  8  from glob import glob 
  9  from requests.models import Response 
 10   
11 -class Singleton(type):
12 _instances = {}
13 - def __call__(cls, *args, **kwargs):
14 if cls not in cls._instances: 15 cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs) 16 return cls._instances[cls]
17 18
19 -def tlib_folder():
20 """ 21 Returns tlib's absolute path 22 """ 23 file_folder = os.path.dirname(__file__) 24 return os.path.abspath(os.path.join(file_folder, os.pardir))
25 26
27 -def tlib_asset_folder():
28 """ 29 Returns absolute path of tlib's asset folder 30 """ 31 return os.path.abspath(os.path.join(tlib_folder(), "asset"))
32 33
34 -def tlib_modules_folder():
35 """ 36 Returns absolute path of folder containing all modules 37 """ 38 return os.path.abspath(os.path.join(tlib_folder(), "base"))
39 40
41 -def tlib_config_folder():
42 """ 43 Returns absolute path of tlib's config folder 44 """ 45 return os.path.abspath(os.path.join(tlib_folder(), "config"))
46 47
48 -def tlib_template_folder():
49 """ 50 Returns absolute path of tlib's template folder\n 51 Template folder contains jinja templates used for generation of reports\n 52 like screenshots 53 """ 54 return os.path.abspath(os.path.join(tlib_folder(), "templates"))
55 56
57 -def webdriver_chrome_executable(version="latest"):
58 """ 59 Returns path to Chrome WebDriver executable 60 """ 61 if version == "latest": 62 #Find all cromedriver files and sort by filename 63 path = os.path.join(tlib_asset_folder(), "selenium", "chromedriver_*.exe") 64 r = sorted(glob(path)) 65 return os.path.join(tlib_asset_folder(), "selenium", r[-1]) 66 else: 67 return os.path.join(tlib_asset_folder(), "selenium", "chromedriver_%s.exe" % version)
68 69
70 -def webdriver_ie_executable():
71 """ 72 Alias for webdriver_ie32_executable 73 """ 74 return webdriver_ie32_executable();
75 76
77 -def webdriver_ie32_executable():
78 """ 79 Returns path to IE WebDriver executable 80 """ 81 return os.path.join(tlib_asset_folder(), "selenium", "IE", "2.41.0", "Win32", "IEDriverServer.exe")
82
83 -def webdriver_ie64_executable():
84 """ 85 Returns path to IE WebDriver executable 86 """ 87 return os.path.join(tlib_asset_folder(), "selenium", "IE", "2.41.0", "x64", "IEDriverServer.exe")
88
89 -def android_server_apk():
90 """ 91 Returns path to Webdriver for android 92 """ 93 return os.path.join(tlib_asset_folder(), "selenium", "android-server-2.21.0.apk")
94 95
96 -def selendroid_server_jar():
97 """ 98 Returns path to selendroid jar for android native app 99 """ 100 return os.path.join(tlib_asset_folder(), "selenium", "selendroid-standalone-0.9.0-with-dependencies.jar")
101 102
103 -def is_valid_ip(ip):
104 """ 105 Returns true if IP parameter is a valid IP address.\n 106 Currently IPs in this format are valid:\n 107 X.X.X.X\n 108 X.X.X.X:PORT 109 110 @type ip: str 111 @return: bool 112 """ 113 114 if ip is None: 115 return False 116 117 try: 118 (ip, port) = ip.split(":", 1) 119 except ValueError: 120 #There is no ':' in the string 121 port = None 122 123 try: 124 socket.inet_aton(ip) 125 except socket.error: 126 return False 127 128 if port is not None: 129 try: 130 return (int(port) >= 1) and (int(port) <= 65535) 131 except ValueError: 132 #Not a valid integer 133 return False 134 135 return True
136
137 -def run_command(logger, command, shell=False, fail_on_error=True):
138 """ 139 Run a command and skip test if exit code is not 0 140 141 Example: 142 Run 'adb devices' and don't skip test if commands returns non-zero status 143 run_command(logger, ["adb", "devices"], fail_on_error=False) 144 145 @param logger: logger for debugging purposes 146 @type logger: logging.Logger 147 @param command: Command to run 148 @type command: list 149 @param fail_on_error: When True, skip test if command returned a non-zero exit code 150 @type fail_on_error: bool 151 @rtype: list 152 @return: Returns a list with stdout and stderr output 153 """ 154 155 fd_out = tempfile.NamedTemporaryFile(delete=True) 156 #With delete = True option, the files will be automatically removed after close 157 fd_err = tempfile.NamedTemporaryFile(delete=True) 158 try: 159 process = subprocess.Popen(command, shell=shell, stdout=fd_out, stderr=fd_err) 160 except WindowsError as e: 161 logger.error(r"Problem running command, skipping test.\n%s" % e) 162 # noinspection PyUnresolvedReferences 163 if fail_on_error: 164 pytest.fail(r"Problem running command, skipping test.\n%s" % e) 165 166 # noinspection PyUnboundLocalVariable 167 process.communicate() 168 fd_out.seek(0) 169 fd_err.seek(0) 170 out = (fd_out.read(), fd_err.read()) 171 fd_out.close() 172 fd_err.close() 173 errcode = process.returncode 174 175 if (errcode != 0) and fail_on_error: 176 logger.error(r"Program exited with code {errcode}, skipping test\n{out}".format(errcode=errcode, out=out)) 177 # noinspection PyUnresolvedReferences 178 pytest.fail(r"Program exited with code {errcode}, skipping test\n{out}".format(errcode=errcode, out=out)) 179 180 return out
181 182
183 -def start_process(logger, command, shell=False):
184 """ 185 Run a command and skip test if exit code is not 0 186 187 Example: 188 Run 'adb devices' and don't skip test if commands returns non-zero status 189 run_command(logger, ["adb", "devices"], fail_on_error=False) 190 191 @param logger: logger for debugging purposes 192 @type logger: logging.Logger 193 @param command: Command to run 194 @type command: list 195 @param fail_on_error: When True, skip test if command returned a non-zero exit code 196 @type fail_on_error: bool 197 @rtype: list 198 @return: Returns a list with stdout and stderr output 199 """ 200 201 try: 202 process = subprocess.Popen(command, shell=shell) 203 except WindowsError as e: 204 logger.error(r"Problem running command, skipping test.\n%s" % e) 205 # noinspection PyUnresolvedReferences 206 return process
207
208 -def sort_list(l):
209 """ 210 Sorts a list, and if the list has other objects inside, it will iterate over them 211 @param l: list to sort 212 @type l: list 213 @return: sorted list 214 @rtype: list 215 """ 216 if type(l) is not list: 217 pytest.fail("Parameter l is not a list") 218 219 for i, s in enumerate(l): 220 if type(s) is list: 221 l[i] = sort_list(s) 222 if type(s) is dict: 223 l[i] = sort_dict(s) 224 225 l.sort() 226 227 return l
228 229
230 -def sort_dict(d):
231 """ 232 Sorts a dictionary, and if the list has other objects inside, it will iterate over them 233 @param d: dictionary to sort 234 @type d: dict 235 @return: sorted dictionary 236 @rtype: dict 237 """ 238 if type(d) is not dict: 239 pytest.fail("Parameter d is not a dictionary") 240 241 for key in d.keys(): 242 if type(d[key]) is list: 243 #Sort list 244 d[key] = sort_list(d[key]) 245 elif type(d[key]) is dict: 246 d[key] = sort_dict(d[key]) 247 248 return d
249
250 -def log_rest_request(response, logger):
251 """ 252 Logs REST request and response 253 254 :param response: Object returned by requests class 255 :type response: Response 256 :param logger: Where to log request and response 257 :type logger: logging.Logger 258 """ 259 260 logger.debug("Request\n\t{url} [{status_code} - {reason}]".format(url=response.request.url, status_code=response.status_code, reason=response.reason)) 261 262 try: 263 #Try to get response as JSON 264 json_resp = response.json() 265 logger.debug("Response\n" + json.dumps(json_resp, sort_keys=True, indent=4, separators=(',', ': '))) 266 return 267 except ValueError: 268 #not valid JSON 269 pass 270 271 #log as text 272 logger.debug("Response\n" + response.content)
273