TinyFW.py 9.6 KB

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