TinyFW.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  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. """ Interface for test cases. """
  15. import os
  16. import time
  17. import traceback
  18. import functools
  19. import socket
  20. from datetime import datetime
  21. import junit_xml
  22. from . import Env
  23. from . import DUT
  24. from . import App
  25. from . import Utility
  26. class DefaultEnvConfig(object):
  27. """
  28. default test configs. There're 3 places to set configs, priority is (high -> low):
  29. 1. overwrite set by caller of test method
  30. 2. values set by test_method decorator
  31. 3. default env config get from this class
  32. """
  33. DEFAULT_CONFIG = {
  34. "app": App.BaseApp,
  35. "dut": DUT.BaseDUT,
  36. "env_tag": "default",
  37. "env_config_file": None,
  38. "test_suite_name": None,
  39. }
  40. @classmethod
  41. def set_default_config(cls, **kwargs):
  42. """
  43. :param kwargs: configs need to be updated
  44. :return: None
  45. """
  46. cls.DEFAULT_CONFIG.update(kwargs)
  47. @classmethod
  48. def get_default_config(cls):
  49. """
  50. :return: current default config
  51. """
  52. return cls.DEFAULT_CONFIG.copy()
  53. set_default_config = DefaultEnvConfig.set_default_config
  54. get_default_config = DefaultEnvConfig.get_default_config
  55. MANDATORY_INFO = {
  56. "execution_time": 1,
  57. "env_tag": "default",
  58. "category": "function",
  59. "ignore": False,
  60. }
  61. class JunitReport(object):
  62. # wrapper for junit test report
  63. # TODO: JunitReport methods are not thread safe (although not likely to be used this way).
  64. JUNIT_FILE_NAME = "XUNIT_RESULT.xml"
  65. JUNIT_DEFAULT_TEST_SUITE = "test-suite"
  66. JUNIT_TEST_SUITE = junit_xml.TestSuite(JUNIT_DEFAULT_TEST_SUITE,
  67. hostname=socket.gethostname(),
  68. timestamp=datetime.utcnow().isoformat())
  69. JUNIT_CURRENT_TEST_CASE = None
  70. _TEST_CASE_CREATED_TS = 0
  71. @classmethod
  72. def output_report(cls, junit_file_path):
  73. """ Output current test result to file. """
  74. with open(os.path.join(junit_file_path, cls.JUNIT_FILE_NAME), "w") as f:
  75. cls.JUNIT_TEST_SUITE.to_file(f, [cls.JUNIT_TEST_SUITE], prettyprint=False)
  76. @classmethod
  77. def get_current_test_case(cls):
  78. """
  79. By default, the test framework will handle junit test report automatically.
  80. While some test case might want to update some info to test report.
  81. They can use this method to get current test case created by test framework.
  82. :return: current junit test case instance created by ``JunitTestReport.create_test_case``
  83. """
  84. return cls.JUNIT_CURRENT_TEST_CASE
  85. @classmethod
  86. def test_case_finish(cls, test_case):
  87. """
  88. Append the test case to test suite so it can be output to file.
  89. Execution time will be automatically updated (compared to ``create_test_case``).
  90. """
  91. test_case.elapsed_sec = time.time() - cls._TEST_CASE_CREATED_TS
  92. cls.JUNIT_TEST_SUITE.test_cases.append(test_case)
  93. @classmethod
  94. def create_test_case(cls, name):
  95. """
  96. Extend ``junit_xml.TestCase`` with:
  97. 1. save create test case so it can be get by ``get_current_test_case``
  98. 2. log create timestamp, so ``elapsed_sec`` can be auto updated in ``test_case_finish``.
  99. :param name: test case name
  100. :return: instance of ``junit_xml.TestCase``
  101. """
  102. # set stdout to empty string, so we can always append string to stdout.
  103. # It won't affect output logic. If stdout is empty, it won't be put to report.
  104. test_case = junit_xml.TestCase(name, stdout="")
  105. cls.JUNIT_CURRENT_TEST_CASE = test_case
  106. cls._TEST_CASE_CREATED_TS = time.time()
  107. return test_case
  108. @classmethod
  109. def update_performance(cls, performance_items):
  110. """
  111. Update performance results to ``stdout`` of current test case.
  112. :param performance_items: a list of performance items. each performance item is a key-value pair.
  113. """
  114. assert cls.JUNIT_CURRENT_TEST_CASE
  115. for item in performance_items:
  116. cls.JUNIT_CURRENT_TEST_CASE.stdout += "[{}]: {}\n".format(item[0], item[1])
  117. def test_method(**kwargs):
  118. """
  119. decorator for test case function.
  120. The following keyword arguments are pre-defined.
  121. Any other keyword arguments will be regarded as filter for the test case,
  122. able to access them by ``case_info`` attribute of test method.
  123. :keyword app: class for test app. see :doc:`App <App>` for details
  124. :keyword dut: class for current dut. see :doc:`DUT <DUT>` for details
  125. :keyword env_tag: name for test environment, used to select configs from config file
  126. :keyword env_config_file: test env config file. usually will not set this keyword when define case
  127. :keyword test_suite_name: test suite name, used for generating log folder name and adding xunit format test result.
  128. usually will not set this keyword when define case
  129. :keyword junit_report_by_case: By default the test fw will handle junit report generation.
  130. In some cases, one test function might test many test cases.
  131. If this flag is set, test case can update junit report by its own.
  132. """
  133. def test(test_func):
  134. case_info = MANDATORY_INFO.copy()
  135. case_info["name"] = case_info["ID"] = test_func.__name__
  136. case_info["junit_report_by_case"] = False
  137. case_info.update(kwargs)
  138. @functools.wraps(test_func)
  139. def handle_test(extra_data=None, **overwrite):
  140. """
  141. create env, run test and record test results
  142. :param extra_data: extra data that runner or main passed to test case
  143. :param overwrite: args that runner or main want to overwrite
  144. :return: None
  145. """
  146. # create env instance
  147. env_config = DefaultEnvConfig.get_default_config()
  148. for key in kwargs:
  149. if key in env_config:
  150. env_config[key] = kwargs[key]
  151. env_config.update(overwrite)
  152. env_inst = Env.Env(**env_config)
  153. # prepare for xunit test results
  154. junit_file_path = env_inst.app_cls.get_log_folder(env_config["test_suite_name"])
  155. junit_test_case = JunitReport.create_test_case(case_info["ID"])
  156. result = False
  157. try:
  158. Utility.console_log("starting running test: " + test_func.__name__, color="green")
  159. # execute test function
  160. test_func(env_inst, extra_data)
  161. # if finish without exception, test result is True
  162. result = True
  163. except Exception as e:
  164. # handle all the exceptions here
  165. traceback.print_exc()
  166. # log failure
  167. junit_test_case.add_failure_info(str(e) + ":\r\n" + traceback.format_exc())
  168. finally:
  169. # do close all DUTs, if result is False then print DUT debug info
  170. close_errors = env_inst.close(dut_debug=(not result))
  171. # We have a hook in DUT close, allow DUT to raise error to fail test case.
  172. # For example, we don't allow DUT exception (reset) during test execution.
  173. # We don't want to implement in exception detection in test function logic,
  174. # as we need to add it to every test case.
  175. # We can implement it in DUT receive thread,
  176. # and raise exception in DUT close to fail test case if reset detected.
  177. if close_errors:
  178. for error in close_errors:
  179. junit_test_case.add_failure_info(str(error))
  180. result = False
  181. if not case_info["junit_report_by_case"]:
  182. JunitReport.test_case_finish(junit_test_case)
  183. # end case and output result
  184. JunitReport.output_report(junit_file_path)
  185. if result:
  186. Utility.console_log("Test Succeed: " + test_func.__name__, color="green")
  187. else:
  188. Utility.console_log(("Test Fail: " + test_func.__name__), color="red")
  189. return result
  190. handle_test.case_info = case_info
  191. handle_test.test_method = True
  192. return handle_test
  193. return test