Env.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  1. # Copyright 2015-2017 Espressif Systems (Shanghai) PTE LTD
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http:#www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """ Test Env, manages DUT, App and EnvConfig, interface for test cases to access these components """
  15. import os
  16. import threading
  17. import functools
  18. import netifaces
  19. import traceback
  20. from . import EnvConfig
  21. def _synced(func):
  22. @functools.wraps(func)
  23. def decorator(self, *args, **kwargs):
  24. with self.lock:
  25. ret = func(self, *args, **kwargs)
  26. return ret
  27. decorator.__doc__ = func.__doc__
  28. return decorator
  29. class Env(object):
  30. """
  31. test env, manages DUTs and env configs.
  32. :keyword app: class for default application
  33. :keyword dut: class for default DUT
  34. :keyword env_tag: test env tag, used to select configs from env config file
  35. :keyword env_config_file: test env config file path
  36. :keyword test_name: test suite name, used when generate log folder name
  37. """
  38. def __init__(self,
  39. app=None,
  40. dut=None,
  41. env_tag=None,
  42. env_config_file=None,
  43. test_suite_name=None,
  44. **kwargs):
  45. self.app_cls = app
  46. self.default_dut_cls = dut
  47. self.config = EnvConfig.Config(env_config_file, env_tag)
  48. self.log_path = self.app_cls.get_log_folder(test_suite_name)
  49. if not os.path.exists(self.log_path):
  50. os.makedirs(self.log_path)
  51. self.allocated_duts = dict()
  52. self.lock = threading.RLock()
  53. @_synced
  54. def get_dut(self, dut_name, app_path, dut_class=None, app_class=None, app_config_name=None, **dut_init_args):
  55. """
  56. get_dut(dut_name, app_path, dut_class=None, app_class=None)
  57. :param dut_name: user defined name for DUT
  58. :param app_path: application path, app instance will use this path to process application info
  59. :param dut_class: dut class, if not specified will use default dut class of env
  60. :param app_class: app class, if not specified will use default app of env
  61. :param app_config_name: app build config
  62. :keyword dut_init_args: extra kwargs used when creating DUT instance
  63. :return: dut instance
  64. """
  65. if dut_name in self.allocated_duts:
  66. dut = self.allocated_duts[dut_name]["dut"]
  67. else:
  68. if dut_class is None:
  69. dut_class = self.default_dut_cls
  70. if app_class is None:
  71. app_class = self.app_cls
  72. detected_target = None
  73. try:
  74. port = self.config.get_variable(dut_name)
  75. except ValueError:
  76. # try to auto detect ports
  77. allocated_ports = [self.allocated_duts[x]["port"] for x in self.allocated_duts]
  78. available_ports = dut_class.list_available_ports()
  79. for port in available_ports:
  80. if port not in allocated_ports:
  81. result, detected_target = dut_class.confirm_dut(port)
  82. if result:
  83. break
  84. else:
  85. port = None
  86. app_target = dut_class.TARGET
  87. if not app_target:
  88. app_target = detected_target
  89. if not app_target:
  90. raise ValueError("DUT class doesn't specify the target, and autodetection failed")
  91. app_inst = app_class(app_path, app_config_name, app_target)
  92. if port:
  93. try:
  94. dut_config = self.get_variable(dut_name + "_port_config")
  95. except ValueError:
  96. dut_config = dict()
  97. dut_config.update(dut_init_args)
  98. dut = dut_class(dut_name, port,
  99. os.path.join(self.log_path, dut_name + ".log"),
  100. app_inst,
  101. **dut_config)
  102. self.allocated_duts[dut_name] = {"port": port, "dut": dut}
  103. else:
  104. raise ValueError("Failed to get DUT")
  105. return dut
  106. @_synced
  107. def close_dut(self, dut_name):
  108. """
  109. close_dut(dut_name)
  110. close one DUT by name if DUT name is valid (the name used by ``get_dut``). otherwise will do nothing.
  111. :param dut_name: user defined name for DUT
  112. :return: None
  113. """
  114. try:
  115. dut = self.allocated_duts.pop(dut_name)["dut"]
  116. dut.close()
  117. except KeyError:
  118. pass
  119. @_synced
  120. def get_variable(self, variable_name):
  121. """
  122. get_variable(variable_name)
  123. get variable from config file. If failed then try to auto-detected it.
  124. :param variable_name: name of the variable
  125. :return: value of variable if successfully found. otherwise None.
  126. """
  127. return self.config.get_variable(variable_name)
  128. PROTO_MAP = {
  129. "ipv4": netifaces.AF_INET,
  130. "ipv6": netifaces.AF_INET6,
  131. "mac": netifaces.AF_LINK,
  132. }
  133. @_synced
  134. def get_pc_nic_info(self, nic_name="pc_nic", proto="ipv4"):
  135. """
  136. get_pc_nic_info(nic_name="pc_nic")
  137. try to get info of a specified NIC and protocol.
  138. :param nic_name: pc nic name. allows passing variable name, nic name value.
  139. :param proto: "ipv4", "ipv6" or "mac"
  140. :return: a dict of nic info if successfully found. otherwise None.
  141. nic info keys could be different for different protocols.
  142. key "addr" is available for both mac, ipv4 and ipv6 pic info.
  143. """
  144. interfaces = netifaces.interfaces()
  145. if nic_name in interfaces:
  146. # the name is in the interface list, we regard it as NIC name
  147. if_addr = netifaces.ifaddresses(nic_name)
  148. else:
  149. # it's not in interface name list, we assume it's variable name
  150. _nic_name = self.get_variable(nic_name)
  151. if_addr = netifaces.ifaddresses(_nic_name)
  152. return if_addr[self.PROTO_MAP[proto]][0]
  153. @_synced
  154. def close(self, dut_debug=False):
  155. """
  156. close()
  157. close all DUTs of the Env.
  158. :param dut_debug: if dut_debug is True, then print all dut expect failures before close it
  159. :return: exceptions during close DUT
  160. """
  161. dut_close_errors = []
  162. for dut_name in self.allocated_duts:
  163. dut = self.allocated_duts[dut_name]["dut"]
  164. try:
  165. if dut_debug:
  166. dut.print_debug_info()
  167. dut.close()
  168. except Exception as e:
  169. traceback.print_exc()
  170. dut_close_errors.append(e)
  171. self.allocated_duts = dict()
  172. return dut_close_errors