unit_test.py 27 KB

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