unit_test.py 32 KB

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