File: PcntlTimeoutTest.php

package info (click to toggle)
php-malkusch-lock 2.3.0%2Bds-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 452 kB
  • sloc: php: 2,124; makefile: 19
file content (75 lines) | stat: -rw-r--r-- 1,689 bytes parent folder | download | duplicates (2)
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
71
72
73
74
75
<?php

declare(strict_types=1);

namespace malkusch\lock\Tests\util;

use malkusch\lock\exception\DeadlineException;
use malkusch\lock\exception\LockAcquireException;
use malkusch\lock\util\PcntlTimeout;
use PHPUnit\Framework\TestCase;

/**
 * @requires pcntl
 */
class PcntlTimeoutTest extends TestCase
{
    /**
     * A long running system call should be interrupted.
     */
    public function testShouldTimeout(): void
    {
        $this->expectException(DeadlineException::class);

        $timeout = new PcntlTimeout(1);

        $timeout->timeBoxed(static function () {
            sleep(2);
        });
    }

    /**
     * A short running system call should complete its execution.
     */
    public function testShouldNotTimeout(): void
    {
        $timeout = new PcntlTimeout(1);

        $result = $timeout->timeBoxed(static function () {
            return 42;
        });

        self::assertSame(42, $result);
    }

    /**
     * When a previous scheduled alarm exists, it should fail.
     */
    public function testShouldFailOnExistingAlarm(): void
    {
        $this->expectException(LockAcquireException::class);

        try {
            pcntl_alarm(1);
            $timeout = new PcntlTimeout(1);

            $timeout->timeBoxed(static function () {
                sleep(1);
            });
        } finally {
            pcntl_alarm(0);
        }
    }

    /**
     * After not timing out, there should be no alarm scheduled.
     */
    public function testShouldResetAlarmWhenNotTimeout(): void
    {
        $timeout = new PcntlTimeout(3);

        $timeout->timeBoxed(static function () {});

        self::assertSame(0, pcntl_alarm(0));
    }
}