Build Reactive Signals for Bluesky's AT Protocol Firehose in Laravel
1<?php
2
3declare(strict_types=1);
4
5namespace SocialDept\AtpSignals\Tests\Unit;
6
7use PHPUnit\Framework\TestCase;
8use RuntimeException;
9use SocialDept\AtpSignals\Binary\Varint;
10
11class VarintTest extends TestCase
12{
13 public function test_decode_single_byte_values(): void
14 {
15 $this->assertSame(0, Varint::decode("\x00"));
16 $this->assertSame(1, Varint::decode("\x01"));
17 $this->assertSame(127, Varint::decode("\x7F"));
18 }
19
20 public function test_decode_multi_byte_values(): void
21 {
22 // 128 = 0x80 0x01
23 $this->assertSame(128, Varint::decode("\x80\x01"));
24
25 // 300 = 0xAC 0x02
26 $this->assertSame(300, Varint::decode("\xAC\x02"));
27
28 // 16384 = 0x80 0x80 0x01
29 $this->assertSame(16384, Varint::decode("\x80\x80\x01"));
30 }
31
32 public function test_decode_with_offset(): void
33 {
34 $data = "\x00\x01\x7F\x80\x01";
35 $offset = 0;
36
37 $this->assertSame(0, Varint::decode($data, $offset));
38 $this->assertSame(1, $offset);
39
40 $this->assertSame(1, Varint::decode($data, $offset));
41 $this->assertSame(2, $offset);
42
43 $this->assertSame(127, Varint::decode($data, $offset));
44 $this->assertSame(3, $offset);
45
46 $this->assertSame(128, Varint::decode($data, $offset));
47 $this->assertSame(5, $offset);
48 }
49
50 public function test_decode_first_returns_value_and_remainder(): void
51 {
52 [$value, $remainder] = Varint::decodeFirst("\x7F\x01\x02\x03");
53
54 $this->assertSame(127, $value);
55 $this->assertSame("\x01\x02\x03", $remainder);
56 }
57
58 public function test_decode_throws_on_unexpected_end(): void
59 {
60 $this->expectException(RuntimeException::class);
61 $this->expectExceptionMessage('Unexpected end of varint data');
62
63 Varint::decode("\x80");
64 }
65
66 public function test_decode_throws_on_too_long_varint(): void
67 {
68 $this->expectException(RuntimeException::class);
69 $this->expectExceptionMessage('Varint too long (max 64 bits)');
70
71 // Create a varint that would be longer than 64 bits (10 bytes with continuation bits)
72 $tooLong = str_repeat("\xFF", 10);
73 Varint::decode($tooLong);
74 }
75}