foxglove-sdk 0.16.4__cp314-cp314-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl

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.

Potentially problematic release.


This version of foxglove-sdk might be problematic. Click here for more details.

@@ -0,0 +1,477 @@
1
+ from io import SEEK_CUR, SEEK_SET, BytesIO
2
+ from pathlib import Path
3
+ from typing import Callable, Generator, Optional, Union
4
+
5
+ import pytest
6
+ from foxglove import Channel, ChannelDescriptor, Context, open_mcap
7
+ from foxglove.mcap import MCAPWriteOptions
8
+
9
+ chan = Channel("test", schema={"type": "object"})
10
+
11
+
12
+ @pytest.fixture
13
+ def make_tmp_mcap(
14
+ tmp_path_factory: pytest.TempPathFactory,
15
+ ) -> Generator[Callable[[], Path], None, None]:
16
+ mcap: Optional[Path] = None
17
+ dir: Optional[Path] = None
18
+
19
+ def _make_tmp_mcap() -> Path:
20
+ nonlocal dir, mcap
21
+ dir = tmp_path_factory.mktemp("test", numbered=True)
22
+ mcap = dir / "test.mcap"
23
+ return mcap
24
+
25
+ yield _make_tmp_mcap
26
+
27
+ if mcap is not None and dir is not None:
28
+ try:
29
+ mcap.unlink()
30
+ dir.rmdir()
31
+ except FileNotFoundError:
32
+ pass
33
+
34
+
35
+ @pytest.fixture
36
+ def tmp_mcap(make_tmp_mcap: Callable[[], Path]) -> Generator[Path, None, None]:
37
+ yield make_tmp_mcap()
38
+
39
+
40
+ def test_open_with_str(tmp_mcap: Path) -> None:
41
+ open_mcap(str(tmp_mcap))
42
+
43
+
44
+ def test_overwrite(tmp_mcap: Path) -> None:
45
+ tmp_mcap.touch()
46
+ with pytest.raises(FileExistsError):
47
+ open_mcap(tmp_mcap)
48
+ open_mcap(tmp_mcap, allow_overwrite=True)
49
+
50
+
51
+ def test_explicit_close(tmp_mcap: Path) -> None:
52
+ mcap = open_mcap(tmp_mcap)
53
+ for ii in range(20):
54
+ chan.log({"foo": ii})
55
+ size_before_close = tmp_mcap.stat().st_size
56
+ mcap.close()
57
+ assert tmp_mcap.stat().st_size > size_before_close
58
+
59
+
60
+ def test_context_manager(tmp_mcap: Path) -> None:
61
+ with open_mcap(tmp_mcap):
62
+ for ii in range(20):
63
+ chan.log({"foo": ii})
64
+ size_before_close = tmp_mcap.stat().st_size
65
+ assert tmp_mcap.stat().st_size > size_before_close
66
+
67
+
68
+ def test_writer_compression(make_tmp_mcap: Callable[[], Path]) -> None:
69
+ tmp_1 = make_tmp_mcap()
70
+ tmp_2 = make_tmp_mcap()
71
+
72
+ # Compression is enabled by default
73
+ mcap_1 = open_mcap(tmp_1)
74
+ mcap_2 = open_mcap(tmp_2, writer_options=MCAPWriteOptions(compression=None))
75
+
76
+ for _ in range(20):
77
+ chan.log({"foo": "bar"})
78
+
79
+ mcap_1.close()
80
+ mcap_2.close()
81
+
82
+ assert tmp_1.stat().st_size < tmp_2.stat().st_size
83
+
84
+
85
+ def test_writer_custom_profile(tmp_mcap: Path) -> None:
86
+ options = MCAPWriteOptions(profile="--custom-profile-1--")
87
+ with open_mcap(tmp_mcap, writer_options=options):
88
+ chan.log({"foo": "bar"})
89
+
90
+ contents = tmp_mcap.read_bytes()
91
+ assert contents.find(b"--custom-profile-1--") > -1
92
+
93
+
94
+ def test_write_to_different_contexts(make_tmp_mcap: Callable[[], Path]) -> None:
95
+ tmp_1 = make_tmp_mcap()
96
+ tmp_2 = make_tmp_mcap()
97
+
98
+ ctx1 = Context()
99
+ ctx2 = Context()
100
+
101
+ options = MCAPWriteOptions(compression=None)
102
+ mcap1 = open_mcap(tmp_1, writer_options=options, context=ctx1)
103
+ mcap2 = open_mcap(tmp_2, writer_options=options, context=ctx2)
104
+
105
+ ch1 = Channel("ctx1", context=ctx1)
106
+ ch1.log({"a": "b"})
107
+
108
+ ch2 = Channel("ctx2", context=ctx2)
109
+ ch2.log({"has-more-data": "true"})
110
+
111
+ mcap1.close()
112
+ mcap2.close()
113
+
114
+ contents1 = tmp_1.read_bytes()
115
+ contents2 = tmp_2.read_bytes()
116
+
117
+ assert len(contents1) < len(contents2)
118
+
119
+
120
+ def _verify_metadata_in_file(file_path: Path, expected_metadata: dict) -> None:
121
+ """Helper function to verify metadata in MCAP file matches expected."""
122
+ import mcap.reader
123
+
124
+ with open(file_path, "rb") as f:
125
+ reader = mcap.reader.make_reader(f)
126
+
127
+ found_metadata = {}
128
+ metadata_count = 0
129
+
130
+ for record in reader.iter_metadata():
131
+ metadata_count += 1
132
+ found_metadata[record.name] = dict(record.metadata)
133
+
134
+ # Verify count
135
+ assert metadata_count == len(
136
+ expected_metadata
137
+ ), f"Expected {len(expected_metadata)} metadata records, found {metadata_count}"
138
+
139
+ # Verify metadata names and content
140
+ assert set(found_metadata.keys()) == set(
141
+ expected_metadata.keys()
142
+ ), "Metadata names don't match"
143
+
144
+ for name, expected_kv in expected_metadata.items():
145
+ assert (
146
+ found_metadata[name] == expected_kv
147
+ ), f"Metadata '{name}' has wrong key-value pairs"
148
+
149
+
150
+ def _verify_attachments_in_file(
151
+ file_path: Path, expected_attachments: list[dict]
152
+ ) -> None:
153
+ """Helper function to verify attachments in MCAP file match expected."""
154
+ import mcap.reader
155
+
156
+ with open(file_path, "rb") as f:
157
+ reader = mcap.reader.make_reader(f)
158
+
159
+ found_attachments = []
160
+ for attachment in reader.iter_attachments():
161
+ found_attachments.append(
162
+ {
163
+ "log_time": attachment.log_time,
164
+ "create_time": attachment.create_time,
165
+ "name": attachment.name,
166
+ "media_type": attachment.media_type,
167
+ "data": attachment.data,
168
+ }
169
+ )
170
+
171
+ # Verify count
172
+ assert len(found_attachments) == len(
173
+ expected_attachments
174
+ ), f"Expected {len(expected_attachments)} attachments, found {len(found_attachments)}"
175
+
176
+ # Verify each attachment matches expected
177
+ for expected in expected_attachments:
178
+ matching = [a for a in found_attachments if a["name"] == expected["name"]]
179
+ assert len(matching) == 1, f"Attachment '{expected['name']}' not found"
180
+ actual = matching[0]
181
+ assert (
182
+ actual["log_time"] == expected["log_time"]
183
+ ), f"Attachment '{expected['name']}' has wrong log_time"
184
+ assert (
185
+ actual["create_time"] == expected["create_time"]
186
+ ), f"Attachment '{expected['name']}' has wrong create_time"
187
+ assert (
188
+ actual["media_type"] == expected["media_type"]
189
+ ), f"Attachment '{expected['name']}' has wrong media_type"
190
+ assert (
191
+ actual["data"] == expected["data"]
192
+ ), f"Attachment '{expected['name']}' has wrong data"
193
+
194
+
195
+ def test_write_metadata(tmp_mcap: Path) -> None:
196
+ """Test writing metadata to MCAP file."""
197
+ # Define expected metadata
198
+ expected_metadata = {
199
+ "test1": {"key1": "value1", "key2": "value2"},
200
+ "test2": {"a": "1", "b": "2"},
201
+ "test3": {"x": "y", "z": "w"},
202
+ }
203
+
204
+ with open_mcap(tmp_mcap) as writer:
205
+ # This should not raise an error
206
+ writer.write_metadata("empty", {})
207
+
208
+ # Write basic metadata
209
+ writer.write_metadata("test1", expected_metadata["test1"])
210
+
211
+ # Write multiple metadata records
212
+ writer.write_metadata("test2", expected_metadata["test2"])
213
+ writer.write_metadata("test3", expected_metadata["test3"])
214
+
215
+ # Write empty metadata (should be skipped)
216
+ writer.write_metadata("empty_test", {})
217
+
218
+ # Log some messages
219
+ for ii in range(5):
220
+ chan.log({"foo": ii})
221
+
222
+ # Verify metadata was written correctly
223
+ _verify_metadata_in_file(tmp_mcap, expected_metadata)
224
+
225
+
226
+ def test_channel_filter(make_tmp_mcap: Callable[[], Path]) -> None:
227
+ tmp_1 = make_tmp_mcap()
228
+ tmp_2 = make_tmp_mcap()
229
+
230
+ ch1 = Channel("/1", schema={"type": "object"})
231
+ ch2 = Channel("/2", schema={"type": "object"})
232
+
233
+ def filter(ch: ChannelDescriptor) -> bool:
234
+ return ch.topic.startswith("/1")
235
+
236
+ mcap1 = open_mcap(tmp_1, channel_filter=filter)
237
+ mcap2 = open_mcap(tmp_2, channel_filter=None)
238
+
239
+ ch1.log({})
240
+ ch2.log({})
241
+
242
+ mcap1.close()
243
+ mcap2.close()
244
+
245
+ assert tmp_1.stat().st_size < tmp_2.stat().st_size
246
+
247
+
248
+ def test_attach_basic(tmp_mcap: Path) -> None:
249
+ """Test writing a single attachment to MCAP file."""
250
+ expected_attachments = [
251
+ {
252
+ "log_time": 1000000000,
253
+ "create_time": 2000000000,
254
+ "name": "config.json",
255
+ "media_type": "application/json",
256
+ "data": b'{"setting": true}',
257
+ }
258
+ ]
259
+
260
+ with open_mcap(tmp_mcap) as writer:
261
+ writer.attach(
262
+ log_time=1000000000,
263
+ create_time=2000000000,
264
+ name="config.json",
265
+ media_type="application/json",
266
+ data=b'{"setting": true}',
267
+ )
268
+
269
+ _verify_attachments_in_file(tmp_mcap, expected_attachments)
270
+
271
+
272
+ def test_attach_multiple(tmp_mcap: Path) -> None:
273
+ """Test writing multiple attachments to MCAP file."""
274
+ expected_attachments = [
275
+ {
276
+ "log_time": 100,
277
+ "create_time": 200,
278
+ "name": "config.json",
279
+ "media_type": "application/json",
280
+ "data": b'{"setting": true}',
281
+ },
282
+ {
283
+ "log_time": 300,
284
+ "create_time": 400,
285
+ "name": "calibration.yaml",
286
+ "media_type": "text/yaml",
287
+ "data": b"camera:\n fx: 500\n fy: 500",
288
+ },
289
+ {
290
+ "log_time": 500,
291
+ "create_time": 600,
292
+ "name": "image.png",
293
+ "media_type": "image/png",
294
+ "data": bytes([0x89, 0x50, 0x4E, 0x47]), # PNG magic bytes
295
+ },
296
+ ]
297
+
298
+ with open_mcap(tmp_mcap) as writer:
299
+ writer.attach(
300
+ log_time=100,
301
+ create_time=200,
302
+ name="config.json",
303
+ media_type="application/json",
304
+ data=b'{"setting": true}',
305
+ )
306
+ writer.attach(
307
+ log_time=300,
308
+ create_time=400,
309
+ name="calibration.yaml",
310
+ media_type="text/yaml",
311
+ data=b"camera:\n fx: 500\n fy: 500",
312
+ )
313
+ writer.attach(
314
+ log_time=500,
315
+ create_time=600,
316
+ name="image.png",
317
+ media_type="image/png",
318
+ data=bytes([0x89, 0x50, 0x4E, 0x47]), # PNG magic bytes
319
+ )
320
+
321
+ _verify_attachments_in_file(tmp_mcap, expected_attachments)
322
+
323
+
324
+ def test_attach_with_messages(tmp_mcap: Path) -> None:
325
+ """Test writing attachments alongside messages."""
326
+ with open_mcap(tmp_mcap) as writer:
327
+ # Write some messages
328
+ for ii in range(5):
329
+ chan.log({"foo": ii})
330
+
331
+ # Write an attachment
332
+ writer.attach(
333
+ log_time=1000,
334
+ create_time=2000,
335
+ name="notes.txt",
336
+ media_type="text/plain",
337
+ data=b"Recording notes",
338
+ )
339
+
340
+ # Write more messages
341
+ for ii in range(5, 10):
342
+ chan.log({"foo": ii})
343
+
344
+ # Verify attachment was written
345
+ expected_attachments = [
346
+ {
347
+ "log_time": 1000,
348
+ "create_time": 2000,
349
+ "name": "notes.txt",
350
+ "media_type": "text/plain",
351
+ "data": b"Recording notes",
352
+ }
353
+ ]
354
+ _verify_attachments_in_file(tmp_mcap, expected_attachments)
355
+
356
+
357
+ def test_attach_after_close(tmp_mcap: Path) -> None:
358
+ """Test that attaching after close raises an error."""
359
+ writer = open_mcap(tmp_mcap)
360
+ writer.close()
361
+
362
+ with pytest.raises(Exception): # FoxgloveError for SinkClosed
363
+ writer.attach(
364
+ log_time=100,
365
+ create_time=200,
366
+ name="test.txt",
367
+ media_type="text/plain",
368
+ data=b"test",
369
+ )
370
+
371
+
372
+ # =============================================================================
373
+ # Tests for file-like object support
374
+ # =============================================================================
375
+
376
+
377
+ class TestFileLikeObject:
378
+ """Tests for writing MCAP to file-like objects."""
379
+
380
+ def test_write_to_bytesio(self) -> None:
381
+ """Test writing MCAP to a BytesIO buffer produces valid MCAP."""
382
+ buffer = BytesIO()
383
+ test_chan = Channel("test_bytesio", schema={"type": "object"})
384
+
385
+ with open_mcap(buffer):
386
+ for i in range(10):
387
+ test_chan.log({"value": i})
388
+
389
+ # Verify buffer has data with MCAP magic bytes
390
+ data = buffer.getvalue()
391
+ assert len(data) > 0
392
+ assert data[:8] == b"\x89MCAP0\r\n"
393
+
394
+ def test_bytesio_readable_by_mcap_reader(self) -> None:
395
+ """Test that MCAP written to BytesIO can be read back."""
396
+ import mcap.reader
397
+
398
+ buffer = BytesIO()
399
+ test_chan = Channel("test_readable", schema={"type": "object"})
400
+
401
+ with open_mcap(buffer):
402
+ for i in range(5):
403
+ test_chan.log({"index": i})
404
+
405
+ # Read back and verify
406
+ buffer.seek(0)
407
+ reader = mcap.reader.make_reader(buffer)
408
+ summary = reader.get_summary()
409
+
410
+ assert summary is not None
411
+ assert summary.statistics is not None
412
+ assert summary.statistics.message_count == 5
413
+
414
+
415
+ # =============================================================================
416
+ # Tests for disable_seeking option
417
+ # =============================================================================
418
+
419
+
420
+ class NonSeekableWriter:
421
+ """A file-like object that supports write/flush but raises on actual seeks.
422
+
423
+ This mimics a non-seekable stream like a pipe or network socket. It allows
424
+ position queries (seek(0, SEEK_CUR) or tell()) and no-op seeks to the current
425
+ position, but raises OSError on any seek that would change the position.
426
+ """
427
+
428
+ def __init__(self) -> None:
429
+ self._buffer = BytesIO()
430
+ self._position = 0
431
+
432
+ def write(self, data: Union[bytes, bytearray]) -> int:
433
+ written = self._buffer.write(data)
434
+ self._position += written
435
+ return written
436
+
437
+ def flush(self) -> None:
438
+ self._buffer.flush()
439
+
440
+ def seek(self, offset: int, whence: int = SEEK_SET) -> int:
441
+ if whence == SEEK_CUR and offset == 0:
442
+ # Allow querying current position (tell())
443
+ return self._position
444
+ elif whence == SEEK_SET and offset == self._position:
445
+ # Allow no-op seek to current position
446
+ return self._position
447
+ else:
448
+ # Actual seeks that change position are not supported
449
+ raise OSError("Seeking is not supported")
450
+
451
+ def getvalue(self) -> bytes:
452
+ return self._buffer.getvalue()
453
+
454
+
455
+ class TestDisableSeeking:
456
+ """Tests for the disable_seeking option in MCAPWriteOptions."""
457
+
458
+ def test_disable_seeking_prevents_seek_calls(self) -> None:
459
+ """Test that disable_seeking=True allows writing without seek calls."""
460
+ writer = NonSeekableWriter()
461
+ options = MCAPWriteOptions(disable_seeking=True)
462
+ test_chan = Channel("test_no_seek", schema={"type": "object"})
463
+
464
+ with open_mcap(writer, writer_options=options):
465
+ test_chan.log({"value": 1})
466
+
467
+ # Verify MCAP magic bytes are present
468
+ assert writer.getvalue()[:8] == b"\x89MCAP0\r\n"
469
+
470
+ def test_seeking_fails_without_disable_seeking(self) -> None:
471
+ """Test that seeking is attempted by default and fails on non-seekable writer."""
472
+ writer = NonSeekableWriter()
473
+ test_chan = Channel("test_seek_default", schema={"type": "object"})
474
+
475
+ with pytest.raises(RuntimeError):
476
+ with open_mcap(writer):
477
+ test_chan.log({"value": 1})
@@ -0,0 +1,178 @@
1
+ import pytest
2
+ from foxglove.websocket import (
3
+ AnyNativeParameterValue,
4
+ Parameter,
5
+ ParameterType,
6
+ ParameterValue,
7
+ )
8
+
9
+
10
+ def test_empty() -> None:
11
+ p = Parameter("empty")
12
+ assert p.name == "empty"
13
+ assert p.type is None
14
+ assert p.value is None
15
+ assert p.get_value() is None
16
+
17
+
18
+ def test_float() -> None:
19
+ p = Parameter("float", value=1.234)
20
+ assert p.name == "float"
21
+ assert p.type == ParameterType.Float64
22
+ assert p.value == ParameterValue.Float64(1.234)
23
+ assert p.get_value() == 1.234
24
+
25
+
26
+ def test_int() -> None:
27
+ p = Parameter("int", value=1)
28
+ assert p.name == "int"
29
+ assert p.type is None
30
+ assert p.value == ParameterValue.Integer(1)
31
+ assert type(p.get_value()) is int
32
+ assert p.get_value() == 1
33
+
34
+
35
+ def test_float_array() -> None:
36
+ v: AnyNativeParameterValue = [1.0, 2.0, 3.0]
37
+ p = Parameter("float_array", value=v)
38
+ assert p.name == "float_array"
39
+ assert p.type == ParameterType.Float64Array
40
+ assert p.value == ParameterValue.Array(
41
+ [
42
+ ParameterValue.Float64(1.0),
43
+ ParameterValue.Float64(2.0),
44
+ ParameterValue.Float64(3.0),
45
+ ]
46
+ )
47
+ assert p.get_value() == v
48
+
49
+
50
+ def test_int_array() -> None:
51
+ v: AnyNativeParameterValue = [1, 2, 3]
52
+ p = Parameter("int_array", value=v)
53
+ assert p.name == "int_array"
54
+ assert p.type is None
55
+ assert p.value == ParameterValue.Array(
56
+ [
57
+ ParameterValue.Integer(1),
58
+ ParameterValue.Integer(2),
59
+ ParameterValue.Integer(3),
60
+ ]
61
+ )
62
+ assert p.get_value() == v
63
+
64
+
65
+ def test_parameter_value_integer() -> None:
66
+ p = Parameter("integer_param", value=ParameterValue.Integer(42))
67
+ assert p.name == "integer_param"
68
+ assert p.type is None
69
+ assert p.value == ParameterValue.Integer(42)
70
+ assert type(p.get_value()) is int
71
+ assert p.get_value() == 42
72
+
73
+
74
+ def test_heterogeneous_array() -> None:
75
+ v: AnyNativeParameterValue = ["a", 2, False]
76
+ p = Parameter("heterogeneous_array", value=v)
77
+ assert p.name == "heterogeneous_array"
78
+ assert p.type is None
79
+ assert p.value == ParameterValue.Array(
80
+ [
81
+ ParameterValue.String("a"),
82
+ ParameterValue.Integer(2),
83
+ ParameterValue.Bool(False),
84
+ ]
85
+ )
86
+ assert p.get_value() == v
87
+
88
+
89
+ def test_string() -> None:
90
+ p = Parameter("string", value="hello")
91
+ assert p.name == "string"
92
+ assert p.type is None
93
+ assert p.value == ParameterValue.String("hello")
94
+ assert p.get_value() == "hello"
95
+
96
+
97
+ def test_bytes() -> None:
98
+ p = Parameter("bytes", value=b"hello")
99
+ assert p.name == "bytes"
100
+ assert p.type == ParameterType.ByteArray
101
+ assert p.value == ParameterValue.String("aGVsbG8=")
102
+ assert p.get_value() == b"hello"
103
+
104
+
105
+ def test_dict() -> None:
106
+ v: AnyNativeParameterValue = {
107
+ "a": True,
108
+ "b": 2,
109
+ "c": "C",
110
+ "d": {"inner": [1, 2, 3]},
111
+ }
112
+ p = Parameter(
113
+ "dict",
114
+ value=v,
115
+ )
116
+ assert p.name == "dict"
117
+ assert p.type is None
118
+ assert p.value == ParameterValue.Dict(
119
+ {
120
+ "a": ParameterValue.Bool(True),
121
+ "b": ParameterValue.Integer(2),
122
+ "c": ParameterValue.String("C"),
123
+ "d": ParameterValue.Dict(
124
+ {
125
+ "inner": ParameterValue.Array(
126
+ [
127
+ ParameterValue.Integer(1),
128
+ ParameterValue.Integer(2),
129
+ ParameterValue.Integer(3),
130
+ ]
131
+ )
132
+ }
133
+ ),
134
+ }
135
+ )
136
+ assert p.get_value() == v
137
+
138
+
139
+ def test_explicit() -> None:
140
+ # Derive type from value
141
+ p = Parameter("float", value=ParameterValue.Float64(1))
142
+ assert p.type == ParameterType.Float64
143
+ assert p.get_value() == 1
144
+
145
+ # Override derived type.
146
+ p = Parameter(
147
+ "bad float array",
148
+ value=ParameterValue.Float64(1),
149
+ type=ParameterType.Float64Array,
150
+ )
151
+ assert p.type == ParameterType.Float64Array
152
+ assert p.get_value() == 1
153
+
154
+ # Override derived type in a different way.
155
+ p = Parameter(
156
+ "bad float",
157
+ value=ParameterValue.String("1"),
158
+ type=ParameterType.Float64,
159
+ )
160
+ assert p.type == ParameterType.Float64
161
+ assert p.get_value() == "1"
162
+
163
+ # Override derived type with None.
164
+ p = Parameter("underspecified float", value=ParameterValue.Float64(1), type=None)
165
+ assert p.type is None
166
+ assert p.get_value() == 1
167
+
168
+
169
+ def test_base64_decode_error() -> None:
170
+ p = Parameter(
171
+ "bad bytes",
172
+ value=ParameterValue.String("!!!"),
173
+ type=ParameterType.ByteArray,
174
+ )
175
+ assert p.type == ParameterType.ByteArray
176
+ assert p.value == ParameterValue.String("!!!")
177
+ with pytest.raises(ValueError, match=r"Failed to decode base64"):
178
+ p.get_value()
@@ -0,0 +1,17 @@
1
+ from foxglove.schemas import Log, LogLevel, Timestamp
2
+
3
+ """ Asserts that foxglove schemas can be encoded as protobuf. """
4
+
5
+
6
+ def test_can_encode() -> None:
7
+ msg = Log(
8
+ timestamp=Timestamp(5, 10),
9
+ level=LogLevel.Error,
10
+ message="hello",
11
+ name="logger",
12
+ file="file",
13
+ line=123,
14
+ )
15
+ encoded = msg.encode()
16
+ assert isinstance(encoded, bytes)
17
+ assert len(encoded) == 34