Debian Codegraph @

test/test_asncounter.py

raw symbols SCIP
1 import io
2 from collections import Counter
3 from pathlib import Path
4 from unittest.mock import MagicMock, patch, sentinel
5
6 import pyasn
7 import pytest
8
9 from asncounter import (
10 BaseLineCollector,
11 CollectionsRecorder,
12 LineCollector,
13 PrometheusRecorder,
14 TcpdumpLineCollector,
15 TupleCollector,
16 args,
17 main,
18 )
19
20 # this uses AS64496 from RFC5398, 192.0.2.0/24 and 203.0.113.0/24 from
21 # RFC5737, and 2001:DB8::/32 from RFC3849
22 SAMPLE_DB = """\
23 192.0.2.0/24\t64496
24 2001:DB8::/48\t64496
25 2001:DB8:1::/48\t64497
26 """
27
28 TEST_LINE_ADDRESSES = """\
29 192.0.2.1 # comment
30 192.0.2.2
31 203.0.113.42
32 2001:DB8::1
33 2001:DB8:1::1
34 2001:DB8:2::1
35 # comment
36
37 garbage
38 """
39
40 TEST_LINE_ASN = Counter({None: 2, 64496: 3, 64497: 1})
41 TEST_LINE_PREFIXES = Counter(
42 {None: 2, "192.0.2.0/24": 2, "2001:db8:1::/48": 1, "2001:db8::/48": 1}
43 )
44
45 TEST_TUPLE_ADDRESSES = """\
46 192.0.2.1 1 # comment
47 192.0.2.2 3.4
48 192.0.2.2 2.5
49 203.0.113.42 3
50 2001:DB8::1 0
51 2001:DB8:1::1 1337.3
52 2001:DB8:2::1 1
53 # comment
54
55 garbage
56 """
57
58
59 @pytest.fixture
60 def recorder_setup() -> CollectionsRecorder:
61 args.no_asn = False
62 args.no_prefixes = False
63 args.no_resolve_asn = True
64 args.top = 10
65
66 # required for lookups operations, should probably be moved to the recorder
67 recorder = CollectionsRecorder()
68 # test for division by zero
69 recorder.display_results()
70 recorder.asndb = pyasn.pyasn(None, ipasn_string=SAMPLE_DB)
71 return recorder
72
73
74 def test_line_collectors(recorder_setup: CollectionsRecorder) -> None:
75 recorder = recorder_setup
76 stream = io.StringIO(TEST_LINE_ADDRESSES)
77 collector: BaseLineCollector = LineCollector(recorder=recorder)
78 collector.collect(stream)
79 assert recorder.asn_counter == TEST_LINE_ASN
80 assert recorder.prefix_counter == TEST_LINE_PREFIXES
81 stream = io.StringIO(
82 "10:41:33.342516 IP 192.0.2.3.65278 > 192.0.2.255.59387: UDP, length 42\n",
83 )
84 collector = TcpdumpLineCollector(recorder=recorder)
85 collector.collect(stream)
86 assert recorder.asn_counter == Counter({None: 2, 64496: 4, 64497: 1})
87 assert recorder.prefix_counter == Counter(
88 {None: 2, "192.0.2.0/24": 3, "2001:db8:1::/48": 1, "2001:db8::/48": 1}
89 )
90 recorder.display_results()
91 assert recorder.asn_prefixes(64496) == {"192.0.2.0/24", "2001:db8::/48"}
92 assert recorder.asn_prefixes(64496, 64497) == {
93 "192.0.2.0/24",
94 "2001:db8::/48",
95 "2001:db8:1::/48",
96 }
97
98
99 def test_tuple_collector(recorder_setup: CollectionsRecorder) -> None:
100 recorder = recorder_setup
101
102 stream = io.StringIO(TEST_TUPLE_ADDRESSES)
103 collector = TupleCollector(recorder=recorder)
104 collector.collect(stream)
105 assert recorder.asn_counter == Counter({None: 4, 64496: 6.9, 64497: 1337.3})
106 assert recorder.prefix_counter == Counter(
107 {None: 4, "192.0.2.0/24": 6.9, "2001:db8:1::/48": 1337.3, "2001:db8::/48": 0}
108 )
109
110
111 @pytest.mark.parametrize(
112 "line, expected",
113 [
114 ("garbage", (None, 0.0)),
115 (
116 "19:05:02.229065 IP 203.0.113.42.443 > 216.90.108.31.62122: tcp 60",
117 ("203.0.113.42", 1.0),
118 ),
119 (
120 "19:05:02.229065 IP6 2001:DB8::1.443 > 2001:DB8::2.62122: tcp 60",
121 ("2001:DB8::1", 1.0),
122 ),
123 (
124 "14:44:58.275872 IP [total length 52 > length 44] (invalid) 111.88.85.34.46277 > 116.202.120.165.443: tcp 0", # noqa: E501
125 ("111.88.85.34", 1.0),
126 ),
127 ],
128 )
129 def test_parse_tcpdump(line: str, expected: tuple[str | None, float]) -> None:
130 c = TcpdumpLineCollector(recorder=lambda x, y: None) # type: ignore[arg-type]
131 assert c.parse(line) == expected
132
133
134 @patch("asncounter.prometheus_client")
135 def test_prometheus_record(mock_prom: sentinel) -> None:
136 # Mock the arguments for the test
137 args.no_asn = False
138 args.no_prefixes = False
139 args.no_resolve_asn = False
140
141 # Initialize PrometheusRecorder with mock Prometheus client
142 recorder = PrometheusRecorder(port=None)
143
144 # Mock the lookup_asn return values
145 recorder.lookup_asn = MagicMock(return_value="as name") # type: ignore[method-assign]
146
147 # Record sample data
148 recorder.record(asn=64496, prefix="192.0.2.0/24")
149
150 # Ensure labels are called with correct values
151 mock_prom.Counter.return_value.labels.assert_any_call(64496, "as name")
152 mock_prom.Counter.return_value.labels.assert_any_call(
153 "192.0.2.0/24", 64496, "as name"
154 )
155
156 # reset mock
157 recorder.lookup_asn = MagicMock(return_value=None) # type: ignore[method-assign]
158
159 # Record sample data with None values
160 recorder.record(asn=None, prefix=None)
161
162 # Ensure labels are called with correct values
163 mock_prom.Counter.return_value.labels.assert_any_call(None, "")
164 mock_prom.Counter.return_value.labels.assert_any_call(None, None, "")
165
166
167 def test_dump_prefixes(recorder_setup: CollectionsRecorder) -> None:
168 """test the --dump-prefixes command"""
169 buf = io.StringIO()
170 assert recorder_setup.dump_prefixes("64496", buf) == 0
171 assert buf.getvalue() == "192.0.2.0/24\n2001:db8::/48\n"
172 # "AS" prefix
173 assert recorder_setup.dump_prefixes("as64496", buf) == 0
174 # case-insensitive and with "ASN" prefix
175 assert recorder_setup.dump_prefixes("ASN64496", buf) == 0
176 # non-existing ASN yields an errorx
177 assert recorder_setup.dump_prefixes("NOTANASN", buf) == 1
178 # test that a non-existing ASN yields nothing (not even a newline)
179 buf = io.StringIO()
180 assert recorder_setup.dump_prefixes("1", buf) == 0
181 assert buf.getvalue() == ""
182
183
184 @patch("asncounter.refresh_datfile")
185 @patch("asncounter.download_asnames")
186 def test_main(
187 mock_refresh_datfile: sentinel,
188 mock_download_asnames: sentinel,
189 tmp_path: Path,
190 ) -> None:
191 """test main path
192
193 This tests the cache lookup logic but not, obviously, the download
194 logic, as that requires internet and we don't want to unit test
195 upstream pyasn routines here, we trust they do their thing.
196 """
197
198 datfile = tmp_path / "ipasn_20250613.200000.dat"
199 asnames = tmp_path / "asnames.json"
200 mock_refresh_datfile.return_value = str(datfile)
201
202 testfile = tmp_path / "testfile.txt"
203 with testfile.open("w") as fp:
204 fp.write(TEST_LINE_ADDRESSES)
205 # test lookups of a single IP on the commandline, along with an input file
206 argv = ["--cache-directory", str(tmp_path), "192.0.2.1"]
207 with datfile.open("w") as fp:
208 fp.write(SAMPLE_DB)
209 with asnames.open("w") as fp:
210 fp.write("{}")
211 recorder = main(argv)
212 assert isinstance(recorder, CollectionsRecorder)
213 assert not mock_download_asnames.called
214 assert not mock_refresh_datfile.called
215 # results match the input file *and* commandline IP
216 assert recorder.asn_counter == Counter({64496: 1})
217 assert recorder.prefix_counter == Counter({"192.0.2.0/24": 1})
218
219 # test --input still works
220 argv = ["--cache-directory", str(tmp_path), "--input", str(testfile)]
221 recorder = main(argv)
222 assert isinstance(recorder, CollectionsRecorder)
223 assert recorder.asn_counter == TEST_LINE_ASN
224 assert recorder.prefix_counter == TEST_LINE_PREFIXES