Skip to content

Commit f875ff6

Browse files
committed
header template update tests
1 parent 1ed1def commit f875ff6

21 files changed

Lines changed: 429 additions & 1 deletion

‎hackrfpy/tests/collect_real_data.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,10 @@
2323
# python tests/collect_real_data.py --tools-dir "C:\hackrf-tools-windows"
2424
# python tests/collect_real_data.py --anonymize # scrub serials
2525
# python tests/collect_real_data.py --sweep-band 88:108 --rx-freq 100e6
26+
#
27+
#
28+
# Author(s): Lauren Linkous
29+
# Last Update: July 11, 2026
2630
##--------------------------------------------------------------------\
2731

2832
import argparse

‎hackrfpy/tests/conftest.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,10 @@
55
# Shared pytest fixtures + the hardware-marker self-skip + the
66
# CROSS-PLATFORM stub-binary factory (so lifecycle/handle/stream tests
77
# run on Windows, not just where bash exists).
8+
#
9+
#
10+
# Author(s): Lauren Linkous
11+
# Last Update: July 11, 2026
812
##--------------------------------------------------------------------\
913

1014
import os

‎hackrfpy/tests/test_bugfixes.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,10 @@
44
# hackrfpy 'tests/test_bugfixes.py'
55
# Regression tests for the 2026-06-10 bug-fix pass. Each test pins one
66
# fixed behavior. No device needed (dry-run tests need hackrf-tools).
7+
#
8+
#
9+
# Author(s): Lauren Linkous
10+
# Last Update: July 11, 2026
711
##--------------------------------------------------------------------\
812

913
import shutil

‎hackrfpy/tests/test_calibration.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,10 @@
55
# Level-1 relative calibration helpers: power in dBFS, gain chain, and
66
# gain-normalized relative power (with optional offset + freq correction).
77
# Pure math, no hardware.
8+
#
9+
#
10+
# Author(s): Lauren Linkous
11+
# Last Update: July 11, 2026
812
##--------------------------------------------------------------------\
913

1014
import numpy as np

‎hackrfpy/tests/test_cli.py‎

Lines changed: 349 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,349 @@
1+
#! /usr/bin/python3
2+
3+
##--------------------------------------------------------------------\
4+
# hackrfpy 'tests/test_cli.py'
5+
#
6+
# End-to-end CLI coverage that DOES NOT need real hackrf-tools or a board.
7+
# The trick (same one conftest uses for lifecycle tests): point the CLI's
8+
# HackRF at a tools_dir of cross-platform STUB binaries, so resolve()
9+
# succeeds and the shell exercises its full dispatch/parse/exit surface on
10+
# Windows and POSIX alike. rx/tx/sweep use --print-cmd (nothing executes);
11+
# info/detect/doctor run a functional hackrf_info stub; sweep's CSV loop
12+
# runs a functional hackrf_sweep stub. State + presets are made hermetic by
13+
# redirecting XDG_CONFIG_HOME to a tmp dir.
14+
#
15+
#
16+
# Author(s): Lauren Linkous
17+
# Last Update: July 11, 2026
18+
##--------------------------------------------------------------------\
19+
20+
import os
21+
import stat
22+
import sys
23+
from types import SimpleNamespace
24+
25+
import pytest
26+
27+
from hackrfpy import cli
28+
from hackrfpy.exceptions import HackRFValueError
29+
30+
31+
# --- realistic hackrf_info output (mirrors tests/fixtures/hackrf_info.txt) ---
32+
INFO_TEXT = (
33+
"hackrf_info version: 2024.02.1\n"
34+
"libhackrf version: 2024.02.1 (0.9)\n"
35+
"Found HackRF\n"
36+
"Index: 0\n"
37+
"Serial number: 0000000000000000457863c82b4f3f\n"
38+
"Board ID Number: 2 (HackRF One)\n"
39+
"Firmware Version: 2024.02.1 (API:1.08)\n"
40+
"Part ID Number: 0xa000cb3c 0x004f4762\n"
41+
"Hardware Revision: r9\n"
42+
)
43+
44+
# two well-formed hackrf_sweep CSV rows (date, time, lo, hi, binw, nsamp, db...)
45+
SWEEP_ROWS = (
46+
"2026-06-10, 12:00:00.000000, 88000000, 88500000, 100000.00, 8192, "
47+
"-71.23, -70.10, -69.95, -72.40, -71.88\n"
48+
"2026-06-10, 12:00:00.000000, 88500000, 89000000, 100000.00, 8192, "
49+
"-70.01, -71.12, -72.23, -73.34, -74.45\n"
50+
)
51+
52+
53+
def _write_tool(tools_dir, name, *, emit=""):
54+
"""Write a resolvable stub binary that prints `emit` then exits 0.
55+
56+
POSIX : a shebang'd executable file `<name>` (chmod +x)
57+
Windows: a `<name>.py` plus a `<name>.bat` launcher on PATHEXT
58+
resolve() only needs isfile + X_OK; the functional stubs additionally
59+
emit canned stdout so info/detect/doctor/sweep have something to parse.
60+
"""
61+
prog = "import sys\n"
62+
if emit:
63+
prog += f"sys.stdout.write({emit!r})\n"
64+
prog += "sys.exit(0)\n"
65+
66+
if os.name == "nt":
67+
py = os.path.join(tools_dir, name + ".py")
68+
with open(py, "w") as f:
69+
f.write(prog)
70+
launcher = os.path.join(tools_dir, name + ".bat")
71+
with open(launcher, "w") as f:
72+
f.write(f'@echo off\r\n"{sys.executable}" "{py}" %*\r\n')
73+
return launcher
74+
75+
launcher = os.path.join(tools_dir, name)
76+
with open(launcher, "w") as f:
77+
f.write(f"#!{sys.executable}\n")
78+
f.write(prog)
79+
os.chmod(launcher, os.stat(launcher).st_mode
80+
| stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
81+
return launcher
82+
83+
84+
@pytest.fixture
85+
def cli_env(tmp_path, monkeypatch):
86+
"""Hermetic CLI environment: stub tools + a private config/state dir."""
87+
monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path / "config"))
88+
tools = tmp_path / "tools"
89+
tools.mkdir()
90+
_write_tool(str(tools), "hackrf_info", emit=INFO_TEXT)
91+
_write_tool(str(tools), "hackrf_transfer") # only resolved
92+
_write_tool(str(tools), "hackrf_sweep", emit=SWEEP_ROWS)
93+
94+
real_cls = cli.HackRF
95+
96+
def _factory(*a, **k):
97+
k.setdefault("tools_dir", str(tools))
98+
return real_cls(*a, **k)
99+
100+
monkeypatch.setattr(cli, "HackRF", _factory)
101+
return SimpleNamespace(tools=str(tools), tmp=tmp_path)
102+
103+
104+
def _run_cli(argv):
105+
app = cli.HackRFCLI(argv)
106+
app.main(app.getArgs())
107+
108+
109+
# =====================================================================
110+
# argument parsing / help / version
111+
# =====================================================================
112+
def test_version_action_exits_zero(capsys):
113+
with pytest.raises(SystemExit) as exc:
114+
cli.HackRFCLI(["--version"])
115+
assert exc.value.code == 0
116+
assert "hrf" in capsys.readouterr().out
117+
118+
119+
def test_no_subcommand_prints_help(capsys):
120+
_run_cli([])
121+
out = capsys.readouterr().out
122+
assert "usage" in out.lower()
123+
124+
125+
def test_bad_mode_choice_is_rejected():
126+
# argparse enforces the choices=C.MODES constraint
127+
with pytest.raises(SystemExit):
128+
cli.HackRFCLI(["mode", "sideways"])
129+
130+
131+
def test_sweep_requires_edges():
132+
with pytest.raises(SystemExit):
133+
cli.HackRFCLI(["sweep"]) # --f-min / --f-max are required
134+
135+
136+
# =====================================================================
137+
# mode state file (read/write round-trip, get/set dispatch)
138+
# =====================================================================
139+
def test_mode_state_roundtrip(cli_env, capsys):
140+
# default when no state file exists
141+
_run_cli(["mode"])
142+
assert capsys.readouterr().out.strip() == "rx"
143+
144+
# setting tx fires the safety banner and persists
145+
_run_cli(["mode", "tx"])
146+
assert "TX MODE ARMED" in capsys.readouterr().out
147+
148+
# a fresh read sees the persisted mode
149+
_run_cli(["mode"])
150+
assert capsys.readouterr().out.strip() == "tx"
151+
152+
153+
def test_read_mode_default_without_file(cli_env):
154+
assert cli.read_mode() == "rx"
155+
156+
157+
def test_write_then_read_mode(cli_env):
158+
cli.write_mode("tx")
159+
assert cli.read_mode() == "tx"
160+
161+
162+
# =====================================================================
163+
# presets
164+
# =====================================================================
165+
def test_presets_listing(cli_env, capsys):
166+
_run_cli(["presets"])
167+
out = capsys.readouterr().out
168+
assert "fm" in out
169+
assert "ads-b" in out
170+
171+
172+
# =====================================================================
173+
# info / detect / doctor (functional hackrf_info stub)
174+
# =====================================================================
175+
def test_info_parsed_output(cli_env, capsys):
176+
_run_cli(["info"])
177+
out = capsys.readouterr().out
178+
assert "457863c82b4f3f" in out # serial from the stub
179+
180+
181+
def test_info_print_cmd_does_not_parse(cli_env, capsys):
182+
_run_cli(["info", "--print-cmd"])
183+
out = capsys.readouterr().out
184+
assert "hackrf_info" in out
185+
assert "457863c82b4f3f" not in out # nothing was executed/parsed
186+
187+
188+
def test_detect_reports_ready_board(cli_env, capsys):
189+
_run_cli(["detect"])
190+
out = capsys.readouterr().out
191+
assert "hackrfpy detect" in out
192+
assert "ready" in out
193+
194+
195+
def test_detect_exits_nonzero_when_no_board(cli_env):
196+
# rewrite the info stub to report no board; detect must exit 1 so that
197+
# `hrf detect && hrf rx ...` short-circuits.
198+
no_board = ("hackrf_info version: 2024.02.1\n"
199+
"libhackrf version: 2024.02.1 (0.9)\n"
200+
"No HackRF boards found.\n")
201+
_write_tool(cli_env.tools, "hackrf_info", emit=no_board)
202+
with pytest.raises(SystemExit) as exc:
203+
_run_cli(["detect"])
204+
assert exc.value.code == 1
205+
206+
207+
def test_doctor_ok_with_core_tools(cli_env):
208+
# all three core tools present -> no problems -> no exit
209+
_run_cli(["doctor"])
210+
211+
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)
218+
with pytest.raises(SystemExit) as exc:
219+
_run_cli(["doctor"])
220+
assert exc.value.code == 1
221+
222+
223+
# =====================================================================
224+
# rx dispatch (--print-cmd builds argv; --preset resolves freq)
225+
# =====================================================================
226+
def test_rx_print_cmd_builds_transfer(cli_env, capsys):
227+
_run_cli(["rx", "-f", "433.92M", "-s", "8M", "-n", "1000000",
228+
"--print-cmd"])
229+
out = capsys.readouterr().out
230+
assert "hackrf_transfer" in out
231+
assert "-f 433920000" in out
232+
assert "-n 1000000" in out
233+
234+
235+
def test_rx_preset_supplies_frequency(cli_env, capsys):
236+
_run_cli(["rx", "--preset", "fm", "-n", "1000", "--print-cmd"])
237+
out = capsys.readouterr().out
238+
# fm preset: f_min 88 MHz becomes the center when -f is omitted
239+
assert "-f 88000000" in out
240+
241+
242+
def test_rx_without_freq_or_preset_raises(cli_env):
243+
app = cli.HackRFCLI(["rx", "-s", "8M", "-n", "1000"])
244+
with pytest.raises(HackRFValueError):
245+
app.main(app.getArgs())
246+
247+
248+
# =====================================================================
249+
# tx dispatch (requires persisted TX mode)
250+
# =====================================================================
251+
def test_tx_print_cmd_requires_tx_mode(cli_env, tmp_path, capsys):
252+
src = tmp_path / "sig.iq"
253+
src.write_bytes(b"\x00\x01" * 16)
254+
255+
cli.write_mode("tx") # arm TX for this invocation
256+
_run_cli(["tx", str(src), "-f", "433.92M", "-s", "8M", "-x", "20",
257+
"--print-cmd"])
258+
out = capsys.readouterr().out
259+
assert "hackrf_transfer" in out
260+
assert "-t" in out and "-x 20" in out
261+
262+
263+
def test_tx_blocked_in_rx_mode(cli_env, tmp_path):
264+
from hackrfpy.exceptions import HackRFModeError
265+
src = tmp_path / "sig.iq"
266+
src.write_bytes(b"\x00\x01" * 16)
267+
# mode defaults to rx; the gate must reject transmit
268+
app = cli.HackRFCLI(["tx", str(src), "-f", "433.92M", "-s", "8M"])
269+
with pytest.raises(HackRFModeError):
270+
app.main(app.getArgs())
271+
272+
273+
# =====================================================================
274+
# sweep dispatch (print_cmd path + the CSV printing loop)
275+
# =====================================================================
276+
def test_sweep_print_cmd(cli_env, capsys):
277+
_run_cli(["sweep", "--f-min", "88M", "--f-max", "108M", "--print-cmd"])
278+
out = capsys.readouterr().out
279+
assert "hackrf_sweep" in out
280+
assert "-f 88:108" in out
281+
282+
283+
def test_sweep_streams_csv_rows(cli_env, capsys):
284+
# functional hackrf_sweep stub emits two rows then exits; the CLI parses
285+
# and re-prints them as CSV.
286+
_run_cli(["sweep", "--f-min", "88M", "--f-max", "89M"])
287+
out = capsys.readouterr().out
288+
assert "88000000" in out
289+
assert out.count("\n") >= 2 # both rows printed
290+
291+
292+
# =====================================================================
293+
# module-level main(): exception -> exit code mapping
294+
# =====================================================================
295+
def test_module_main_success(cli_env, monkeypatch):
296+
monkeypatch.setattr(sys, "argv", ["hrf", "presets"])
297+
cli.main() # returns cleanly, no SystemExit
298+
299+
300+
def test_module_main_maps_value_error(cli_env, monkeypatch):
301+
# rx with no frequency -> HackRFValueError (exit code 2)
302+
monkeypatch.setattr(sys, "argv", ["hrf", "rx", "-s", "8M", "-n", "1000"])
303+
with pytest.raises(SystemExit) as exc:
304+
cli.main()
305+
assert exc.value.code == 2
306+
307+
308+
def test_module_main_keyboard_interrupt(monkeypatch):
309+
def _boom(*a, **k):
310+
raise KeyboardInterrupt
311+
monkeypatch.setattr(cli.HackRFCLI, "main", _boom)
312+
monkeypatch.setattr(sys, "argv", ["hrf", "info"])
313+
with pytest.raises(SystemExit) as exc:
314+
cli.main()
315+
assert exc.value.code == 130
316+
317+
318+
# =====================================================================
319+
# _print_detect formatting (pure function; both branches)
320+
# =====================================================================
321+
def test_print_detect_not_found(capsys):
322+
cli._print_detect({
323+
"found": False, "problem": "no HackRF boards found",
324+
"count": 0, "boards": [], "tools_version": None,
325+
"libhackrf_version": None, "multiple": False, "ready": False,
326+
})
327+
assert "no HackRF boards found" in capsys.readouterr().out
328+
329+
330+
def test_print_detect_rich_report(capsys):
331+
cli._print_detect({
332+
"found": True, "problem": "", "count": 2,
333+
"tools_version": "2024.02.1", "libhackrf_version": "2024.02.1 (0.9)",
334+
"boards": [
335+
{"index": 0, "is_hackrf": True, "serial": "abc",
336+
"name": "HackRF One", "firmware": "2024.02.1",
337+
"firmware_stale": False},
338+
{"index": 1, "is_hackrf": False, "serial": "def",
339+
"name": "?", "firmware": "2019.01.1",
340+
"firmware_stale": True},
341+
],
342+
"multiple": True, "ready": True,
343+
"warnings": ["one board has stale firmware"],
344+
})
345+
out = capsys.readouterr().out
346+
assert "UNCONFIRMED" in out # the non-HackRF board
347+
assert "stale" in out # firmware_stale branch
348+
assert "multiple boards" in out # multiple branch
349+
assert "one board has stale firmware" in out # warnings branch

0 commit comments

Comments
 (0)