summaryrefslogtreecommitdiff
path: root/tests/StructureTest.php
blob: 80d94fe8f2d4a2643acdd5c547ea182d7302b176 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
<?php

declare(strict_types=1);

namespace Zhineng\Snowflake\Tests;

use PHPUnit\Framework\Attributes\CoversClass;
use PHPUnit\Framework\TestCase;
use Zhineng\Snowflake\Constant;
use Zhineng\Snowflake\Sequence;
use Zhineng\Snowflake\Structure;

#[CoversClass(Structure::class)]
final class StructureTest extends TestCase
{
    public function testAddFieldAndRetrieveComponents(): void
    {
        $struct = new Structure;
        $struct->add(Constant::make('machine_id', 10));
        $this->assertCount(1, $struct->components());
    }

    public function testAddMultipleFields(): void
    {
        $struct = new Structure;
        $struct->add(Constant::make('machine_id', 5));
        $struct->add(Constant::make('datacenter_id', 5));
        $this->assertCount(2, $struct->components());
    }

    public function testOffsetsAreCalculatedCorrectly(): void
    {
        $struct = new Structure;
        $struct->add($machineId = Constant::make('machine_id', 5));
        $struct->add($dataCenterId = Constant::make('datacenter_id', 5));
        $this->assertSame(0, $machineId->offset());
        $this->assertSame(5, $dataCenterId->offset());
    }

    public function testSizeResolution(): void
    {
        $struct = new Structure;
        $struct->add(Constant::make('machine_id', 5));
        $struct->add(Constant::make('datacenter_id', 5));
        $this->assertSame(10, $struct->size());
    }

    public function testAtMostOneSequenceIsAllowed(): void
    {
        $struct = new Structure;
        $struct->add(Sequence::make('seq1', 12));

        $this->expectException(\LogicException::class);
        $this->expectExceptionMessage('Only one sequence field is allowed in a structure.');

        $struct->add(Sequence::make('seq2', 12));
    }

    public function testTotalSizeCannotExceed63Bits(): void
    {
        $struct = new Structure;
        $struct->add(Constant::make('field1', 32));
        $struct->add(Constant::make('field2', 31));

        $this->expectException(\OverflowException::class);
        $this->expectExceptionMessage('Total structure size cannot exceed 63 bits.');

        $struct->add(Constant::make('field3', 1));
    }
}