Skip to content

Commit 7460a5f

Browse files
committed
test update
1 parent bbeb625 commit 7460a5f

5 files changed

Lines changed: 135 additions & 10 deletions

File tree

‎hackrfpy/tests/test_cli.py‎

Lines changed: 21 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -209,12 +209,27 @@ def test_doctor_ok_with_core_tools(cli_env):
209209
_run_cli(["doctor"])
210210

211211

212-
def test_doctor_exits_when_core_tool_missing(cli_env):
213-
# remove a CORE tool so preflight reports a problem -> exit 1
214-
for fn in ("hackrf_sweep", "hackrf_sweep.bat", "hackrf_sweep.py"):
215-
p = os.path.join(cli_env.tools, fn)
216-
if os.path.exists(p):
217-
os.remove(p)
212+
def test_doctor_exits_when_core_tool_missing(cli_env, monkeypatch):
213+
# Force resolve() to fail for the sweep tool so preflight reports a missing
214+
# CORE binary -> exit 1.
215+
#
216+
# NOTE: deleting the stub from tools_dir is NOT enough. resolve() falls back
217+
# to shutil.which(), so on a machine with real hackrf-tools on PATH (i.e.
218+
# any actual dev box) it would find the real hackrf_sweep and report no
219+
# problems. Patching resolve makes this deterministic everywhere.
220+
from hackrfpy.core import HackRF as _HackRF
221+
from hackrfpy import constants as C
222+
from hackrfpy.exceptions import HackRFDeviceError
223+
224+
real_resolve = _HackRF.resolve
225+
226+
def _resolve(self, key):
227+
if key == "sweep":
228+
raise HackRFDeviceError(f"missing binary: {C.TOOLS['sweep']}")
229+
return real_resolve(self, key)
230+
231+
monkeypatch.setattr(_HackRF, "resolve", _resolve)
232+
218233
with pytest.raises(SystemExit) as exc:
219234
_run_cli(["doctor"])
220235
assert exc.value.code == 1

‎hackrfpy/tests/test_features.py‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -115,12 +115,14 @@ def empty_stream(*a, **k):
115115

116116

117117
# ---- tx: max_duration converts an open-ended repeat into a timed run -------
118-
def test_tx_max_duration_forces_timed(monkeypatch):
118+
def test_tx_max_duration_forces_timed(monkeypatch, tmp_path):
119119
h = HackRF()
120120
h.set_mode(C.MODE_TX)
121+
src = tmp_path / "sig.iq"
122+
src.write_bytes(b"\x00\x01" * 8) # real file for the source guard
121123
seen = {}
122124
monkeypatch.setattr(h, "_run",
123125
lambda argv, **k: seen.update(k) or ("", "", 0))
124-
h.transmit(433.92e6, 8e6, "sig.iq", repeat=True, max_duration=5.0)
126+
h.transmit(433.92e6, 8e6, str(src), repeat=True, max_duration=5.0)
125127
assert seen.get("mode") == "timed"
126128
assert seen.get("duration") == 5.0

‎hackrfpy/tests/test_lifecycle_xplat.py‎

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,10 @@ def test_timed_stops_chatty_child_on_schedule(stub_device):
7676
# ---- handle mode -----------------------------------------------------------
7777
def test_handle_drains_pipes_and_stops_cleanly(stub_device):
7878
# flood stderr past the pipe buffer immediately; without drain threads
79-
# this blocks the child (the classic deadlock)
79+
# this blocks the child (the classic deadlock). Reaching "started" on
80+
# stdout proves the flood was drained past. The retained tail is now
81+
# bounded by _DRAIN_CAP so an open-ended handle can't grow without bound.
82+
from hackrfpy.core import _DRAIN_CAP
8083
h = stub_device(transfer=dict(
8184
stderr_flood=262144, stdout_lines=["started"], idle=True))
8285
proc = h._run(["transfer", "-r", "x.iq"], mode="handle")
@@ -87,10 +90,23 @@ def test_handle_drains_pipes_and_stops_cleanly(stub_device):
8790
time.sleep(0.05)
8891
assert proc.is_alive()
8992
out, err, rc = proc.stop()
90-
assert len(err) >= 262144
93+
assert 0 < len(err) <= _DRAIN_CAP # drained, but capped (was: >= flood)
9194
assert b"started" in out
9295

9396

97+
def test_handle_drain_buffer_is_capped(stub_device):
98+
# Regression: the handle-mode drain used to retain ALL output, growing
99+
# memory without bound on long-lived RX/TX handles. Flood far past the cap,
100+
# then exit; wait() joins the drain threads so the retained size is
101+
# deterministic and must be bounded by _DRAIN_CAP.
102+
from hackrfpy.core import _DRAIN_CAP
103+
h = stub_device(transfer=dict(stderr_flood=_DRAIN_CAP * 8))
104+
proc = h._run(["transfer", "-r", "x.iq"], mode="handle")
105+
out, err, rc = proc.wait()
106+
assert rc == 0
107+
assert 0 < len(err) <= _DRAIN_CAP
108+
109+
94110
def test_handle_context_manager_reaps(stub_device):
95111
h = stub_device(transfer=dict(stdout_lines=["ready"], idle=True))
96112
proc = h._run(["transfer", "-r", "x.iq"], mode="handle")

‎hackrfpy/tests/test_safety.py‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -149,3 +149,39 @@ def test_transmit_cw_builds_c_flag(monkeypatch):
149149
assert seen["argv"][0] == "transfer"
150150
assert seen["argv"][1] == "-c"
151151
assert seen["argv"][2] == 127 # clamped 0-127
152+
153+
154+
# ---- transmit source-file guard: fail fast before spawning ------------------
155+
def test_transmit_missing_source_rejected(monkeypatch):
156+
from hackrfpy.exceptions import HackRFEnvironmentError
157+
h = HackRF()
158+
h.set_mode(C.MODE_TX)
159+
monkeypatch.setattr(h, "_run",
160+
lambda *a, **k: pytest.fail("must not spawn on bad source"))
161+
with pytest.raises(HackRFEnvironmentError, match="source not found"):
162+
h.transmit(433.92e6, 8e6, "/no/such/file.iq")
163+
164+
165+
def test_transmit_mode_gate_precedes_source_check(monkeypatch):
166+
# With BOTH a wrong mode and a missing file, the TX-mode gate must win --
167+
# the safety invariant is checked before input validation.
168+
from hackrfpy.exceptions import HackRFModeError
169+
h = HackRF() # defaults to RX
170+
assert h.mode == C.MODE_RX
171+
monkeypatch.setattr(h, "_run",
172+
lambda *a, **k: pytest.fail("must not spawn"))
173+
with pytest.raises(HackRFModeError):
174+
h.transmit(433.92e6, 8e6, "/no/such/file.iq")
175+
176+
177+
def test_transmit_print_cmd_skips_source_check(monkeypatch):
178+
# A dry-run preview must not require the file to exist (it may be a file
179+
# you haven't generated yet).
180+
h = HackRF()
181+
h.set_mode(C.MODE_TX)
182+
seen = {}
183+
monkeypatch.setattr(h, "_run",
184+
lambda argv, **k: seen.update(argv=argv))
185+
h.transmit(433.92e6, 8e6, "/no/such/file.iq", print_cmd=True)
186+
assert seen["argv"][0] == "transfer"
187+
assert "-t" in seen["argv"]

‎hackrfpy/tests/test_sigmf.py‎

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
#! /usr/bin/python3
2+
3+
##--------------------------------------------------------------------\
4+
# hackrfpy 'tests/test_sigmf.py'
5+
# SigMF sidecar writer/reader. Pins the core namespace shape and the
6+
# core:extensions declaration for hackrf:* keys (strict SigMF validators
7+
# reject a file that uses a non-core namespace without declaring it). No
8+
# device needed.
9+
#
10+
#
11+
# Author(s): Lauren Linkous
12+
# Last Update: July 11, 2026
13+
##--------------------------------------------------------------------\
14+
15+
import json
16+
17+
from hackrfpy import write_sigmf_meta, read_sigmf_meta
18+
19+
20+
def test_core_fields_written(tmp_path):
21+
meta_path = write_sigmf_meta(str(tmp_path / "cap.iq"), 433.92e6, 8e6)
22+
meta = json.load(open(meta_path))
23+
g = meta["global"]
24+
assert g["core:datatype"] == "ci8"
25+
assert g["core:sample_rate"] == 8e6
26+
assert meta["captures"][0]["core:frequency"] == 433.92e6
27+
28+
29+
def test_extensions_declared_when_gains_present(tmp_path):
30+
# hackrf:* keys require a core:extensions declaration to be spec-valid.
31+
meta_path = write_sigmf_meta(str(tmp_path / "cap.iq"), 100e6, 8e6,
32+
lna=24, vga=20, amp=True)
33+
g = json.load(open(meta_path))["global"]
34+
assert g["hackrf:lna_gain_db"] == 24
35+
exts = g.get("core:extensions")
36+
assert isinstance(exts, list) and len(exts) == 1
37+
assert exts[0]["name"] == "hackrf"
38+
assert exts[0]["optional"] is True
39+
assert "version" in exts[0]
40+
41+
42+
def test_extensions_absent_when_no_gains(tmp_path):
43+
# No hackrf:* keys -> no extension declaration (nothing to declare).
44+
meta_path = write_sigmf_meta(str(tmp_path / "cap.iq"), 100e6, 8e6)
45+
g = json.load(open(meta_path))["global"]
46+
assert "core:extensions" not in g
47+
assert not any(k.startswith("hackrf:") for k in g)
48+
49+
50+
def test_roundtrip_via_data_path(tmp_path):
51+
# read_sigmf_meta accepts the data path and maps it to the sidecar.
52+
data_path = str(tmp_path / "cap.iq")
53+
write_sigmf_meta(data_path, 915e6, 10e6, lna=16)
54+
meta = read_sigmf_meta(data_path)
55+
assert meta["global"]["hackrf:lna_gain_db"] == 16
56+
assert meta["captures"][0]["core:frequency"] == 915e6

0 commit comments

Comments
 (0)