DUT.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703
  1. # Copyright 2015-2017 Espressif Systems (Shanghai) PTE LTD
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http:#www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """
  15. DUT provides 3 major groups of features:
  16. * DUT port feature, provide basic open/close/read/write features
  17. * DUT tools, provide extra methods to control the device, like download and start app
  18. * DUT expect method, provide features for users to check DUT outputs
  19. The current design of DUT have 3 classes for one DUT: BaseDUT, DUTPort, DUTTool.
  20. * BaseDUT class:
  21. * defines methods DUT port and DUT tool need to overwrite
  22. * provide the expect methods and some other methods based on DUTPort
  23. * DUTPort class:
  24. * inherent from BaseDUT class
  25. * implements the port features by overwriting port methods defined in BaseDUT
  26. * DUTTool class:
  27. * inherent from one of the DUTPort class
  28. * implements the tools features by overwriting tool methods defined in BaseDUT
  29. * could add some new methods provided by the tool
  30. This module implements the BaseDUT class and one of the port class SerialDUT.
  31. User should implement their DUTTool classes.
  32. If they using different port then need to implement their DUTPort class as well.
  33. """
  34. import time
  35. import re
  36. import threading
  37. import copy
  38. import sys
  39. import functools
  40. import serial
  41. from serial.tools import list_ports
  42. import Utility
  43. if sys.version_info[0] == 2:
  44. import Queue as _queue
  45. else:
  46. import queue as _queue
  47. class ExpectTimeout(ValueError):
  48. """ timeout for expect method """
  49. pass
  50. class UnsupportedExpectItem(ValueError):
  51. """ expect item not supported by the expect method """
  52. pass
  53. def _expect_lock(func):
  54. @functools.wraps(func)
  55. def handler(self, *args, **kwargs):
  56. with self.expect_lock:
  57. ret = func(self, *args, **kwargs)
  58. return ret
  59. return handler
  60. def _decode_data(data):
  61. """ for python3, if the data is bytes, then decode it to string """
  62. if isinstance(data, bytes):
  63. # convert bytes to string
  64. try:
  65. data = data.decode("utf-8", "ignore")
  66. except UnicodeDecodeError:
  67. data = data.decode("iso8859-1", )
  68. return data
  69. def _pattern_to_string(pattern):
  70. try:
  71. ret = "RegEx: " + pattern.pattern
  72. except AttributeError:
  73. ret = pattern
  74. return ret
  75. class _DataCache(_queue.Queue):
  76. """
  77. Data cache based on Queue. Allow users to process data cache based on bytes instead of Queue."
  78. """
  79. def __init__(self, maxsize=0):
  80. _queue.Queue.__init__(self, maxsize=maxsize)
  81. self.data_cache = str()
  82. def _move_from_queue_to_cache(self):
  83. """
  84. move all of the available data in the queue to cache
  85. :return: True if moved any item from queue to data cache, else False
  86. """
  87. ret = False
  88. while True:
  89. try:
  90. self.data_cache += _decode_data(self.get(0))
  91. ret = True
  92. except _queue.Empty:
  93. break
  94. return ret
  95. def get_data(self, timeout=0.0):
  96. """
  97. get a copy of data from cache.
  98. :param timeout: timeout for waiting new queue item
  99. :return: copy of data cache
  100. """
  101. # make sure timeout is non-negative
  102. if timeout < 0:
  103. timeout = 0
  104. ret = self._move_from_queue_to_cache()
  105. if not ret:
  106. # we only wait for new data if we can't provide a new data_cache
  107. try:
  108. data = self.get(timeout=timeout)
  109. self.data_cache += _decode_data(data)
  110. except _queue.Empty:
  111. # don't do anything when on update for cache
  112. pass
  113. return copy.deepcopy(self.data_cache)
  114. def flush(self, index=0xFFFFFFFF):
  115. """
  116. flush data from cache.
  117. :param index: if < 0 then don't do flush, otherwise flush data before index
  118. :return: None
  119. """
  120. # first add data in queue to cache
  121. self.get_data()
  122. if index > 0:
  123. self.data_cache = self.data_cache[index:]
  124. class _LogThread(threading.Thread, _queue.Queue):
  125. """
  126. We found some SD card on Raspberry Pi could have very bad performance.
  127. It could take seconds to save small amount of data.
  128. If the DUT receives data and save it as log, then it stops receiving data until log is saved.
  129. This could lead to expect timeout.
  130. As an workaround to this issue, ``BaseDUT`` class will create a thread to save logs.
  131. Then data will be passed to ``expect`` as soon as received.
  132. """
  133. def __init__(self):
  134. threading.Thread.__init__(self, name="LogThread")
  135. _queue.Queue.__init__(self, maxsize=0)
  136. self.setDaemon(True)
  137. self.flush_lock = threading.Lock()
  138. def save_log(self, filename, data):
  139. """
  140. :param filename: log file name
  141. :param data: log data. Must be ``bytes``.
  142. """
  143. self.put({"filename": filename, "data": data})
  144. def flush_data(self):
  145. with self.flush_lock:
  146. data_cache = dict()
  147. while True:
  148. # move all data from queue to data cache
  149. try:
  150. log = self.get_nowait()
  151. try:
  152. data_cache[log["filename"]] += log["data"]
  153. except KeyError:
  154. data_cache[log["filename"]] = log["data"]
  155. except _queue.Empty:
  156. break
  157. # flush data
  158. for filename in data_cache:
  159. with open(filename, "ab+") as f:
  160. f.write(data_cache[filename])
  161. def run(self):
  162. while True:
  163. time.sleep(1)
  164. self.flush_data()
  165. class _RecvThread(threading.Thread):
  166. PERFORMANCE_PATTERN = re.compile(r"\[Performance]\[(\w+)]: ([^\r\n]+)\r?\n")
  167. def __init__(self, read, data_cache):
  168. super(_RecvThread, self).__init__()
  169. self.exit_event = threading.Event()
  170. self.setDaemon(True)
  171. self.read = read
  172. self.data_cache = data_cache
  173. # cache the last line of recv data for collecting performance
  174. self._line_cache = str()
  175. def collect_performance(self, data):
  176. """ collect performance """
  177. if data:
  178. decoded_data = _decode_data(data)
  179. matches = self.PERFORMANCE_PATTERN.findall(self._line_cache + decoded_data)
  180. for match in matches:
  181. Utility.console_log("[Performance][{}]: {}".format(match[0], match[1]),
  182. color="orange")
  183. # cache incomplete line to later process
  184. lines = decoded_data.splitlines(True)
  185. last_line = lines[-1]
  186. if last_line[-1] != "\n":
  187. if len(lines) == 1:
  188. # only one line and the line is not finished, then append this to cache
  189. self._line_cache += lines[-1]
  190. else:
  191. # more than one line and not finished, replace line cache
  192. self._line_cache = lines[-1]
  193. else:
  194. # line finishes, flush cache
  195. self._line_cache = str()
  196. def run(self):
  197. while not self.exit_event.isSet():
  198. data = self.read(1000)
  199. if data:
  200. self.data_cache.put(data)
  201. self.collect_performance(data)
  202. def exit(self):
  203. self.exit_event.set()
  204. self.join()
  205. class BaseDUT(object):
  206. """
  207. :param name: application defined name for port
  208. :param port: comport name, used to create DUT port
  209. :param log_file: log file name
  210. :param app: test app instance
  211. :param kwargs: extra args for DUT to create ports
  212. """
  213. DEFAULT_EXPECT_TIMEOUT = 10
  214. MAX_EXPECT_FAILURES_TO_SAVED = 10
  215. LOG_THREAD = _LogThread()
  216. LOG_THREAD.start()
  217. def __init__(self, name, port, log_file, app, **kwargs):
  218. self.expect_lock = threading.Lock()
  219. self.name = name
  220. self.port = port
  221. self.log_file = log_file
  222. self.app = app
  223. self.data_cache = _DataCache()
  224. self.receive_thread = None
  225. self.expect_failures = []
  226. # open and start during init
  227. self.open()
  228. def __str__(self):
  229. return "DUT({}: {})".format(self.name, str(self.port))
  230. def _save_expect_failure(self, pattern, data, start_time):
  231. """
  232. Save expect failure. If the test fails, then it will print the expect failures.
  233. In some cases, user will handle expect exceptions.
  234. The expect failures could be false alarm, and test case might generate a lot of such failures.
  235. Therefore, we don't print the failure immediately and limit the max size of failure list.
  236. """
  237. self.expect_failures.insert(0, {"pattern": pattern, "data": data,
  238. "start": start_time, "end": time.time()})
  239. self.expect_failures = self.expect_failures[:self.MAX_EXPECT_FAILURES_TO_SAVED]
  240. def _save_dut_log(self, data):
  241. """
  242. Save DUT log into file using another thread.
  243. This is a workaround for some devices takes long time for file system operations.
  244. See descriptions in ``_LogThread`` for details.
  245. """
  246. self.LOG_THREAD.save_log(self.log_file, data)
  247. # define for methods need to be overwritten by Port
  248. @classmethod
  249. def list_available_ports(cls):
  250. """
  251. list all available ports.
  252. subclass (port) must overwrite this method.
  253. :return: list of available comports
  254. """
  255. pass
  256. def _port_open(self):
  257. """
  258. open the port.
  259. subclass (port) must overwrite this method.
  260. :return: None
  261. """
  262. pass
  263. def _port_read(self, size=1):
  264. """
  265. read form port. This method should not blocking for long time, otherwise receive thread can not exit.
  266. subclass (port) must overwrite this method.
  267. :param size: max size to read.
  268. :return: read data.
  269. """
  270. pass
  271. def _port_write(self, data):
  272. """
  273. write to port.
  274. subclass (port) must overwrite this method.
  275. :param data: data to write
  276. :return: None
  277. """
  278. pass
  279. def _port_close(self):
  280. """
  281. close port.
  282. subclass (port) must overwrite this method.
  283. :return: None
  284. """
  285. pass
  286. # methods that need to be overwritten by Tool
  287. @classmethod
  288. def confirm_dut(cls, port, app, **kwargs):
  289. """
  290. confirm if it's a DUT, usually used by auto detecting DUT in by Env config.
  291. subclass (tool) must overwrite this method.
  292. :param port: comport
  293. :param app: app instance
  294. :return: True or False
  295. """
  296. pass
  297. def start_app(self):
  298. """
  299. usually after we got DUT, we need to do some extra works to let App start.
  300. For example, we need to reset->download->reset to let IDF application start on DUT.
  301. subclass (tool) must overwrite this method.
  302. :return: None
  303. """
  304. pass
  305. # methods that features raw port methods
  306. def open(self):
  307. """
  308. open port and create thread to receive data.
  309. :return: None
  310. """
  311. self._port_open()
  312. self.receive_thread = _RecvThread(self._port_read, self.data_cache)
  313. self.receive_thread.start()
  314. def close(self):
  315. """
  316. close receive thread and then close port.
  317. :return: None
  318. """
  319. if self.receive_thread:
  320. self.receive_thread.exit()
  321. self._port_close()
  322. self.LOG_THREAD.flush_data()
  323. def write(self, data, eol="\r\n", flush=True):
  324. """
  325. :param data: data
  326. :param eol: end of line pattern.
  327. :param flush: if need to flush received data cache before write data.
  328. usually we need to flush data before write,
  329. make sure processing outputs generated by wrote.
  330. :return: None
  331. """
  332. # do flush before write
  333. if flush:
  334. self.data_cache.flush()
  335. # do write if cache
  336. if data is not None:
  337. self._port_write(data + eol if eol else data)
  338. @_expect_lock
  339. def read(self, size=0xFFFFFFFF):
  340. """
  341. read(size=0xFFFFFFFF)
  342. read raw data. NOT suggested to use this method.
  343. Only use it if expect method doesn't meet your requirement.
  344. :param size: read size. default read all data
  345. :return: read data
  346. """
  347. data = self.data_cache.get_data(0)[:size]
  348. self.data_cache.flush(size)
  349. return data
  350. # expect related methods
  351. @staticmethod
  352. def _expect_str(data, pattern):
  353. """
  354. protected method. check if string is matched in data cache.
  355. :param data: data to process
  356. :param pattern: string
  357. :return: pattern if match succeed otherwise None
  358. """
  359. index = data.find(pattern)
  360. if index != -1:
  361. ret = pattern
  362. index += len(pattern)
  363. else:
  364. ret = None
  365. return ret, index
  366. @staticmethod
  367. def _expect_re(data, pattern):
  368. """
  369. protected method. check if re pattern is matched in data cache
  370. :param data: data to process
  371. :param pattern: compiled RegEx pattern
  372. :return: match groups if match succeed otherwise None
  373. """
  374. ret = None
  375. match = pattern.search(data)
  376. if match:
  377. ret = match.groups()
  378. index = match.end()
  379. else:
  380. index = -1
  381. return ret, index
  382. EXPECT_METHOD = [
  383. [type(re.compile("")), "_expect_re"],
  384. [str, "_expect_str"],
  385. ]
  386. def _get_expect_method(self, pattern):
  387. """
  388. protected method. get expect method according to pattern type.
  389. :param pattern: expect pattern, string or compiled RegEx
  390. :return: ``_expect_str`` or ``_expect_re``
  391. """
  392. for expect_method in self.EXPECT_METHOD:
  393. if isinstance(pattern, expect_method[0]):
  394. method = expect_method[1]
  395. break
  396. else:
  397. raise UnsupportedExpectItem()
  398. return self.__getattribute__(method)
  399. @_expect_lock
  400. def expect(self, pattern, timeout=DEFAULT_EXPECT_TIMEOUT):
  401. """
  402. expect(pattern, timeout=DEFAULT_EXPECT_TIMEOUT)
  403. expect received data on DUT match the pattern. will raise exception when expect timeout.
  404. :raise ExpectTimeout: failed to find the pattern before timeout
  405. :raise UnsupportedExpectItem: pattern is not string or compiled RegEx
  406. :param pattern: string or compiled RegEx(string pattern)
  407. :param timeout: timeout for expect
  408. :return: string if pattern is string; matched groups if pattern is RegEx
  409. """
  410. method = self._get_expect_method(pattern)
  411. # non-blocking get data for first time
  412. data = self.data_cache.get_data(0)
  413. start_time = time.time()
  414. while True:
  415. ret, index = method(data, pattern)
  416. if ret is not None:
  417. self.data_cache.flush(index)
  418. break
  419. time_remaining = start_time + timeout - time.time()
  420. if time_remaining < 0:
  421. break
  422. # wait for new data from cache
  423. data = self.data_cache.get_data(time_remaining)
  424. if ret is None:
  425. pattern = _pattern_to_string(pattern)
  426. self._save_expect_failure(pattern, data, start_time)
  427. raise ExpectTimeout(self.name + ": " + pattern)
  428. return ret
  429. def _expect_multi(self, expect_all, expect_item_list, timeout):
  430. """
  431. protected method. internal logical for expect multi.
  432. :param expect_all: True or False, expect all items in the list or any in the list
  433. :param expect_item_list: expect item list
  434. :param timeout: timeout
  435. :return: None
  436. """
  437. def process_expected_item(item_raw):
  438. # convert item raw data to standard dict
  439. item = {
  440. "pattern": item_raw[0] if isinstance(item_raw, tuple) else item_raw,
  441. "method": self._get_expect_method(item_raw[0] if isinstance(item_raw, tuple)
  442. else item_raw),
  443. "callback": item_raw[1] if isinstance(item_raw, tuple) else None,
  444. "index": -1,
  445. "ret": None,
  446. }
  447. return item
  448. expect_items = [process_expected_item(x) for x in expect_item_list]
  449. # non-blocking get data for first time
  450. data = self.data_cache.get_data(0)
  451. start_time = time.time()
  452. matched_expect_items = list()
  453. while True:
  454. for expect_item in expect_items:
  455. if expect_item not in matched_expect_items:
  456. # exclude those already matched
  457. expect_item["ret"], expect_item["index"] = \
  458. expect_item["method"](data, expect_item["pattern"])
  459. if expect_item["ret"] is not None:
  460. # match succeed for one item
  461. matched_expect_items.append(expect_item)
  462. # if expect all, then all items need to be matched,
  463. # else only one item need to matched
  464. if expect_all:
  465. match_succeed = len(matched_expect_items) == len(expect_items)
  466. else:
  467. match_succeed = True if matched_expect_items else False
  468. time_remaining = start_time + timeout - time.time()
  469. if time_remaining < 0 or match_succeed:
  470. break
  471. else:
  472. data = self.data_cache.get_data(time_remaining)
  473. if match_succeed:
  474. # do callback and flush matched data cache
  475. slice_index = -1
  476. for expect_item in matched_expect_items:
  477. # trigger callback
  478. if expect_item["callback"]:
  479. expect_item["callback"](expect_item["ret"])
  480. slice_index = max(slice_index, expect_item["index"])
  481. # flush already matched data
  482. self.data_cache.flush(slice_index)
  483. else:
  484. pattern = str([_pattern_to_string(x["pattern"]) for x in expect_items])
  485. self._save_expect_failure(pattern, data, start_time)
  486. raise ExpectTimeout(self.name + ": " + pattern)
  487. @_expect_lock
  488. def expect_any(self, *expect_items, **timeout):
  489. """
  490. expect_any(*expect_items, timeout=DEFAULT_TIMEOUT)
  491. expect any of the patterns.
  492. will call callback (if provided) if pattern match succeed and then return.
  493. will pass match result to the callback.
  494. :raise ExpectTimeout: failed to match any one of the expect items before timeout
  495. :raise UnsupportedExpectItem: pattern in expect_item is not string or compiled RegEx
  496. :arg expect_items: one or more expect items.
  497. string, compiled RegEx pattern or (string or RegEx(string pattern), callback)
  498. :keyword timeout: timeout for expect
  499. :return: None
  500. """
  501. # to be compatible with python2
  502. # in python3 we can write f(self, *expect_items, timeout=DEFAULT_TIMEOUT)
  503. if "timeout" not in timeout:
  504. timeout["timeout"] = self.DEFAULT_EXPECT_TIMEOUT
  505. return self._expect_multi(False, expect_items, **timeout)
  506. @_expect_lock
  507. def expect_all(self, *expect_items, **timeout):
  508. """
  509. expect_all(*expect_items, timeout=DEFAULT_TIMEOUT)
  510. expect all of the patterns.
  511. will call callback (if provided) if all pattern match succeed and then return.
  512. will pass match result to the callback.
  513. :raise ExpectTimeout: failed to match all of the expect items before timeout
  514. :raise UnsupportedExpectItem: pattern in expect_item is not string or compiled RegEx
  515. :arg expect_items: one or more expect items.
  516. string, compiled RegEx pattern or (string or RegEx(string pattern), callback)
  517. :keyword timeout: timeout for expect
  518. :return: None
  519. """
  520. # to be compatible with python2
  521. # in python3 we can write f(self, *expect_items, timeout=DEFAULT_TIMEOUT)
  522. if "timeout" not in timeout:
  523. timeout["timeout"] = self.DEFAULT_EXPECT_TIMEOUT
  524. return self._expect_multi(True, expect_items, **timeout)
  525. @staticmethod
  526. def _format_ts(ts):
  527. return "{}:{}".format(time.strftime("%m-%d %H:%M:%S", time.localtime(ts)), str(ts % 1)[2:5])
  528. def print_debug_info(self):
  529. """
  530. Print debug info of current DUT. Currently we will print debug info for expect failures.
  531. """
  532. Utility.console_log("DUT debug info for DUT: {}:".format(self.name), color="orange")
  533. for failure in self.expect_failures:
  534. Utility.console_log(u"\t[pattern]: {}\r\n\t[data]: {}\r\n\t[time]: {} - {}\r\n"
  535. .format(failure["pattern"], failure["data"],
  536. self._format_ts(failure["start"]), self._format_ts(failure["end"])),
  537. color="orange")
  538. class SerialDUT(BaseDUT):
  539. """ serial with logging received data feature """
  540. DEFAULT_UART_CONFIG = {
  541. "baudrate": 115200,
  542. "bytesize": serial.EIGHTBITS,
  543. "parity": serial.PARITY_NONE,
  544. "stopbits": serial.STOPBITS_ONE,
  545. "timeout": 0.05,
  546. "xonxoff": False,
  547. "rtscts": False,
  548. }
  549. def __init__(self, name, port, log_file, app, **kwargs):
  550. self.port_inst = None
  551. self.serial_configs = self.DEFAULT_UART_CONFIG.copy()
  552. self.serial_configs.update(kwargs)
  553. super(SerialDUT, self).__init__(name, port, log_file, app, **kwargs)
  554. def _format_data(self, data):
  555. """
  556. format data for logging. do decode and add timestamp.
  557. :param data: raw data from read
  558. :return: formatted data (str)
  559. """
  560. timestamp = "[{}]".format(self._format_ts(time.time()))
  561. formatted_data = timestamp.encode() + b"\r\n" + data + b"\r\n"
  562. return formatted_data
  563. def _port_open(self):
  564. self.port_inst = serial.Serial(self.port, **self.serial_configs)
  565. def _port_close(self):
  566. self.port_inst.close()
  567. def _port_read(self, size=1):
  568. data = self.port_inst.read(size)
  569. if data:
  570. self._save_dut_log(self._format_data(data))
  571. return data
  572. def _port_write(self, data):
  573. if isinstance(data, str):
  574. data = data.encode()
  575. self.port_inst.write(data)
  576. @classmethod
  577. def list_available_ports(cls):
  578. return [x.device for x in list_ports.comports()]