summaryrefslogtreecommitdiff
path: root/tests/ConstantTest.php
blob: 78d1be3d123b4a1a9da3a6e4583115747956ff71 (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;

#[CoversClass(Constant::class)]
final class ConstantTest extends TestCase
{
    public function testConstantCanBeInitialized(): void
    {
        $field = new Constant('machine_id', 10);
        $this->assertSame('machine_id', $field->name);
        $this->assertSame(10, $field->bits);
        $this->assertSame(0, $field->value);
    }

    public function testMaxValueShouldBeCalculatedCorrectly(): void
    {
        $field = new Constant('machine_id', 10);
        $maxValue = (1 << 10) - 1;
        $this->assertSame($maxValue, $field->maxValue());
    }

    public function testInitialValueCanBeSet(): void
    {
        $field = new Constant('machine_id', 10, 2);
        $this->assertSame(2, $field->value);
    }

    public function testInitialValueMustBePositive(): void
    {
        $this->expectException(\InvalidArgumentException::class);
        $this->expectExceptionMessage('Field value must be non-negative.');
        new Constant('machine_id', 10, -1);
    }

    public function testInitialValueMustNotExceedMaxValue(): void
    {
        $this->expectException(\InvalidArgumentException::class);
        $this->expectExceptionMessage('Field value 1024 exceeds maximum 1023 for 10 bits.');
        new Constant('machine_id', 10, 1024);
    }

    public function testConstantHasMakeFactoryMethod(): void
    {
        $field = Constant::make('machine_id', 10, 5);
        $this->assertSame('machine_id', $field->name);
        $this->assertSame(10, $field->bits);
        $this->assertSame(5, $field->value);
    }

    public function testBitsMustBeAtLeastOne(): void
    {
        $this->expectException(\InvalidArgumentException::class);
        $this->expectExceptionMessage('Bits must be between 1 and 63.');
        new Constant('machine_id', 0);
    }

    public function testBitsMustNotExceed63(): void
    {
        $this->expectException(\InvalidArgumentException::class);
        $this->expectExceptionMessage('Bits must be between 1 and 63.');
        new Constant('machine_id', 64);
    }
}