summaryrefslogtreecommitdiffstats
path: root/tests/Inc/IpUtilTest.php
blob: 8c65a0c34d60afc2a4d8a8d155832b0d86cdd7b3 (plain) (blame)
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
<?php

use PHPUnit\Framework\TestCase;

class IpUtilTest extends TestCase
{
	public function testParseCidrWithSlashNotation(): void
	{
		$res = IpUtil::parseCidr('192.168.1/24');
		$this->assertNotNull($res);
		$this->assertSame(ip2long('192.168.1.0'), $res['start']);
		$this->assertSame(ip2long('192.168.1.255'), $res['end']);
	}

	public function testParseCidrSingleIp(): void
	{
		$res = IpUtil::parseCidr('10.0.0.1');
		$this->assertNotNull($res);
		$this->assertSame(ip2long('10.0.0.1'), $res['start']);
		$this->assertSame(ip2long('10.0.0.1'), $res['end']);
	}

	public function testParseCidrInvalid(): void
	{
		$this->assertNull(IpUtil::parseCidr('1.2.3.4/33'));
		$this->assertNull(IpUtil::parseCidr('not-an-ip'));
	}

	public function testIsValidSubnetRange(): void
	{
		$start = ip2long('192.168.0.0');
		$end = ip2long('192.168.0.255');
		$this->assertTrue(IpUtil::isValidSubnetRange($start, $end));

		$start = ip2long('192.168.0.1');
		$end = ip2long('192.168.0.254');
		$this->assertFalse(IpUtil::isValidSubnetRange($start, $end));

		// single IP should be considered a valid /32 range
		$ip = ip2long('10.0.0.1');
		$this->assertTrue(IpUtil::isValidSubnetRange($ip, $ip));
	}

	public function testRangeToCidrValid(): void
	{
		$start = ip2long('192.168.2.0');
		$end = ip2long('192.168.2.255');
		$this->assertSame('192.168.2.0/24', IpUtil::rangeToCidr($start, $end));
	}

	public function testRangeToCidrNotSubnet(): void
	{
		$start = ip2long('192.168.5.1');
		$end = ip2long('192.168.5.254');
		$this->assertSame(
			'NOT SUBNET: 192.168.5.1-192.168.5.254',
			IpUtil::rangeToCidr($start, $end)
		);
	}
}