TinyFW.py 9.3 KB

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