unit_test.py 32 KB

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