unit_test.py 32 KB

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