pytest-embedded 2.8.1__tar.gz → 2.9.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pytest-embedded
3
- Version: 2.8.1
3
+ Version: 2.9.0
4
4
  Summary: A pytest plugin that designed for embedded testing.
5
5
  Author-email: Fu Hanxi <fuhanxi@espressif.com>
6
6
  Requires-Python: >=3.10
@@ -6,4 +6,4 @@ from .dut_factory import DutFactory
6
6
 
7
7
  __all__ = ['App', 'Dut', 'DutFactory']
8
8
 
9
- __version__ = '2.8.1'
9
+ __version__ = '2.9.0'
@@ -13,6 +13,7 @@ from collections import defaultdict
13
13
  from pathlib import Path
14
14
 
15
15
  if t.TYPE_CHECKING:
16
+ from pytest_embedded_espemu import EspEmu
16
17
  from pytest_embedded_idf import LinuxSerial
17
18
  from pytest_embedded_idf.dut import IdfDut
18
19
  from pytest_embedded_jtag import Gdb, OpenOcd
@@ -157,6 +158,10 @@ def _fixture_classes_and_options_fn(
157
158
  qemu_cli_args,
158
159
  qemu_extra_args,
159
160
  qemu_efuse_path,
161
+ espemu_image_path,
162
+ espemu_prog_path,
163
+ espemu_cli_args,
164
+ espemu_extra_args,
160
165
  wokwi_diagram,
161
166
  wokwi_usb_serial_jtag,
162
167
  skip_regenerate_image,
@@ -195,6 +200,18 @@ def _fixture_classes_and_options_fn(
195
200
  'qemu_efuse_path': qemu_efuse_path,
196
201
  }
197
202
  )
203
+ elif 'espemu' in _services:
204
+ from pytest_embedded_espemu import EspEmuApp
205
+
206
+ classes[fixture] = EspEmuApp
207
+ kwargs[fixture].update(
208
+ {
209
+ 'msg_queue': msg_queue,
210
+ 'part_tool': part_tool,
211
+ 'espemu_image_path': espemu_image_path,
212
+ 'skip_regenerate_image': skip_regenerate_image,
213
+ }
214
+ )
198
215
  else:
199
216
  from pytest_embedded_idf import IdfApp
200
217
 
@@ -330,6 +347,24 @@ def _fixture_classes_and_options_fn(
330
347
  'meta': _meta,
331
348
  'dut_index': dut_index,
332
349
  }
350
+ elif fixture == 'espemu':
351
+ if 'espemu' in _services:
352
+ from pytest_embedded_espemu import (
353
+ DEFAULT_IMAGE_FN,
354
+ EspEmu,
355
+ )
356
+
357
+ classes[fixture] = EspEmu
358
+ kwargs[fixture] = {
359
+ 'msg_queue': msg_queue,
360
+ 'espemu_image_path': espemu_image_path
361
+ or os.path.join(app_path or '', build_dir or 'build', DEFAULT_IMAGE_FN),
362
+ 'espemu_prog_path': espemu_prog_path,
363
+ 'espemu_cli_args': espemu_cli_args,
364
+ 'espemu_extra_args': espemu_extra_args,
365
+ 'app': None,
366
+ 'meta': _meta,
367
+ }
333
368
  elif fixture == 'wokwi':
334
369
  if 'wokwi' in _services:
335
370
  from pytest_embedded_wokwi import Wokwi
@@ -381,6 +416,15 @@ def _fixture_classes_and_options_fn(
381
416
  kwargs['wokwi'].update({'firmware_resolver': ArduinoFirmwareResolver()})
382
417
  else:
383
418
  raise SystemExit('wokwi service should be used together with idf or arduino service')
419
+ elif 'espemu' in _services:
420
+ from pytest_embedded_espemu import EspEmuDut
421
+
422
+ classes[fixture] = EspEmuDut
423
+ kwargs[fixture].update(
424
+ {
425
+ 'espemu': None,
426
+ }
427
+ )
384
428
  elif 'qemu' in _services:
385
429
  if 'nuttx' in _services:
386
430
  from pytest_embedded_nuttx import NuttxQemuDut
@@ -534,6 +578,19 @@ def qemu_gn(_fixture_classes_and_options: ClassCliOptions, app) -> t.Optional['Q
534
578
  return cls(**_drop_none_kwargs(kwargs))
535
579
 
536
580
 
581
+ def espemu_gn(_fixture_classes_and_options: ClassCliOptions, app) -> t.Optional['EspEmu']:
582
+ if 'espemu' not in _fixture_classes_and_options.classes:
583
+ return None
584
+
585
+ cls = _fixture_classes_and_options.classes['espemu']
586
+ kwargs = _fixture_classes_and_options.kwargs['espemu']
587
+
588
+ if 'app' in kwargs and kwargs['app'] is None:
589
+ kwargs['app'] = app
590
+
591
+ return cls(**_drop_none_kwargs(kwargs))
592
+
593
+
537
594
  def wokwi_gn(_fixture_classes_and_options: ClassCliOptions, app) -> t.Optional['Wokwi']:
538
595
  """A wokwi subprocess that could read/redirect/write"""
539
596
  if 'wokwi' not in _fixture_classes_and_options.classes:
@@ -555,6 +612,7 @@ def dut_gn(
555
612
  serial: t.Union['Serial', 'LinuxSerial'] | None,
556
613
  qemu: t.Optional['Qemu'],
557
614
  wokwi: t.Optional['Wokwi'],
615
+ espemu: t.Optional['EspEmu'] = None,
558
616
  ) -> Dut | list[Dut]:
559
617
  global DUT_GLOBAL_INDEX
560
618
  DUT_GLOBAL_INDEX += 1
@@ -584,6 +642,8 @@ def dut_gn(
584
642
  kwargs[k] = gdb
585
643
  elif k == 'qemu':
586
644
  kwargs[k] = qemu
645
+ elif k == 'espemu':
646
+ kwargs[k] = espemu
587
647
  elif k == 'wokwi':
588
648
  kwargs[k] = wokwi
589
649
  return cls(**_drop_none_kwargs(kwargs), mixins=mixins)
@@ -700,6 +760,10 @@ class DutFactory:
700
760
  qemu_cli_args: str | None = None,
701
761
  qemu_extra_args: str | None = None,
702
762
  qemu_efuse_path: str | None = None,
763
+ espemu_image_path: str | None = None,
764
+ espemu_prog_path: str | None = None,
765
+ espemu_cli_args: str | None = None,
766
+ espemu_extra_args: str | None = None,
703
767
  wokwi_diagram: str | None = None,
704
768
  wokwi_usb_serial_jtag: bool | None = None,
705
769
  skip_regenerate_image: bool | None = None,
@@ -748,6 +812,10 @@ class DutFactory:
748
812
  qemu_cli_args: QEMU CLI arguments.
749
813
  qemu_extra_args: Additional QEMU arguments.
750
814
  qemu_efuse_path: Efuse binary path.
815
+ espemu_image_path: esp-emu image path.
816
+ espemu_prog_path: esp-emu program path.
817
+ espemu_cli_args: esp-emu CLI arguments.
818
+ espemu_extra_args: Additional esp-emu arguments.
751
819
  wokwi_diagram: Wokwi diagram path.
752
820
  wokwi_usb_serial_jtag: Use USB Serial JTAG instead of UART for Wokwi serial communication.
753
821
  skip_regenerate_image: Skip image regeneration flag.
@@ -820,6 +888,10 @@ class DutFactory:
820
888
  'qemu_cli_args': qemu_cli_args,
821
889
  'qemu_extra_args': qemu_extra_args,
822
890
  'qemu_efuse_path': qemu_efuse_path,
891
+ 'espemu_image_path': espemu_image_path,
892
+ 'espemu_prog_path': espemu_prog_path,
893
+ 'espemu_cli_args': espemu_cli_args,
894
+ 'espemu_extra_args': espemu_extra_args,
823
895
  'wokwi_diagram': wokwi_diagram,
824
896
  'wokwi_usb_serial_jtag': wokwi_usb_serial_jtag,
825
897
  'skip_regenerate_image': skip_regenerate_image,
@@ -850,11 +922,13 @@ class DutFactory:
850
922
 
851
923
  qemu = qemu_gn(_fixture_classes_and_options, app)
852
924
  layout.append(qemu)
925
+ espemu = espemu_gn(_fixture_classes_and_options, app)
926
+ layout.append(espemu)
853
927
 
854
928
  wokwi = wokwi_gn(_fixture_classes_and_options, app)
855
929
  layout.append(wokwi)
856
930
 
857
- dut = dut_gn(_fixture_classes_and_options, openocd, gdb, app, serial, qemu, wokwi)
931
+ dut = dut_gn(_fixture_classes_and_options, openocd, gdb, app, serial, qemu, wokwi, espemu)
858
932
  layout.append(dut)
859
933
 
860
934
  cls.obj_stack.append(layout)
@@ -154,7 +154,13 @@ class _PopenRedirectProcess(_ctx.Process):
154
154
 
155
155
  @staticmethod
156
156
  def _forward_io(msg_queue, logfile) -> None:
157
- with open(logfile) as fr:
157
+ # Binary, because the file is still being written to: a text-mode read finalizes the
158
+ # decoder at every temporary EOF, and a UTF-8 sequence straddling that boundary raises
159
+ # UnicodeDecodeError. `except Exception` below would swallow it and this process would
160
+ # exit 0, cutting the output off for the rest of the session. Decoding here is not
161
+ # needed either - `MessageQueue.put` re-encodes with `to_bytes`, the pexpect buffer is
162
+ # bytes, and the serial transport already forwards `read_all()` undecoded.
163
+ with open(logfile, 'rb') as fr:
158
164
  while True:
159
165
  try:
160
166
  msg_queue.put(fr.read()) # msg_queue may be closed
@@ -36,6 +36,7 @@ from .dut_factory import (
36
36
  _pexpect_fr_gn,
37
37
  app_fn,
38
38
  dut_gn,
39
+ espemu_gn,
39
40
  gdb_gn,
40
41
  openocd_gn,
41
42
  pexpect_proc_fn,
@@ -60,6 +61,7 @@ from .utils import (
60
61
  )
61
62
 
62
63
  if t.TYPE_CHECKING:
64
+ from pytest_embedded_espemu import EspEmu
63
65
  from pytest_embedded_idf import CaseTester, IdfDut, LinuxSerial
64
66
  from pytest_embedded_jtag import Gdb, OpenOcd
65
67
  from pytest_embedded_qemu import Qemu
@@ -70,7 +72,7 @@ if t.TYPE_CHECKING:
70
72
  _T = t.TypeVar('_T')
71
73
 
72
74
 
73
- def pytest_addoption(parser):
75
+ def pytest_addoption(parser: pytest.Parser):
74
76
  base_group = parser.getgroup('embedded')
75
77
  base_group.addoption(
76
78
  '--count',
@@ -140,6 +142,7 @@ def pytest_addoption(parser):
140
142
  '- idf: auto-detect more app info with idf specific rules, auto flash-in\n'
141
143
  '- jtag: openocd and gdb\n'
142
144
  '- qemu: use qemu simulator instead of the real target\n'
145
+ '- espemu: use esp-emu simulator instead of the real target\n'
143
146
  '- arduino: auto-detect more app info with arduino specific rules, auto flash-in\n'
144
147
  '- wokwi: use wokwi simulator instead of the real target\n'
145
148
  '- nuttx: service for nuttx project, optionally with espressif devices\n'
@@ -304,6 +307,24 @@ def pytest_addoption(parser):
304
307
  help='Flash Encryption (pre-encrypted workflow) key path. (Default: None)',
305
308
  )
306
309
 
310
+ espemu_group = parser.getgroup('embedded-espemu')
311
+ espemu_group.addoption(
312
+ '--espemu-image-path',
313
+ help='esp-emu image path. (Default: "<app_path>/<build_dir>/espemu_image.bin")',
314
+ )
315
+ espemu_group.addoption(
316
+ '--espemu-prog-path',
317
+ help='esp-emu program path. (Default: "esp-emu")',
318
+ )
319
+ espemu_group.addoption(
320
+ '--espemu-cli-args',
321
+ help='esp-emu cli default arguments. (Default: None)',
322
+ )
323
+ espemu_group.addoption(
324
+ '--espemu-extra-args',
325
+ help='esp-emu cli extra arguments, will append to the argument list. (Default: None)',
326
+ )
327
+
307
328
  wokwi_group = parser.getgroup('embedded-wokwi')
308
329
  wokwi_group.addoption(
309
330
  '--wokwi-diagram',
@@ -1070,6 +1091,37 @@ def qemu_efuse_path(request: FixtureRequest) -> str | None:
1070
1091
  return _request_param_or_config_option_or_default(request, 'qemu_efuse_path', None)
1071
1092
 
1072
1093
 
1094
+ ##########
1095
+ # espemu #
1096
+ ##########
1097
+ @pytest.fixture
1098
+ @multi_dut_argument
1099
+ def espemu_image_path(request: FixtureRequest) -> str | None:
1100
+ """Enable parametrization for the same cli option"""
1101
+ return _request_param_or_config_option_or_default(request, 'espemu_image_path', None)
1102
+
1103
+
1104
+ @pytest.fixture
1105
+ @multi_dut_argument
1106
+ def espemu_prog_path(request: FixtureRequest) -> str | None:
1107
+ """Enable parametrization for the same cli option"""
1108
+ return _request_param_or_config_option_or_default(request, 'espemu_prog_path', None)
1109
+
1110
+
1111
+ @pytest.fixture
1112
+ @multi_dut_argument
1113
+ def espemu_cli_args(request: FixtureRequest) -> str | None:
1114
+ """Enable parametrization for the same cli option"""
1115
+ return _request_param_or_config_option_or_default(request, 'espemu_cli_args', None)
1116
+
1117
+
1118
+ @pytest.fixture
1119
+ @multi_dut_argument
1120
+ def espemu_extra_args(request: FixtureRequest) -> str | None:
1121
+ """Enable parametrization for the same cli option"""
1122
+ return _request_param_or_config_option_or_default(request, 'espemu_extra_args', None)
1123
+
1124
+
1073
1125
  @pytest.fixture
1074
1126
  @multi_dut_argument
1075
1127
  def skip_regenerate_image(request: FixtureRequest) -> str | None:
@@ -1166,6 +1218,10 @@ def parametrize_fixtures(
1166
1218
  qemu_cli_args,
1167
1219
  qemu_extra_args,
1168
1220
  qemu_efuse_path,
1221
+ espemu_image_path,
1222
+ espemu_prog_path,
1223
+ espemu_cli_args,
1224
+ espemu_extra_args,
1169
1225
  wokwi_diagram,
1170
1226
  wokwi_usb_serial_jtag,
1171
1227
  skip_regenerate_image,
@@ -1257,6 +1313,13 @@ def qemu(_fixture_classes_and_options: ClassCliOptions, app) -> t.Optional['Qemu
1257
1313
  return qemu_gn(**locals())
1258
1314
 
1259
1315
 
1316
+ @pytest.fixture
1317
+ @multi_dut_generator_fixture
1318
+ def espemu(_fixture_classes_and_options: ClassCliOptions, app) -> t.Optional['EspEmu']:
1319
+ """An esp-emu subprocess that could read/redirect/write"""
1320
+ return espemu_gn(**locals())
1321
+
1322
+
1260
1323
  @pytest.fixture
1261
1324
  @multi_dut_generator_fixture
1262
1325
  def wokwi(_fixture_classes_and_options: ClassCliOptions, app) -> t.Optional['Wokwi']:
@@ -1274,6 +1337,7 @@ def dut(
1274
1337
  serial: t.Union['Serial', 'LinuxSerial'] | None,
1275
1338
  qemu: t.Optional['Qemu'],
1276
1339
  wokwi: t.Optional['Wokwi'],
1340
+ espemu: t.Optional['EspEmu'],
1277
1341
  ) -> Dut | list[Dut]:
1278
1342
  """
1279
1343
  A device under test (DUT) object that could gather output from various sources and redirect them to the pexpect
@@ -1415,7 +1479,7 @@ class PytestEmbedded:
1415
1479
 
1416
1480
  from esp_bool_parser import parse_bool_expr
1417
1481
 
1418
- target = config.getoption('--target', None)
1482
+ target = config.getoption('target', None)
1419
1483
  if hasattr(item, 'callspec'):
1420
1484
  target = item.callspec.params.get('target', None)
1421
1485
  if target == 'auto' or not isinstance(target, str):
@@ -1491,7 +1555,7 @@ class PytestEmbedded:
1491
1555
  self._raise_dut_failed_cases_if_exists(all_duts) # type: ignore
1492
1556
 
1493
1557
  @pytest.hookimpl(trylast=True) # combine all possible junit reports should be the last step
1494
- def pytest_sessionfinish(self, session: Session, exitstatus: int) -> None:
1558
+ def pytest_sessionfinish(self, session: Session) -> None:
1495
1559
  modifier: JunitMerger = session.config.stash[_junit_merger_key]
1496
1560
  _stash_session_tempdir = session.config.stash.get(_session_tempdir_key, None)
1497
1561
  _stash_junit_report_path = session.config.stash.get(_junit_report_path_key, None)
@@ -1509,4 +1573,8 @@ class PytestEmbedded:
1509
1573
  if self.prettify_junit_report:
1510
1574
  _prettify_xml(_stash_junit_report_path)
1511
1575
 
1512
- exitstatus = int(modifier.failed) # True -> 1 False -> 0 # noqa
1576
+ # escalate the session exit status to failure if the merged junit report contains failures,
1577
+ # without downgrading an already-failing run
1578
+ current_exitstatus = getattr(session, 'exitstatus', pytest.ExitCode.OK)
1579
+ if modifier.failed and current_exitstatus == pytest.ExitCode.OK:
1580
+ session.exitstatus = pytest.ExitCode.TESTS_FAILED
@@ -23,19 +23,21 @@ SERVICE_LIB_NAMES = {
23
23
  'idf': f'{BASE_LIB_NAME}-idf',
24
24
  'jtag': f'{BASE_LIB_NAME}-jtag',
25
25
  'qemu': f'{BASE_LIB_NAME}-qemu',
26
+ 'espemu': f'{BASE_LIB_NAME}-espemu',
26
27
  'arduino': f'{BASE_LIB_NAME}-arduino',
27
28
  'wokwi': f'{BASE_LIB_NAME}-wokwi',
28
29
  'nuttx': f'{BASE_LIB_NAME}-nuttx',
29
30
  }
30
31
 
31
32
  FIXTURES_SERVICES = {
32
- 'app': ['base', 'idf', 'qemu', 'arduino', 'nuttx'],
33
+ 'app': ['base', 'idf', 'qemu', 'espemu', 'arduino', 'nuttx'],
33
34
  'serial': ['serial', 'jtag', 'esp', 'idf', 'arduino', 'nuttx'],
34
35
  'openocd': ['jtag'],
35
36
  'gdb': ['jtag'],
36
37
  'qemu': ['qemu'],
38
+ 'espemu': ['espemu'],
37
39
  'wokwi': ['wokwi'],
38
- 'dut': ['base', 'serial', 'jtag', 'qemu', 'idf', 'wokwi', 'nuttx'],
40
+ 'dut': ['base', 'serial', 'jtag', 'qemu', 'espemu', 'idf', 'wokwi', 'nuttx'],
39
41
  }
40
42
 
41
43
 
@@ -35,6 +35,7 @@ def test_services(testdir):
35
35
  ('idf,serial', {'IdfApp', 'Serial', 'SerialDut'}),
36
36
  ('idf,esp', {'IdfApp', 'IdfSerial', 'IdfDut'}),
37
37
  ('idf,qemu', {'QemuApp', 'Qemu', 'QemuDut'}),
38
+ ('idf,espemu', {'EspEmuApp', 'EspEmu', 'EspEmuDut'}),
38
39
  ('arduino,esp', {'ArduinoApp', 'ArduinoSerial', 'SerialDut'}),
39
40
  ],
40
41
  indirect=True
@@ -45,7 +46,7 @@ def test_services(testdir):
45
46
 
46
47
  result = testdir.runpytest()
47
48
 
48
- result.assert_outcomes(passed=7)
49
+ result.assert_outcomes(passed=8)
49
50
 
50
51
 
51
52
  def test_fixtures(testdir):
@@ -1010,3 +1011,84 @@ def test_multi_dut_no_data_loss(testdir):
1010
1011
 
1011
1012
  result = testdir.runpytest()
1012
1013
  result.assert_outcomes(passed=1)
1014
+
1015
+
1016
+ def _drain(q, deadline_s=10):
1017
+ """Collect everything the queue yields until it stays quiet for a moment."""
1018
+ import queue as _q
1019
+ import time
1020
+
1021
+ chunks = []
1022
+ deadline = time.monotonic() + deadline_s
1023
+ while time.monotonic() < deadline:
1024
+ try:
1025
+ chunks.append(q.get(timeout=0.2))
1026
+ except _q.Empty:
1027
+ if chunks:
1028
+ break
1029
+ return b''.join(chunks)
1030
+
1031
+
1032
+ def test_forward_io_survives_split_multibyte_char(tmp_path):
1033
+ """A multi-byte sequence split across two appends must not kill the forwarder.
1034
+
1035
+ The redirect log is written to while it is being read, so the reader keeps hitting a
1036
+ temporary EOF. Decoding there turns any UTF-8 sequence straddling that boundary into
1037
+ a UnicodeDecodeError, which the forwarder's `except Exception` swallows: the process
1038
+ exits 0 and DUT output stops for the rest of the session.
1039
+ """
1040
+ import time
1041
+
1042
+ from pytest_embedded.log import MessageQueue, _PopenRedirectProcess
1043
+
1044
+ logfile = str(tmp_path / 'redirect.log')
1045
+ open(logfile, 'wb').close()
1046
+
1047
+ q = MessageQueue()
1048
+ p = _PopenRedirectProcess(q, logfile)
1049
+ p.start()
1050
+ try:
1051
+ with open(logfile, 'ab') as fw:
1052
+ fw.write(b'head\n')
1053
+ fw.flush()
1054
+ assert b'head\n' in _drain(q), 'nothing forwarded before the split'
1055
+
1056
+ # U+2014 EM DASH, torn in half: the reader reaches EOF between the two bytes.
1057
+ with open(logfile, 'ab') as fw:
1058
+ fw.write(b'dash \xe2')
1059
+ fw.flush()
1060
+ time.sleep(0.5)
1061
+ assert p.is_alive(), f'forwarder died on a split sequence (exitcode={p.exitcode})'
1062
+
1063
+ with open(logfile, 'ab') as fw:
1064
+ fw.write(b'\x80\x94 tail\n')
1065
+ fw.flush()
1066
+ assert b'dash \xe2\x80\x94 tail\n' in _drain(q), 'the split character was not reassembled'
1067
+ finally:
1068
+ p.terminate()
1069
+ p.join(timeout=5)
1070
+
1071
+
1072
+ def test_forward_io_preserves_carriage_returns(tmp_path):
1073
+ """The forwarder passes the log through byte for byte, CR included.
1074
+
1075
+ Reading in text mode used to apply universal-newline translation, so a device sending
1076
+ CRLF was forwarded as LF. The serial transport never did that, and the console writer
1077
+ and the Unity parser both handle CRLF themselves.
1078
+ """
1079
+ from pytest_embedded.log import MessageQueue, _PopenRedirectProcess
1080
+
1081
+ logfile = str(tmp_path / 'redirect.log')
1082
+ open(logfile, 'wb').close()
1083
+
1084
+ q = MessageQueue()
1085
+ p = _PopenRedirectProcess(q, logfile)
1086
+ p.start()
1087
+ try:
1088
+ with open(logfile, 'ab') as fw:
1089
+ fw.write(b'first\r\nsecond\r\n')
1090
+ fw.flush()
1091
+ assert _drain(q) == b'first\r\nsecond\r\n'
1092
+ finally:
1093
+ p.terminate()
1094
+ p.join(timeout=5)
File without changes