Completed
Pull Request — master (#454)
by Alejandro
14:47
created

exceptionIsThrownIfReaderThrowsException()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 7
dl 0
loc 12
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 2
1
<?php
2
declare(strict_types=1);
3
4
namespace ShlinkioTest\Shlink\IpGeolocation\Resolver;
5
6
use GeoIp2\Database\Reader;
7
use GeoIp2\Exception\AddressNotFoundException;
8
use GeoIp2\Model\City;
9
use MaxMind\Db\Reader\InvalidDatabaseException;
10
use PHPUnit\Framework\TestCase;
11
use Prophecy\Prophecy\ObjectProphecy;
12
use Shlinkio\Shlink\Common\Exception\WrongIpException;
13
use Shlinkio\Shlink\IpGeolocation\Model\Location;
14
use Shlinkio\Shlink\IpGeolocation\Resolver\GeoLite2LocationResolver;
15
16
class GeoLite2LocationResolverTest extends TestCase
17
{
18
    /** @var GeoLite2LocationResolver */
19
    private $resolver;
20
    /** @var ObjectProphecy */
21
    private $reader;
22
23
    public function setUp(): void
24
    {
25
        $this->reader = $this->prophesize(Reader::class);
26
        $this->resolver = new GeoLite2LocationResolver($this->reader->reveal());
27
    }
28
29
    /**
30
     * @test
31
     * @dataProvider provideReaderExceptions
32
     */
33
    public function exceptionIsThrownIfReaderThrowsException(string $e, string $message): void
34
    {
35
        $ipAddress = '1.2.3.4';
36
37
        $cityMethod = $this->reader->city($ipAddress)->willThrow($e);
38
39
        $this->expectException(WrongIpException::class);
40
        $this->expectExceptionMessage($message);
41
        $this->expectExceptionCode(0);
42
        $cityMethod->shouldBeCalledOnce();
43
44
        $this->resolver->resolveIpLocation($ipAddress);
45
    }
46
47
    public function provideReaderExceptions(): iterable
48
    {
49
        yield 'invalid IP address' => [AddressNotFoundException::class, 'Provided IP "1.2.3.4" is invalid'];
50
        yield 'invalid geolite DB' => [InvalidDatabaseException::class, 'Provided GeoLite2 db file is invalid'];
51
    }
52
53
    /** @test */
54
    public function resolvedCityIsProperlyMapped(): void
55
    {
56
        $ipAddress = '1.2.3.4';
57
        $city = new City([]);
58
59
        $cityMethod = $this->reader->city($ipAddress)->willReturn($city);
60
61
        $result = $this->resolver->resolveIpLocation($ipAddress);
62
63
        $this->assertEquals(Location::emptyInstance(), $result);
64
        $cityMethod->shouldHaveBeenCalledOnce();
65
    }
66
}
67