unit_test.py 27 KB

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