forked from fossasia/pslab-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconftest.py
More file actions
80 lines (59 loc) · 2.39 KB
/
conftest.py
File metadata and controls
80 lines (59 loc) · 2.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
"""Tests can be run as either unit tests or integration tests.
By default, they are run as unit tests. When running as unit tests, recorded
serial traffic from passing integration tests are played back during the test.
By calling pytest with the --integration flag, the tests will instead be run as
integration tests. In this mode, a real PSLab device must be connected.
Additionally, certain pins must be connected in a specific manner. Refer to the
individual test modules in the tests package.
By calling pytest with the --record flag, the serial traffic generated by the
integration tests will be recorded to JSON files, which are played back during
unit testing. The --record flag implies --integration.
"""
import json
import os
import pytest
from pslab import serial_handler
def pytest_addoption(parser):
parser.addoption("--integration", action="store_true", default=False)
parser.addoption("--record", action="store_true", default=False)
@pytest.fixture(scope="module")
def logdir(request):
# First five chars are "test_", last three are ".py".
return os.path.join("tests", "recordings", request.node.name[5:][:-3])
@pytest.fixture
def handler(monkeypatch, request, logdir):
"""Return a SerialHandler instance.
When running unit tests, the SerialHandler is a MockHandler.
"""
record = request.config.getoption("--record")
integration = request.config.getoption("--integration") or record
logfile = os.path.join(logdir, request.node.name + ".json")
if integration:
H = serial_handler.SerialHandler()
else:
tx, rx = json.load(open(logfile, "r"))
traffic = ((bytes(t), bytes(r)) for t, r in zip(tx, rx))
monkeypatch.setattr(serial_handler, "RECORDED_TRAFFIC", traffic)
H = serial_handler.MockHandler()
yield H
if record:
log = H._log.split(b"STOP")[:-1]
record_traffic(log, logfile)
def record_traffic(log: list, logfile: str):
"""Record serial traffic to a JSON file.
The file name is the test name + .json.
"""
tx = []
rx = []
for b in log:
direction = b[:2]
data = b[2:]
if direction == b"TX":
tx.append(list(data))
rx.append([])
elif direction == b"RX":
rx[-1] += list(data)
else:
raise ValueError(f"Unknown direction: {direction}")
print([tx, rx])
json.dump([tx, rx], open(logfile, "w"))