DUT.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801
  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. from __future__ import print_function
  35. import copy
  36. import functools
  37. import re
  38. import sys
  39. import threading
  40. import time
  41. # python2 and python3 queue package name is different
  42. try:
  43. import Queue as _queue
  44. except ImportError:
  45. import queue as _queue # type: ignore
  46. try:
  47. from typing import Callable, List
  48. except ImportError:
  49. # Only used for type annotations
  50. pass
  51. import serial
  52. from serial.tools import list_ports
  53. from . import Utility
  54. class ExpectTimeout(ValueError):
  55. """ timeout for expect method """
  56. pass
  57. class UnsupportedExpectItem(ValueError):
  58. """ expect item not supported by the expect method """
  59. pass
  60. def _expect_lock(func):
  61. @functools.wraps(func)
  62. def handler(self, *args, **kwargs):
  63. with self.expect_lock:
  64. ret = func(self, *args, **kwargs)
  65. return ret
  66. return handler
  67. def _decode_data(data):
  68. """ for python3, if the data is bytes, then decode it to string """
  69. if isinstance(data, bytes):
  70. # convert bytes to string. This is a bit of a hack, we know that we want to log this
  71. # later so encode to the stdout encoding with backslash escapes for anything non-encodable
  72. try:
  73. return data.decode(sys.stdout.encoding, 'backslashreplace')
  74. except UnicodeDecodeError: # Python <3.5 doesn't support backslashreplace
  75. return data.decode(sys.stdout.encoding, 'replace')
  76. return data
  77. def _pattern_to_string(pattern):
  78. try:
  79. ret = 'RegEx: ' + pattern.pattern
  80. except AttributeError:
  81. ret = pattern
  82. return ret
  83. class _DataCache(_queue.Queue):
  84. """
  85. Data cache based on Queue. Allow users to process data cache based on bytes instead of Queue."
  86. """
  87. def __init__(self, maxsize=0):
  88. _queue.Queue.__init__(self, maxsize=maxsize)
  89. self.data_cache = str()
  90. def _move_from_queue_to_cache(self):
  91. """
  92. move all of the available data in the queue to cache
  93. :return: True if moved any item from queue to data cache, else False
  94. """
  95. ret = False
  96. while True:
  97. try:
  98. self.data_cache += _decode_data(self.get(0))
  99. ret = True
  100. except _queue.Empty:
  101. break
  102. return ret
  103. def get_data(self, timeout=0.0):
  104. """
  105. get a copy of data from cache.
  106. :param timeout: timeout for waiting new queue item
  107. :return: copy of data cache
  108. """
  109. # make sure timeout is non-negative
  110. if timeout < 0:
  111. timeout = 0
  112. ret = self._move_from_queue_to_cache()
  113. if not ret:
  114. # we only wait for new data if we can't provide a new data_cache
  115. try:
  116. data = self.get(timeout=timeout)
  117. self.data_cache += _decode_data(data)
  118. except _queue.Empty:
  119. # don't do anything when on update for cache
  120. pass
  121. return copy.deepcopy(self.data_cache)
  122. def flush(self, index=0xFFFFFFFF):
  123. """
  124. flush data from cache.
  125. :param index: if < 0 then don't do flush, otherwise flush data before index
  126. :return: None
  127. """
  128. # first add data in queue to cache
  129. self.get_data()
  130. if index > 0:
  131. self.data_cache = self.data_cache[index:]
  132. class _LogThread(threading.Thread, _queue.Queue):
  133. """
  134. We found some SD card on Raspberry Pi could have very bad performance.
  135. It could take seconds to save small amount of data.
  136. If the DUT receives data and save it as log, then it stops receiving data until log is saved.
  137. This could lead to expect timeout.
  138. As an workaround to this issue, ``BaseDUT`` class will create a thread to save logs.
  139. Then data will be passed to ``expect`` as soon as received.
  140. """
  141. def __init__(self):
  142. threading.Thread.__init__(self, name='LogThread')
  143. _queue.Queue.__init__(self, maxsize=0)
  144. self.setDaemon(True)
  145. self.flush_lock = threading.Lock()
  146. def save_log(self, filename, data):
  147. """
  148. :param filename: log file name
  149. :param data: log data. Must be ``bytes``.
  150. """
  151. self.put({'filename': filename, 'data': data})
  152. def flush_data(self):
  153. with self.flush_lock:
  154. data_cache = dict()
  155. while True:
  156. # move all data from queue to data cache
  157. try:
  158. log = self.get_nowait()
  159. try:
  160. data_cache[log['filename']] += log['data']
  161. except KeyError:
  162. data_cache[log['filename']] = log['data']
  163. except _queue.Empty:
  164. break
  165. # flush data
  166. for filename in data_cache:
  167. with open(filename, 'ab+') as f:
  168. f.write(data_cache[filename])
  169. def run(self):
  170. while True:
  171. time.sleep(1)
  172. self.flush_data()
  173. class RecvThread(threading.Thread):
  174. CHECK_FUNCTIONS = [] # type: List[Callable]
  175. """ DUT subclass can define a few check functions to process received data. """
  176. def __init__(self, read, dut):
  177. super(RecvThread, self).__init__()
  178. self.exit_event = threading.Event()
  179. self.setDaemon(True)
  180. self.read = read
  181. self.dut = dut
  182. self.data_cache = dut.data_cache
  183. self.recorded_data = dut.recorded_data
  184. self.record_data_lock = dut.record_data_lock
  185. self._line_cache = str()
  186. def _line_completion(self, data):
  187. """
  188. Usually check functions requires to check for one complete line.
  189. This method will do line completion for the first line, and strip incomplete last line.
  190. """
  191. ret = self._line_cache
  192. decoded_data = _decode_data(data)
  193. # cache incomplete line to later process
  194. lines = decoded_data.splitlines(True)
  195. last_line = lines[-1]
  196. if last_line[-1] != '\n':
  197. if len(lines) == 1:
  198. # only one line and the line is not finished, then append this to cache
  199. self._line_cache += lines[-1]
  200. ret = str()
  201. else:
  202. # more than one line and not finished, replace line cache
  203. self._line_cache = lines[-1]
  204. ret += ''.join(lines[:-1])
  205. else:
  206. # line finishes, flush cache
  207. self._line_cache = str()
  208. ret += decoded_data
  209. return ret
  210. def run(self):
  211. while not self.exit_event.isSet():
  212. raw_data = self.read(1000)
  213. if raw_data:
  214. # we need to do line completion before call check functions
  215. # need to call check functions first
  216. # otherwise check functions could be called after cases finished
  217. comp_data = self._line_completion(raw_data)
  218. for check_function in self.CHECK_FUNCTIONS:
  219. check_function(self, comp_data)
  220. with self.record_data_lock:
  221. self.data_cache.put(raw_data)
  222. for capture_id in self.recorded_data:
  223. self.recorded_data[capture_id].put(raw_data)
  224. def exit(self):
  225. self.exit_event.set()
  226. self.join()
  227. class BaseDUT(object):
  228. """
  229. :param name: application defined name for port
  230. :param port: comport name, used to create DUT port
  231. :param log_file: log file name
  232. :param app: test app instance
  233. :param kwargs: extra args for DUT to create ports
  234. """
  235. DEFAULT_EXPECT_TIMEOUT = 10
  236. MAX_EXPECT_FAILURES_TO_SAVED = 10
  237. RECV_THREAD_CLS = RecvThread
  238. TARGET = None
  239. """ DUT subclass can specify RECV_THREAD_CLS to do add some extra stuff when receive data.
  240. For example, DUT can implement exception detect & analysis logic in receive thread subclass. """
  241. LOG_THREAD = _LogThread()
  242. LOG_THREAD.start()
  243. def __init__(self, name, port, log_file, app, **kwargs):
  244. self.expect_lock = threading.Lock()
  245. self.name = name
  246. self.port = port
  247. self.log_file = log_file
  248. self.app = app
  249. self.data_cache = _DataCache()
  250. # the main process of recorded data are done in receive thread
  251. # but receive thread could be closed in DUT lifetime (tool methods)
  252. # so we keep it in BaseDUT, as their life cycle are same
  253. self.recorded_data = dict()
  254. self.record_data_lock = threading.RLock()
  255. self.receive_thread = None
  256. self.expect_failures = []
  257. self._port_open()
  258. self.start_receive()
  259. def __str__(self):
  260. return 'DUT({}: {})'.format(self.name, str(self.port))
  261. def _save_expect_failure(self, pattern, data, start_time):
  262. """
  263. Save expect failure. If the test fails, then it will print the expect failures.
  264. In some cases, user will handle expect exceptions.
  265. The expect failures could be false alarm, and test case might generate a lot of such failures.
  266. Therefore, we don't print the failure immediately and limit the max size of failure list.
  267. """
  268. self.expect_failures.insert(0, {'pattern': pattern, 'data': data,
  269. 'start': start_time, 'end': time.time()})
  270. self.expect_failures = self.expect_failures[:self.MAX_EXPECT_FAILURES_TO_SAVED]
  271. def _save_dut_log(self, data):
  272. """
  273. Save DUT log into file using another thread.
  274. This is a workaround for some devices takes long time for file system operations.
  275. See descriptions in ``_LogThread`` for details.
  276. """
  277. self.LOG_THREAD.save_log(self.log_file, data)
  278. # define for methods need to be overwritten by Port
  279. @classmethod
  280. def list_available_ports(cls):
  281. """
  282. list all available ports.
  283. subclass (port) must overwrite this method.
  284. :return: list of available comports
  285. """
  286. pass
  287. def _port_open(self):
  288. """
  289. open the port.
  290. subclass (port) must overwrite this method.
  291. :return: None
  292. """
  293. pass
  294. def _port_read(self, size=1):
  295. """
  296. read form port. This method should not blocking for long time, otherwise receive thread can not exit.
  297. subclass (port) must overwrite this method.
  298. :param size: max size to read.
  299. :return: read data.
  300. """
  301. pass
  302. def _port_write(self, data):
  303. """
  304. write to port.
  305. subclass (port) must overwrite this method.
  306. :param data: data to write
  307. :return: None
  308. """
  309. pass
  310. def _port_close(self):
  311. """
  312. close port.
  313. subclass (port) must overwrite this method.
  314. :return: None
  315. """
  316. pass
  317. # methods that need to be overwritten by Tool
  318. @classmethod
  319. def confirm_dut(cls, port, **kwargs):
  320. """
  321. confirm if it's a DUT, usually used by auto detecting DUT in by Env config.
  322. subclass (tool) must overwrite this method.
  323. :param port: comport
  324. :return: tuple of result (bool), and target (str)
  325. """
  326. pass
  327. def start_app(self):
  328. """
  329. usually after we got DUT, we need to do some extra works to let App start.
  330. For example, we need to reset->download->reset to let IDF application start on DUT.
  331. subclass (tool) must overwrite this method.
  332. :return: None
  333. """
  334. pass
  335. # methods that features raw port methods
  336. def start_receive(self):
  337. """
  338. Start thread to receive data.
  339. :return: None
  340. """
  341. self.receive_thread = self.RECV_THREAD_CLS(self._port_read, self)
  342. self.receive_thread.start()
  343. def stop_receive(self):
  344. """
  345. stop the receiving thread for the port
  346. :return: None
  347. """
  348. if self.receive_thread:
  349. self.receive_thread.exit()
  350. self.LOG_THREAD.flush_data()
  351. self.receive_thread = None
  352. def close(self):
  353. """
  354. permanently close the port
  355. """
  356. self.stop_receive()
  357. self._port_close()
  358. @staticmethod
  359. def u_to_bytearray(data):
  360. """
  361. if data is not bytearray then it tries to convert it
  362. :param data: data which needs to be checked and maybe transformed
  363. """
  364. if isinstance(data, type(u'')):
  365. try:
  366. data = data.encode('utf-8')
  367. except UnicodeEncodeError as e:
  368. print(u'Cannot encode {} of type {}'.format(data, type(data)))
  369. raise e
  370. return data
  371. def write(self, data, eol='\r\n', flush=True):
  372. """
  373. :param data: data
  374. :param eol: end of line pattern.
  375. :param flush: if need to flush received data cache before write data.
  376. usually we need to flush data before write,
  377. make sure processing outputs generated by wrote.
  378. :return: None
  379. """
  380. # do flush before write
  381. if flush:
  382. self.data_cache.flush()
  383. # do write if cache
  384. if data is not None:
  385. self._port_write(self.u_to_bytearray(data) + self.u_to_bytearray(eol) if eol else self.u_to_bytearray(data))
  386. @_expect_lock
  387. def read(self, size=0xFFFFFFFF):
  388. """
  389. read(size=0xFFFFFFFF)
  390. read raw data. NOT suggested to use this method.
  391. Only use it if expect method doesn't meet your requirement.
  392. :param size: read size. default read all data
  393. :return: read data
  394. """
  395. data = self.data_cache.get_data(0)[:size]
  396. self.data_cache.flush(size)
  397. return data
  398. def start_capture_raw_data(self, capture_id='default'):
  399. """
  400. Sometime application want to get DUT raw data and use ``expect`` method at the same time.
  401. Capture methods provides a way to get raw data without affecting ``expect`` or ``read`` method.
  402. If you call ``start_capture_raw_data`` with same capture id again, it will restart capture on this ID.
  403. :param capture_id: ID of capture. You can use different IDs to do different captures at the same time.
  404. """
  405. with self.record_data_lock:
  406. try:
  407. # if start capture on existed ID, we do flush data and restart capture
  408. self.recorded_data[capture_id].flush()
  409. except KeyError:
  410. # otherwise, create new data cache
  411. self.recorded_data[capture_id] = _DataCache()
  412. def stop_capture_raw_data(self, capture_id='default'):
  413. """
  414. Stop capture and get raw data.
  415. This method should be used after ``start_capture_raw_data`` on the same capture ID.
  416. :param capture_id: ID of capture.
  417. :return: captured raw data between start capture and stop capture.
  418. """
  419. with self.record_data_lock:
  420. try:
  421. ret = self.recorded_data[capture_id].get_data()
  422. self.recorded_data.pop(capture_id)
  423. except KeyError as e:
  424. e.message = 'capture_id does not exist. ' \
  425. 'You should call start_capture_raw_data with same ID ' \
  426. 'before calling stop_capture_raw_data'
  427. raise e
  428. return ret
  429. # expect related methods
  430. @staticmethod
  431. def _expect_str(data, pattern):
  432. """
  433. protected method. check if string is matched in data cache.
  434. :param data: data to process
  435. :param pattern: string
  436. :return: pattern if match succeed otherwise None
  437. """
  438. index = data.find(pattern)
  439. if index != -1:
  440. ret = pattern
  441. index += len(pattern)
  442. else:
  443. ret = None
  444. return ret, index
  445. @staticmethod
  446. def _expect_re(data, pattern):
  447. """
  448. protected method. check if re pattern is matched in data cache
  449. :param data: data to process
  450. :param pattern: compiled RegEx pattern
  451. :return: match groups if match succeed otherwise None
  452. """
  453. ret = None
  454. if isinstance(pattern.pattern, bytes):
  455. pattern = re.compile(_decode_data(pattern.pattern))
  456. match = pattern.search(data)
  457. if match:
  458. ret = tuple(x for x in match.groups())
  459. index = match.end()
  460. else:
  461. index = -1
  462. return ret, index
  463. EXPECT_METHOD = [
  464. [type(re.compile('')), '_expect_re'],
  465. [type(b''), '_expect_str'], # Python 2 & 3 hook to work without 'from builtins import str' from future
  466. [type(u''), '_expect_str'],
  467. ]
  468. def _get_expect_method(self, pattern):
  469. """
  470. protected method. get expect method according to pattern type.
  471. :param pattern: expect pattern, string or compiled RegEx
  472. :return: ``_expect_str`` or ``_expect_re``
  473. """
  474. for expect_method in self.EXPECT_METHOD:
  475. if isinstance(pattern, expect_method[0]):
  476. method = expect_method[1]
  477. break
  478. else:
  479. raise UnsupportedExpectItem()
  480. return self.__getattribute__(method)
  481. @_expect_lock
  482. def expect(self, pattern, timeout=DEFAULT_EXPECT_TIMEOUT, full_stdout=False):
  483. """
  484. expect(pattern, timeout=DEFAULT_EXPECT_TIMEOUT)
  485. expect received data on DUT match the pattern. will raise exception when expect timeout.
  486. :raise ExpectTimeout: failed to find the pattern before timeout
  487. :raise UnsupportedExpectItem: pattern is not string or compiled RegEx
  488. :param pattern: string or compiled RegEx(string pattern)
  489. :param timeout: timeout for expect
  490. :param full_stdout: return full stdout until meet expect string/pattern or just matched string
  491. :return: string if pattern is string; matched groups if pattern is RegEx
  492. """
  493. method = self._get_expect_method(pattern)
  494. stdout = ''
  495. # non-blocking get data for first time
  496. data = self.data_cache.get_data(0)
  497. start_time = time.time()
  498. while True:
  499. ret, index = method(data, pattern)
  500. if ret is not None:
  501. stdout = data[:index]
  502. self.data_cache.flush(index)
  503. break
  504. time_remaining = start_time + timeout - time.time()
  505. if time_remaining < 0:
  506. break
  507. # wait for new data from cache
  508. data = self.data_cache.get_data(time_remaining)
  509. if ret is None:
  510. pattern = _pattern_to_string(pattern)
  511. self._save_expect_failure(pattern, data, start_time)
  512. raise ExpectTimeout(self.name + ': ' + pattern)
  513. return stdout if full_stdout else ret
  514. def _expect_multi(self, expect_all, expect_item_list, timeout):
  515. """
  516. protected method. internal logical for expect multi.
  517. :param expect_all: True or False, expect all items in the list or any in the list
  518. :param expect_item_list: expect item list
  519. :param timeout: timeout
  520. :return: None
  521. """
  522. def process_expected_item(item_raw):
  523. # convert item raw data to standard dict
  524. item = {
  525. 'pattern': item_raw[0] if isinstance(item_raw, tuple) else item_raw,
  526. 'method': self._get_expect_method(item_raw[0] if isinstance(item_raw, tuple)
  527. else item_raw),
  528. 'callback': item_raw[1] if isinstance(item_raw, tuple) else None,
  529. 'index': -1,
  530. 'ret': None,
  531. }
  532. return item
  533. expect_items = [process_expected_item(x) for x in expect_item_list]
  534. # non-blocking get data for first time
  535. data = self.data_cache.get_data(0)
  536. start_time = time.time()
  537. matched_expect_items = list()
  538. while True:
  539. for expect_item in expect_items:
  540. if expect_item not in matched_expect_items:
  541. # exclude those already matched
  542. expect_item['ret'], expect_item['index'] = \
  543. expect_item['method'](data, expect_item['pattern'])
  544. if expect_item['ret'] is not None:
  545. # match succeed for one item
  546. matched_expect_items.append(expect_item)
  547. # if expect all, then all items need to be matched,
  548. # else only one item need to matched
  549. if expect_all:
  550. match_succeed = len(matched_expect_items) == len(expect_items)
  551. else:
  552. match_succeed = True if matched_expect_items else False
  553. time_remaining = start_time + timeout - time.time()
  554. if time_remaining < 0 or match_succeed:
  555. break
  556. else:
  557. data = self.data_cache.get_data(time_remaining)
  558. if match_succeed:
  559. # sort matched items according to order of appearance in the input data,
  560. # so that the callbacks are invoked in correct order
  561. matched_expect_items = sorted(matched_expect_items, key=lambda it: it['index'])
  562. # invoke callbacks and flush matched data cache
  563. slice_index = -1
  564. for expect_item in matched_expect_items:
  565. # trigger callback
  566. if expect_item['callback']:
  567. expect_item['callback'](expect_item['ret'])
  568. slice_index = max(slice_index, expect_item['index'])
  569. # flush already matched data
  570. self.data_cache.flush(slice_index)
  571. else:
  572. pattern = str([_pattern_to_string(x['pattern']) for x in expect_items])
  573. self._save_expect_failure(pattern, data, start_time)
  574. raise ExpectTimeout(self.name + ': ' + pattern)
  575. @_expect_lock
  576. def expect_any(self, *expect_items, **timeout):
  577. """
  578. expect_any(*expect_items, timeout=DEFAULT_TIMEOUT)
  579. expect any of the patterns.
  580. will call callback (if provided) if pattern match succeed and then return.
  581. will pass match result to the callback.
  582. :raise ExpectTimeout: failed to match any one of the expect items before timeout
  583. :raise UnsupportedExpectItem: pattern in expect_item is not string or compiled RegEx
  584. :arg expect_items: one or more expect items.
  585. string, compiled RegEx pattern or (string or RegEx(string pattern), callback)
  586. :keyword timeout: timeout for expect
  587. :return: None
  588. """
  589. # to be compatible with python2
  590. # in python3 we can write f(self, *expect_items, timeout=DEFAULT_TIMEOUT)
  591. if 'timeout' not in timeout:
  592. timeout['timeout'] = self.DEFAULT_EXPECT_TIMEOUT
  593. return self._expect_multi(False, expect_items, **timeout)
  594. @_expect_lock
  595. def expect_all(self, *expect_items, **timeout):
  596. """
  597. expect_all(*expect_items, timeout=DEFAULT_TIMEOUT)
  598. expect all of the patterns.
  599. will call callback (if provided) if all pattern match succeed and then return.
  600. will pass match result to the callback.
  601. :raise ExpectTimeout: failed to match all of the expect items before timeout
  602. :raise UnsupportedExpectItem: pattern in expect_item is not string or compiled RegEx
  603. :arg expect_items: one or more expect items.
  604. string, compiled RegEx pattern or (string or RegEx(string pattern), callback)
  605. :keyword timeout: timeout for expect
  606. :return: None
  607. """
  608. # to be compatible with python2
  609. # in python3 we can write f(self, *expect_items, timeout=DEFAULT_TIMEOUT)
  610. if 'timeout' not in timeout:
  611. timeout['timeout'] = self.DEFAULT_EXPECT_TIMEOUT
  612. return self._expect_multi(True, expect_items, **timeout)
  613. @staticmethod
  614. def _format_ts(ts):
  615. return '{}:{}'.format(time.strftime('%m-%d %H:%M:%S', time.localtime(ts)), str(ts % 1)[2:5])
  616. def print_debug_info(self):
  617. """
  618. Print debug info of current DUT. Currently we will print debug info for expect failures.
  619. """
  620. Utility.console_log('DUT debug info for DUT: {}:'.format(self.name), color='orange')
  621. for failure in self.expect_failures:
  622. Utility.console_log(u'\t[pattern]: {}\r\n\t[data]: {}\r\n\t[time]: {} - {}\r\n'
  623. .format(failure['pattern'], failure['data'],
  624. self._format_ts(failure['start']), self._format_ts(failure['end'])),
  625. color='orange')
  626. class SerialDUT(BaseDUT):
  627. """ serial with logging received data feature """
  628. DEFAULT_UART_CONFIG = {
  629. 'baudrate': 115200,
  630. 'bytesize': serial.EIGHTBITS,
  631. 'parity': serial.PARITY_NONE,
  632. 'stopbits': serial.STOPBITS_ONE,
  633. 'timeout': 0.05,
  634. 'xonxoff': False,
  635. 'rtscts': False,
  636. }
  637. def __init__(self, name, port, log_file, app, **kwargs):
  638. self.port_inst = None
  639. self.serial_configs = self.DEFAULT_UART_CONFIG.copy()
  640. for uart_config_name in self.serial_configs.keys():
  641. if uart_config_name in kwargs:
  642. self.serial_configs[uart_config_name] = kwargs[uart_config_name]
  643. super(SerialDUT, self).__init__(name, port, log_file, app, **kwargs)
  644. def _format_data(self, data):
  645. """
  646. format data for logging. do decode and add timestamp.
  647. :param data: raw data from read
  648. :return: formatted data (str)
  649. """
  650. timestamp = '[{}]'.format(self._format_ts(time.time()))
  651. formatted_data = timestamp.encode() + b'\r\n' + data + b'\r\n'
  652. return formatted_data
  653. def _port_open(self):
  654. self.port_inst = serial.serial_for_url(self.port, **self.serial_configs)
  655. def _port_close(self):
  656. self.port_inst.close()
  657. def _port_read(self, size=1):
  658. data = self.port_inst.read(size)
  659. if data:
  660. self._save_dut_log(self._format_data(data))
  661. return data
  662. def _port_write(self, data):
  663. if isinstance(data, str):
  664. data = data.encode()
  665. self.port_inst.write(data)
  666. @classmethod
  667. def list_available_ports(cls):
  668. return [x.device for x in list_ports.comports()]