unit_test.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811
  1. #!/usr/bin/env python
  2. #
  3. # SPDX-FileCopyrightText: 2018-2022 Espressif Systems (Shanghai) CO LTD
  4. # SPDX-License-Identifier: Apache-2.0
  5. """
  6. Test script for unit test case.
  7. """
  8. import argparse
  9. import re
  10. import threading
  11. import time
  12. import ttfw_idf
  13. from tiny_test_fw import DUT, Env, TinyFW, Utility
  14. from tiny_test_fw.TinyFW import TestCaseFailed
  15. from tiny_test_fw.Utility import format_case_id, handle_unexpected_exception
  16. UT_APP_BOOT_UP_DONE = 'Press ENTER to see the list of tests.'
  17. STRIP_CONFIG_PATTERN = re.compile(r'(.+?)(_\d+)?$')
  18. # matches e.g.: "rst:0xc (SW_CPU_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)"
  19. RESET_PATTERN = re.compile(r'(rst:0x[0-9a-fA-F]*\s\([\w].*?\),boot:0x[0-9a-fA-F]*\s\([\w].*?\))')
  20. EXCEPTION_PATTERN = re.compile(r"(Guru Meditation Error: Core\s+\d panic'ed \([\w].*?\))")
  21. ABORT_PATTERN = re.compile(r'(abort\(\) was called at PC 0x[a-fA-F\d]{8} on core \d)')
  22. ASSERT_PATTERN = re.compile(r'(assert failed: .*)')
  23. FINISH_PATTERN = re.compile(r'1 Tests (\d) Failures (\d) Ignored')
  24. END_LIST_STR = r'\r?\nEnter test for running'
  25. TEST_PATTERN = re.compile(r'\((\d+)\)\s+"([^"]+)" ([^\r\n]+)\r?\n(' + END_LIST_STR + r')?')
  26. TEST_SUBMENU_PATTERN = re.compile(r'\s+\((\d+)\)\s+"[^"]+"\r?\n(?=(?=\()|(' + END_LIST_STR + r'))')
  27. UT_APP_PATH = 'tools/unit-test-app'
  28. SIMPLE_TEST_ID = 0
  29. MULTI_STAGE_ID = 1
  30. MULTI_DEVICE_ID = 2
  31. DEFAULT_TIMEOUT = 20
  32. DUT_DELAY_AFTER_RESET = 2
  33. DUT_STARTUP_CHECK_RETRY_COUNT = 5
  34. TEST_HISTORY_CHECK_TIMEOUT = 2
  35. def reset_reason_matches(reported_str, expected_str):
  36. known_aliases = {
  37. '_RESET': '_RST',
  38. 'POWERON_RESET': 'POWERON',
  39. 'DEEPSLEEP_RESET': 'DSLEEP',
  40. }
  41. if expected_str in reported_str:
  42. return True
  43. for token, alias in known_aliases.items():
  44. if token in expected_str:
  45. alt_expected_str = expected_str.replace(token, alias)
  46. if alt_expected_str in reported_str:
  47. return True
  48. return False
  49. def format_test_case_config(test_case_data, target='esp32'):
  50. """
  51. convert the test case data to unified format.
  52. We need to following info to run unit test cases:
  53. 1. unit test app config
  54. 2. test case name
  55. 3. test case reset info
  56. the formatted case config is a dict, with ut app config as keys. The value is a list of test cases.
  57. Each test case is a dict with "name" and "reset" as keys. For example::
  58. case_config = {
  59. "default": [{"name": "restart from PRO CPU", "reset": "SW_CPU_RESET"}, {...}],
  60. "psram": [{"name": "restart from PRO CPU", "reset": "SW_CPU_RESET"}],
  61. }
  62. If config is not specified for test case, then
  63. :param test_case_data: string, list, or a dictionary list
  64. :param target: target
  65. :return: formatted data
  66. """
  67. case_config = dict()
  68. def parse_case(one_case_data):
  69. """ parse and format one case """
  70. def process_reset_list(reset_list):
  71. # strip space and remove white space only items
  72. _output = list()
  73. for _r in reset_list:
  74. _data = _r.strip(' ')
  75. if _data:
  76. _output.append(_data)
  77. return _output
  78. _case = dict()
  79. if isinstance(one_case_data, str):
  80. _temp = one_case_data.split(' [reset=')
  81. _case['name'] = _temp[0]
  82. try:
  83. _case['reset'] = process_reset_list(_temp[1][0:-1].split(','))
  84. except IndexError:
  85. _case['reset'] = list()
  86. elif isinstance(one_case_data, dict):
  87. _case = one_case_data.copy()
  88. assert 'name' in _case
  89. if 'reset' not in _case:
  90. _case['reset'] = list()
  91. else:
  92. if isinstance(_case['reset'], str):
  93. _case['reset'] = process_reset_list(_case['reset'].split(','))
  94. else:
  95. raise TypeError('Not supported type during parsing unit test case')
  96. if 'config' not in _case:
  97. _case['config'] = 'default'
  98. if 'target' not in _case:
  99. _case['target'] = target
  100. return _case
  101. if not isinstance(test_case_data, list):
  102. test_case_data = [test_case_data]
  103. for case_data in test_case_data:
  104. parsed_case = parse_case(case_data)
  105. try:
  106. case_config[parsed_case['config']].append(parsed_case)
  107. except KeyError:
  108. case_config[parsed_case['config']] = [parsed_case]
  109. return case_config
  110. def replace_app_bin(dut, name, new_app_bin):
  111. if new_app_bin is None:
  112. return
  113. search_pattern = '/{}.bin'.format(name)
  114. for i, config in enumerate(dut.download_config):
  115. if config.endswith(search_pattern):
  116. dut.download_config[i] = new_app_bin
  117. Utility.console_log('The replaced application binary is {}'.format(new_app_bin), 'O')
  118. break
  119. def format_case_name(case):
  120. # we could split cases of same config into multiple binaries as we have limited rom space
  121. # we should regard those configs like `default` and `default_2` as the same config
  122. match = STRIP_CONFIG_PATTERN.match(case['config'])
  123. stripped_config_name = match.group(1)
  124. return format_case_id(case['name'], target=case['target'], config=stripped_config_name)
  125. def reset_dut(dut):
  126. dut.reset()
  127. # esptool ``run`` cmd takes quite long time.
  128. # before reset finish, serial port is closed. therefore DUT could already bootup before serial port opened.
  129. # this could cause checking bootup print failed.
  130. # now use input cmd `-` and check test history to check if DUT is bootup.
  131. # we'll retry this step for a few times,
  132. # in case `dut.reset` returns during DUT bootup (when DUT can't process any command).
  133. #
  134. # during bootup, DUT might only receive part of the first `-` command.
  135. # If it only receive `\n`, then it will print all cases. It could take more than 5 seconds, reset check will fail.
  136. # To solve this problem, we will add a delay between reset and input `-` command. And we'll also enlarge expect timeout.
  137. time.sleep(DUT_DELAY_AFTER_RESET)
  138. for _ in range(DUT_STARTUP_CHECK_RETRY_COUNT):
  139. dut.write('-')
  140. try:
  141. dut.expect('0 Tests 0 Failures 0 Ignored', timeout=TEST_HISTORY_CHECK_TIMEOUT)
  142. break
  143. except DUT.ExpectTimeout:
  144. pass
  145. else:
  146. raise AssertionError('Reset {} ({}) failed!'.format(dut.name, dut.port))
  147. def log_test_case(description, test_case, ut_config):
  148. Utility.console_log("Running {} '{}' (config {})".format(description, test_case['name'], ut_config),
  149. color='orange')
  150. Utility.console_log('Tags: %s' % ', '.join('%s=%s' % (k, v) for (k, v) in test_case.items()
  151. if k != 'name' and v is not None),
  152. color='orange')
  153. def run_one_normal_case(dut, one_case, junit_test_case):
  154. reset_dut(dut)
  155. dut.start_capture_raw_data()
  156. # run test case
  157. dut.write("\"{}\"".format(one_case['name']))
  158. dut.expect('Running ' + one_case['name'] + '...')
  159. exception_reset_list = []
  160. # we want to set this flag in callbacks (inner functions)
  161. # use list here so we can use append to set this flag
  162. test_finish = list()
  163. # expect callbacks
  164. def one_case_finish(result):
  165. """ one test finished, let expect loop break and log result """
  166. test_finish.append(True)
  167. output = dut.stop_capture_raw_data()
  168. if result:
  169. Utility.console_log('Success: ' + format_case_name(one_case), color='green')
  170. else:
  171. Utility.console_log('Failed: ' + format_case_name(one_case), color='red')
  172. junit_test_case.add_failure_info(output)
  173. raise TestCaseFailed(format_case_name(one_case))
  174. def handle_exception_reset(data):
  175. """
  176. just append data to exception list.
  177. exception list will be checked in ``handle_reset_finish``, once reset finished.
  178. """
  179. exception_reset_list.append(data[0])
  180. def handle_test_finish(data):
  181. """ test finished without reset """
  182. # in this scenario reset should not happen
  183. assert not exception_reset_list
  184. if int(data[1]):
  185. # case ignored
  186. Utility.console_log('Ignored: ' + format_case_name(one_case), color='orange')
  187. junit_test_case.add_skipped_info('ignored')
  188. one_case_finish(not int(data[0]))
  189. def handle_reset_finish(data):
  190. """ reset happened and reboot finished """
  191. assert exception_reset_list # reboot but no exception/reset logged. should never happen
  192. result = False
  193. if len(one_case['reset']) == len(exception_reset_list):
  194. for i, exception in enumerate(exception_reset_list):
  195. if not reset_reason_matches(exception, one_case['reset'][i]):
  196. break
  197. else:
  198. result = True
  199. if not result:
  200. err_msg = 'Reset Check Failed: \r\n\tExpected: {}\r\n\tGet: {}'.format(one_case['reset'],
  201. exception_reset_list)
  202. Utility.console_log(err_msg, color='orange')
  203. junit_test_case.add_failure_info(err_msg)
  204. one_case_finish(result)
  205. while not test_finish:
  206. try:
  207. timeout_value = one_case['timeout']
  208. dut.expect_any((RESET_PATTERN, handle_exception_reset),
  209. (EXCEPTION_PATTERN, handle_exception_reset),
  210. (ABORT_PATTERN, handle_exception_reset),
  211. (ASSERT_PATTERN, handle_exception_reset),
  212. (FINISH_PATTERN, handle_test_finish),
  213. (UT_APP_BOOT_UP_DONE, handle_reset_finish),
  214. timeout=timeout_value)
  215. except DUT.ExpectTimeout:
  216. Utility.console_log('Timeout in expect (%s seconds)' % timeout_value, color='orange')
  217. junit_test_case.add_failure_info('timeout')
  218. one_case_finish(False)
  219. break
  220. @ttfw_idf.idf_unit_test(env_tag='UT_T1_1', junit_report_by_case=True)
  221. def run_unit_test_cases(env, extra_data):
  222. """
  223. extra_data can be three types of value
  224. 1. as string:
  225. 1. "case_name"
  226. 2. "case_name [reset=RESET_REASON]"
  227. 2. as dict:
  228. 1. with key like {"name": "Intr_alloc test, shared ints"}
  229. 2. with key like {"name": "restart from PRO CPU", "reset": "SW_CPU_RESET", "config": "psram"}
  230. 3. as list of string or dict:
  231. [case1, case2, case3, {"name": "restart from PRO CPU", "reset": "SW_CPU_RESET"}, ...]
  232. :param env: test env instance
  233. :param extra_data: the case name or case list or case dictionary
  234. :return: None
  235. """
  236. case_config = format_test_case_config(extra_data, env.default_dut_cls.TARGET)
  237. # we don't want stop on failed case (unless some special scenarios we can't handle)
  238. # this flag is used to log if any of the case failed during executing
  239. # Before exit test function this flag is used to log if the case fails
  240. failed_cases = []
  241. for ut_config in case_config:
  242. Utility.console_log('Running unit test for config: ' + ut_config, 'O')
  243. # Get the console baudrate from the sdkconfig
  244. _app = ttfw_idf.UT(app_path=UT_APP_PATH, config_name=ut_config, target=env.default_dut_cls.TARGET)
  245. baud = _app.get_sdkconfig_config_value('CONFIG_ESP_CONSOLE_UART_BAUDRATE')
  246. if baud is None:
  247. baud = 115200
  248. Utility.console_log('Can\'t find console baudrate in sdkconfig, use 115200 as default')
  249. else:
  250. baud = int(baud, 10) if isinstance(baud, str) else baud
  251. Utility.console_log('Console baudrate is {}'.format(baud))
  252. # Get the DUT with specified baudrate
  253. dut = env.get_dut('unit-test-app', app_path=UT_APP_PATH, app_config_name=ut_config,
  254. allow_dut_exception=True, baudrate=baud)
  255. if len(case_config[ut_config]) > 0:
  256. replace_app_bin(dut, 'unit-test-app', case_config[ut_config][0].get('app_bin'))
  257. dut.start_app()
  258. Utility.console_log('Download finished, start running test cases', 'O')
  259. for one_case in case_config[ut_config]:
  260. log_test_case('test case', one_case, ut_config)
  261. performance_items = []
  262. # create junit report test case
  263. junit_test_case = TinyFW.JunitReport.create_test_case(format_case_name(one_case))
  264. try:
  265. run_one_normal_case(dut, one_case, junit_test_case)
  266. performance_items = dut.get_performance_items()
  267. except TestCaseFailed:
  268. failed_cases.append(format_case_name(one_case))
  269. except Exception as e:
  270. handle_unexpected_exception(junit_test_case, e)
  271. failed_cases.append(format_case_name(one_case))
  272. finally:
  273. TinyFW.JunitReport.update_performance(performance_items)
  274. TinyFW.JunitReport.test_case_finish(junit_test_case)
  275. # close DUT when finish running all cases for one config
  276. env.close_dut(dut.name)
  277. class Handler(threading.Thread):
  278. WAIT_SIGNAL_PATTERN = re.compile(r'Waiting for signal: \[(.+)]!')
  279. SEND_SIGNAL_PATTERN = re.compile(r'Send signal: \[([^]]+)](\[([^]]+)])?!')
  280. FINISH_PATTERN = re.compile(r'1 Tests (\d) Failures (\d) Ignored')
  281. def __init__(self, dut, sent_signal_list, lock, parent_case_name, child_case_index, timeout):
  282. self.dut = dut
  283. self.sent_signal_list = sent_signal_list
  284. self.lock = lock
  285. self.parent_case_name = parent_case_name
  286. self.child_case_name = ''
  287. self.child_case_index = child_case_index + 1
  288. self.finish = False
  289. self.result = False
  290. self.output = ''
  291. self.fail_name = None
  292. self.timeout = timeout
  293. self.force_stop = threading.Event() # it show the running status
  294. reset_dut(self.dut) # reset the board to make it start from begining
  295. threading.Thread.__init__(self, name='{} Handler'.format(dut))
  296. def run(self):
  297. self.dut.start_capture_raw_data()
  298. def get_child_case_name(data):
  299. self.child_case_name = data[0]
  300. time.sleep(1)
  301. self.dut.write(str(self.child_case_index))
  302. def one_device_case_finish(result):
  303. """ one test finished, let expect loop break and log result """
  304. self.finish = True
  305. self.result = result
  306. self.output = '[{}]\n\n{}\n'.format(self.child_case_name,
  307. self.dut.stop_capture_raw_data())
  308. if not result:
  309. self.fail_name = self.child_case_name
  310. def device_wait_action(data):
  311. start_time = time.time()
  312. expected_signal = data[0].encode('utf-8')
  313. while 1:
  314. if time.time() > start_time + self.timeout:
  315. Utility.console_log('Timeout in device for function: %s' % self.child_case_name, color='orange')
  316. break
  317. with self.lock:
  318. for sent_signal in self.sent_signal_list:
  319. if expected_signal == sent_signal['name']:
  320. self.dut.write(sent_signal['parameter'])
  321. self.sent_signal_list.remove(sent_signal)
  322. break
  323. else:
  324. time.sleep(0.01)
  325. continue
  326. break
  327. def device_send_action(data):
  328. with self.lock:
  329. self.sent_signal_list.append({
  330. 'name': data[0].encode('utf-8'),
  331. 'parameter': '' if data[2] is None else data[2].encode('utf-8')
  332. # no parameter means we only write EOL to DUT
  333. })
  334. def handle_device_test_finish(data):
  335. """ test finished without reset """
  336. # in this scenario reset should not happen
  337. if int(data[1]):
  338. # case ignored
  339. Utility.console_log('Ignored: ' + self.child_case_name, color='orange')
  340. one_device_case_finish(not int(data[0]))
  341. try:
  342. time.sleep(1)
  343. self.dut.write("\"{}\"".format(self.parent_case_name))
  344. self.dut.expect('Running ' + self.parent_case_name + '...')
  345. except DUT.ExpectTimeout:
  346. Utility.console_log('No case detected!', color='orange')
  347. while not self.finish and not self.force_stop.isSet():
  348. try:
  349. self.dut.expect_any((re.compile('\(' + str(self.child_case_index) + '\)\s"(\w+)"'), # noqa: W605 - regex
  350. get_child_case_name),
  351. (self.WAIT_SIGNAL_PATTERN, device_wait_action), # wait signal pattern
  352. (self.SEND_SIGNAL_PATTERN, device_send_action), # send signal pattern
  353. (self.FINISH_PATTERN, handle_device_test_finish), # test finish pattern
  354. timeout=self.timeout)
  355. except DUT.ExpectTimeout:
  356. Utility.console_log('Timeout in expect (%s seconds)' % self.timeout, color='orange')
  357. one_device_case_finish(False)
  358. break
  359. def stop(self):
  360. self.force_stop.set()
  361. def get_case_info(one_case):
  362. parent_case = one_case['name']
  363. child_case_num = one_case['child case num']
  364. return parent_case, child_case_num
  365. def get_dut(duts, env, name, ut_config, app_bin=None):
  366. if name in duts:
  367. dut = duts[name]
  368. else:
  369. dut = env.get_dut(name, app_path=UT_APP_PATH, app_config_name=ut_config, allow_dut_exception=True)
  370. duts[name] = dut
  371. replace_app_bin(dut, 'unit-test-app', app_bin)
  372. dut.start_app() # download bin to board
  373. return dut
  374. def run_one_multiple_devices_case(duts, ut_config, env, one_case, app_bin, junit_test_case):
  375. lock = threading.RLock()
  376. threads = []
  377. send_signal_list = []
  378. result = True
  379. parent_case, case_num = get_case_info(one_case)
  380. for i in range(case_num):
  381. dut = get_dut(duts, env, 'dut%d' % i, ut_config, app_bin)
  382. threads.append(Handler(dut, send_signal_list, lock,
  383. parent_case, i, one_case['timeout']))
  384. for thread in threads:
  385. thread.setDaemon(True)
  386. thread.start()
  387. output = 'Multiple Device Failed\n'
  388. for thread in threads:
  389. thread.join()
  390. result = result and thread.result
  391. output += thread.output
  392. if not thread.result:
  393. [thd.stop() for thd in threads]
  394. if not result:
  395. junit_test_case.add_failure_info(output)
  396. # collect performances from DUTs
  397. performance_items = []
  398. for dut_name in duts:
  399. performance_items.extend(duts[dut_name].get_performance_items())
  400. TinyFW.JunitReport.update_performance(performance_items)
  401. return result
  402. @ttfw_idf.idf_unit_test(env_tag='UT_T2_1', junit_report_by_case=True)
  403. def run_multiple_devices_cases(env, extra_data):
  404. """
  405. extra_data can be two types of value
  406. 1. as dict:
  407. e.g.
  408. {"name": "gpio master/slave test example",
  409. "child case num": 2,
  410. "config": "release",
  411. "env_tag": "UT_T2_1"}
  412. 2. as list dict:
  413. e.g.
  414. [{"name": "gpio master/slave test example1",
  415. "child case num": 2,
  416. "config": "release",
  417. "env_tag": "UT_T2_1"},
  418. {"name": "gpio master/slave test example2",
  419. "child case num": 2,
  420. "config": "release",
  421. "env_tag": "UT_T2_1"}]
  422. """
  423. failed_cases = []
  424. case_config = format_test_case_config(extra_data, env.default_dut_cls.TARGET)
  425. duts = {}
  426. for ut_config in case_config:
  427. Utility.console_log('Running unit test for config: ' + ut_config, 'O')
  428. for one_case in case_config[ut_config]:
  429. log_test_case('multi-device test', one_case, ut_config, )
  430. result = False
  431. junit_test_case = TinyFW.JunitReport.create_test_case(format_case_name(one_case))
  432. try:
  433. result = run_one_multiple_devices_case(duts, ut_config, env, one_case,
  434. one_case.get('app_bin'), junit_test_case)
  435. except TestCaseFailed:
  436. pass # result is False, this is handled by the finally block
  437. except Exception as e:
  438. handle_unexpected_exception(junit_test_case, e)
  439. finally:
  440. if result:
  441. Utility.console_log('Success: ' + format_case_name(one_case), color='green')
  442. else:
  443. failed_cases.append(format_case_name(one_case))
  444. Utility.console_log('Failed: ' + format_case_name(one_case), color='red')
  445. TinyFW.JunitReport.test_case_finish(junit_test_case)
  446. # close all DUTs when finish running all cases for one config
  447. for dut in duts:
  448. env.close_dut(dut)
  449. duts = {}
  450. def run_one_multiple_stage_case(dut, one_case, junit_test_case):
  451. reset_dut(dut)
  452. dut.start_capture_raw_data()
  453. exception_reset_list = []
  454. for test_stage in range(one_case['child case num']):
  455. # select multi stage test case name
  456. dut.write("\"{}\"".format(one_case['name']))
  457. dut.expect('Running ' + one_case['name'] + '...')
  458. # select test function for current stage
  459. dut.write(str(test_stage + 1))
  460. # we want to set this flag in callbacks (inner functions)
  461. # use list here so we can use append to set this flag
  462. stage_finish = list()
  463. def last_stage():
  464. return test_stage == one_case['child case num'] - 1
  465. def check_reset():
  466. if one_case['reset']:
  467. assert exception_reset_list # reboot but no exception/reset logged. should never happen
  468. result = False
  469. if len(one_case['reset']) == len(exception_reset_list):
  470. for i, exception in enumerate(exception_reset_list):
  471. if not reset_reason_matches(exception, one_case['reset'][i]):
  472. break
  473. else:
  474. result = True
  475. if not result:
  476. err_msg = 'Reset Check Failed: \r\n\tExpected: {}\r\n\tGet: {}'.format(one_case['reset'],
  477. exception_reset_list)
  478. Utility.console_log(err_msg, color='orange')
  479. junit_test_case.add_failure_info(err_msg)
  480. else:
  481. # we allow omit reset in multi stage cases
  482. result = True
  483. return result
  484. # expect callbacks
  485. def one_case_finish(result):
  486. """ one test finished, let expect loop break and log result """
  487. # handle test finish
  488. result = result and check_reset()
  489. output = dut.stop_capture_raw_data()
  490. if result:
  491. Utility.console_log('Success: ' + format_case_name(one_case), color='green')
  492. else:
  493. Utility.console_log('Failed: ' + format_case_name(one_case), color='red')
  494. junit_test_case.add_failure_info(output)
  495. raise TestCaseFailed(format_case_name(one_case))
  496. stage_finish.append('break')
  497. def handle_exception_reset(data):
  498. """
  499. just append data to exception list.
  500. exception list will be checked in ``handle_reset_finish``, once reset finished.
  501. """
  502. exception_reset_list.append(data[0])
  503. def handle_test_finish(data):
  504. """ test finished without reset """
  505. # in this scenario reset should not happen
  506. if int(data[1]):
  507. # case ignored
  508. Utility.console_log('Ignored: ' + format_case_name(one_case), color='orange')
  509. junit_test_case.add_skipped_info('ignored')
  510. # only passed in last stage will be regarded as real pass
  511. if last_stage():
  512. one_case_finish(not int(data[0]))
  513. else:
  514. Utility.console_log('test finished before enter last stage', color='orange')
  515. one_case_finish(False)
  516. def handle_next_stage(data):
  517. """ reboot finished. we goto next stage """
  518. if last_stage():
  519. # already last stage, should never goto next stage
  520. Utility.console_log("didn't finish at last stage", color='orange')
  521. one_case_finish(False)
  522. else:
  523. stage_finish.append('continue')
  524. while not stage_finish:
  525. try:
  526. timeout_value = one_case['timeout']
  527. dut.expect_any((RESET_PATTERN, handle_exception_reset),
  528. (EXCEPTION_PATTERN, handle_exception_reset),
  529. (ABORT_PATTERN, handle_exception_reset),
  530. (ASSERT_PATTERN, handle_exception_reset),
  531. (FINISH_PATTERN, handle_test_finish),
  532. (UT_APP_BOOT_UP_DONE, handle_next_stage),
  533. timeout=timeout_value)
  534. except DUT.ExpectTimeout:
  535. Utility.console_log('Timeout in expect (%s seconds)' % timeout_value, color='orange')
  536. one_case_finish(False)
  537. break
  538. if stage_finish[0] == 'break':
  539. # test breaks on current stage
  540. break
  541. @ttfw_idf.idf_unit_test(env_tag='UT_T1_1', junit_report_by_case=True)
  542. def run_multiple_stage_cases(env, extra_data):
  543. """
  544. extra_data can be 2 types of value
  545. 1. as dict: Mandatory keys: "name" and "child case num", optional keys: "reset" and others
  546. 3. as list of string or dict:
  547. [case1, case2, case3, {"name": "restart from PRO CPU", "child case num": 2}, ...]
  548. :param env: test env instance
  549. :param extra_data: the case name or case list or case dictionary
  550. :return: None
  551. """
  552. case_config = format_test_case_config(extra_data, env.default_dut_cls.TARGET)
  553. # we don't want stop on failed case (unless some special scenarios we can't handle)
  554. # this flag is used to log if any of the case failed during executing
  555. # Before exit test function this flag is used to log if the case fails
  556. failed_cases = []
  557. for ut_config in case_config:
  558. Utility.console_log('Running unit test for config: ' + ut_config, 'O')
  559. dut = env.get_dut('unit-test-app', app_path=UT_APP_PATH, app_config_name=ut_config, allow_dut_exception=True)
  560. if len(case_config[ut_config]) > 0:
  561. replace_app_bin(dut, 'unit-test-app', case_config[ut_config][0].get('app_bin'))
  562. dut.start_app()
  563. for one_case in case_config[ut_config]:
  564. log_test_case('multi-stage test', one_case, ut_config)
  565. performance_items = []
  566. junit_test_case = TinyFW.JunitReport.create_test_case(format_case_name(one_case))
  567. try:
  568. run_one_multiple_stage_case(dut, one_case, junit_test_case)
  569. performance_items = dut.get_performance_items()
  570. except TestCaseFailed:
  571. failed_cases.append(format_case_name(one_case))
  572. except Exception as e:
  573. handle_unexpected_exception(junit_test_case, e)
  574. failed_cases.append(format_case_name(one_case))
  575. finally:
  576. TinyFW.JunitReport.update_performance(performance_items)
  577. TinyFW.JunitReport.test_case_finish(junit_test_case)
  578. # close DUT when finish running all cases for one config
  579. env.close_dut(dut.name)
  580. def detect_update_unit_test_info(env, extra_data, app_bin):
  581. case_config = format_test_case_config(extra_data, env.default_dut_cls.TARGET)
  582. for ut_config in case_config:
  583. dut = env.get_dut('unit-test-app', app_path=UT_APP_PATH, app_config_name=ut_config)
  584. replace_app_bin(dut, 'unit-test-app', app_bin)
  585. dut.start_app()
  586. reset_dut(dut)
  587. # get the list of test cases
  588. dut.write('')
  589. dut.expect("Here's the test menu, pick your combo:", timeout=DEFAULT_TIMEOUT)
  590. def find_update_dic(name, _t, _timeout, child_case_num=None):
  591. for _case_data in extra_data:
  592. if _case_data['name'] == name:
  593. _case_data['type'] = _t
  594. if 'timeout' not in _case_data:
  595. _case_data['timeout'] = _timeout
  596. if child_case_num:
  597. _case_data['child case num'] = child_case_num
  598. try:
  599. while True:
  600. data = dut.expect(TEST_PATTERN, timeout=DEFAULT_TIMEOUT)
  601. test_case_name = data[1]
  602. m = re.search(r'\[timeout=(\d+)\]', data[2])
  603. if m:
  604. timeout = int(m.group(1))
  605. else:
  606. timeout = 30
  607. m = re.search(r'\[multi_stage\]', data[2])
  608. if m:
  609. test_case_type = MULTI_STAGE_ID
  610. else:
  611. m = re.search(r'\[multi_device\]', data[2])
  612. if m:
  613. test_case_type = MULTI_DEVICE_ID
  614. else:
  615. test_case_type = SIMPLE_TEST_ID
  616. find_update_dic(test_case_name, test_case_type, timeout)
  617. if data[3] and re.search(END_LIST_STR, data[3]):
  618. break
  619. continue
  620. # find the last submenu item
  621. data = dut.expect(TEST_SUBMENU_PATTERN, timeout=DEFAULT_TIMEOUT)
  622. find_update_dic(test_case_name, test_case_type, timeout, child_case_num=int(data[0]))
  623. if data[1] and re.search(END_LIST_STR, data[1]):
  624. break
  625. # check if the unit test case names are correct, i.e. they could be found in the device
  626. for _dic in extra_data:
  627. if 'type' not in _dic:
  628. raise ValueError("Unit test \"{}\" doesn't exist in the flashed device!".format(_dic.get('name')))
  629. except DUT.ExpectTimeout:
  630. Utility.console_log('Timeout during getting the test list', color='red')
  631. finally:
  632. dut.close()
  633. # These options are the same for all configs, therefore there is no need to continue
  634. break
  635. if __name__ == '__main__':
  636. parser = argparse.ArgumentParser()
  637. parser.add_argument(
  638. '--repeat', '-r',
  639. help='Number of repetitions for the test(s). Default is 1.',
  640. type=int,
  641. default=1
  642. )
  643. parser.add_argument('--env_config_file', '-e',
  644. help='test env config file',
  645. default=None)
  646. parser.add_argument('--app_bin', '-b',
  647. help='application binary file for flashing the chip',
  648. default=None)
  649. parser.add_argument('test',
  650. help='Comma separated list of <option>:<argument> where option can be "name" (default), '
  651. '"child case num", "config", "timeout".',
  652. nargs='+')
  653. args = parser.parse_args()
  654. list_of_dicts = []
  655. for test in args.test:
  656. test_args = test.split(r',')
  657. test_dict = dict()
  658. for test_item in test_args:
  659. if len(test_item) == 0:
  660. continue
  661. pair = test_item.split(r':', 1)
  662. if len(pair) == 1 or pair[0] == 'name':
  663. test_dict['name'] = pair[0]
  664. elif len(pair) == 2:
  665. if pair[0] == 'timeout' or pair[0] == 'child case num':
  666. test_dict[pair[0]] = int(pair[1])
  667. else:
  668. test_dict[pair[0]] = pair[1]
  669. else:
  670. raise ValueError('Error in argument item {} of {}'.format(test_item, test))
  671. test_dict['app_bin'] = args.app_bin
  672. list_of_dicts.append(test_dict)
  673. TinyFW.set_default_config(env_config_file=args.env_config_file)
  674. env_config = TinyFW.get_default_config()
  675. env_config['app'] = ttfw_idf.UT
  676. env_config['dut'] = ttfw_idf.IDFDUT
  677. env_config['test_suite_name'] = 'unit_test_parsing'
  678. test_env = Env.Env(**env_config)
  679. detect_update_unit_test_info(test_env, extra_data=list_of_dicts, app_bin=args.app_bin)
  680. for index in range(1, args.repeat + 1):
  681. if args.repeat > 1:
  682. Utility.console_log('Repetition {}'.format(index), color='green')
  683. for dic in list_of_dicts:
  684. t = dic.get('type', SIMPLE_TEST_ID)
  685. if t == SIMPLE_TEST_ID:
  686. run_unit_test_cases(extra_data=dic)
  687. elif t == MULTI_STAGE_ID:
  688. run_multiple_stage_cases(extra_data=dic)
  689. elif t == MULTI_DEVICE_ID:
  690. run_multiple_devices_cases(extra_data=dic)
  691. else:
  692. raise ValueError('Unknown type {} of {}'.format(t, dic.get('name')))