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 tempfile
      7  from glob import glob
      8
      9 -def tlib_folder():
     10      """
     11      Returns tlib's absolute path
     12      """
     13      file_folder = os.path.dirname(__file__)
     14      return os.path.abspath(os.path.join(file_folder, os.pardir))
     15
     16
     17 -def tlib_asset_folder():
     18      """
     19      Returns absolute path of tlib's asset folder
     20      """
     21      return os.path.abspath(os.path.join(tlib_folder(), "asset"))
     22
     23
     24 -def tlib_modules_folder():
     25      """
     26      Returns absolute path of folder containing all modules
     27      """
     28      return os.path.abspath(os.path.join(tlib_folder(), "base"))
     29
     30
     31 -def tlib_config_folder():
     32      """
     33      Returns absolute path of tlib's config folder
     34      """
     35      return os.path.abspath(os.path.join(tlib_folder(), "config"))
     36
     37
     38 -def tlib_template_folder():
     39      """
     40      Returns absolute path of tlib's template folder\n
     41      Template folder contains jinja templates used for generation of reports\n
     42      like screenshots
     43      """
     44      return os.path.abspath(os.path.join(tlib_folder(), "templates"))
     45
     46
     47 -def webdriver_chrome_executable(version="latest"):
     48      """
     49      Returns path to Chrome WebDriver executable
     50      """
     51      if version == "latest":
     52          #Find all cromedriver files and sort by filename
     53          path = os.path.join(tlib_asset_folder(), "selenium", "chromedriver_*.exe")
     54          r = sorted(glob(path))
     55          return os.path.join(tlib_asset_folder(), "selenium", r[-1])
     56      else:
     57          return os.path.join(tlib_asset_folder(), "selenium", "chromedriver_%s.exe" % version)
     58
     59
     60 -def webdriver_ie_executable():
     61      """
     62      Alias for webdriver_ie32_executable
     63      """
     64      return webdriver_ie32_executable();
     65
     66
     67 -def webdriver_ie32_executable():
     68      """
     69      Returns path to IE WebDriver executable
     70      """
     71      return os.path.join(tlib_asset_folder(), "selenium", "IE", "2.41.0", "Win32", "IEDriverServer.exe")
     72
     73
     74 -def webdriver_ie64_executable():
     75      """
     76      Returns path to IE WebDriver executable
     77      """
     78      return os.path.join(tlib_asset_folder(), "selenium", "IE", "2.41.0", "x64", "IEDriverServer.exe")
     79
     80
     81 -def android_server_apk():
     82      """
     83      Returns path to Webdriver for android
     84      """
     85      return os.path.join(tlib_asset_folder(), "selenium", "android-server-2.21.0.apk")
     86
     87
     88 -def is_valid_ip(ip):
     89      """
     90      Returns true if IP parameter is a valid IP address.\n
     91      Currently IPs in this format are valid:\n
     92      X.X.X.X\n
     93      X.X.X.X:PORT
     94
     95      @type ip: str
     96      @return: bool
     97      """
     98
     99      if ip is None:
    100          return False
    101
    102      try:
    103          (ip, port) = ip.split(":", 1)
    104      except ValueError:
    105          #There is no ':' in the string
    106          port = None
    107
    108      try:
    109          socket.inet_aton(ip)
    110      except socket.error:
    111          return False
    112
    113      if port is not None:
    114          try:
    115              return (int(port) >= 1) and (int(port) <= 65535)
    116          except ValueError:
    117              #Not a valid integer
    118              return False
    119
    120      return True
    121
    122 -def run_command(logger, command, fail_on_error=True):
    123      """
    124      Run a command and skip test if exit code is not 0
    125
    126      Example:
    127      Run 'adb devices' and don't skip test if commands returns non-zero status
    128      run_command(logger, ["adb", "devices"], fail_on_error=False)
    129
    130      @param logger: logger for debugging purposes
    131      @type logger: logging.logger
    132      @param command: Command to run
    133      @type command: list
    134      @param fail_on_error: When True, skip test if command returned a non-zero exit code
    135      @type fail_on_error: bool
    136      @rtype: list
    137      @return: Returns a list with stdout and stderr output
    138      """
    139
    140      fd_out = tempfile.NamedTemporaryFile(delete=True)
    141      #With delete = True option, the files will be automatically removed after close
    142      fd_err = tempfile.NamedTemporaryFile(delete=True)
    143      try:
    144          process = subprocess.Popen(command, stdout=fd_out, stderr=fd_err)
    145      except WindowsError as e:
    146          logger.error(r"Problem running command, skipping test.\n%s" % e)
    147          # noinspection PyUnresolvedReferences
    148          if fail_on_error:
    149              pytest.fail(r"Problem running command, skipping test.\n%s" % e)
    150
    151      # noinspection PyUnboundLocalVariable
    152      process.communicate()
    153      fd_out.seek(0)
    154      fd_err.seek(0)
    155      out = (fd_out.read(), fd_err.read())
    156      fd_out.close()
    157      fd_err.close()
    158      errcode = process.returncode
    159
    160      if (errcode != 0) and fail_on_error:
    161          logger.error(r"Program  exited with code {errcode}, skipping test\n{out}".format(errcode=errcode, out=out))
    162          # noinspection PyUnresolvedReferences
    163          pytest.fail(r"Program exited with code {errcode}, skipping test\n{out}".format(errcode=errcode, out=out))
    164
    165      return out
    166
    167 -def sort_list(l):
    168      """
    169      Sorts a list, and if the list has other objects inside, it will iterate over them
    170      @param l: list to sort
    171      @type l: list
    172      @return: sorted list
    173      @rtype: list
    174      """
    175      if type(l) is not list:
    176          pytest.fail("Parameter l is not a list")
    177
    178      for i, s in enumerate(l):
    179          if type(s) is list:
    180              l[i] = sort_list(s)
    181          if type(s) is dict:
    182              l[i] = sort_dict(s)
    183
    184      l.sort()
    185
    186      return l
    187
    188
    189 -def sort_dict(d):
    190      """
    191      Sorts a dictionary, and if the list has other objects inside, it will iterate over them
    192      @param d: dictionary to sort
    193      @type d: dict
    194      @return: sorted dictionary
    195      @rtype: dict
    196      """
    197      if type(d) is not dict:
    198          pytest.fail("Parameter d is not a dictionary")
    199
    200      for key in d.keys():
    201          if type(d[key]) is list:
    202              #Sort list
    203              d[key] = sort_list(d[key])
    204          elif type(d[key]) is dict:
    205              d[key] = sort_dict(d[key])
    206
    207      return d
    208