shlink/module/Common/test/IpGeolocation/GeoLite2LocationResolverTest.php

69 lines
2 KiB
PHP
Raw Normal View History

2018-11-11 15:18:21 +03:00
<?php
declare(strict_types=1);
namespace ShlinkioTest\Shlink\Common\IpGeolocation;
use GeoIp2\Database\Reader;
use GeoIp2\Exception\AddressNotFoundException;
use GeoIp2\Model\City;
use MaxMind\Db\Reader\InvalidDatabaseException;
use PHPUnit\Framework\TestCase;
use Prophecy\Prophecy\ObjectProphecy;
use Shlinkio\Shlink\Common\Exception\WrongIpException;
use Shlinkio\Shlink\Common\IpGeolocation\GeoLite2LocationResolver;
use Shlinkio\Shlink\Common\IpGeolocation\Model\Location;
2018-11-11 15:18:21 +03:00
class GeoLite2LocationResolverTest extends TestCase
{
/** @var GeoLite2LocationResolver */
2018-11-11 15:18:21 +03:00
private $resolver;
/** @var ObjectProphecy */
2018-11-11 15:18:21 +03:00
private $reader;
2019-02-16 12:53:45 +03:00
public function setUp(): void
2018-11-11 15:18:21 +03:00
{
$this->reader = $this->prophesize(Reader::class);
$this->resolver = new GeoLite2LocationResolver($this->reader->reveal());
}
/**
* @test
* @dataProvider provideReaderExceptions
*/
public function exceptionIsThrownIfReaderThrowsException(string $e, string $message)
{
$ipAddress = '1.2.3.4';
$cityMethod = $this->reader->city($ipAddress)->willThrow($e);
$this->expectException(WrongIpException::class);
$this->expectExceptionMessage($message);
2018-11-17 20:40:47 +03:00
$this->expectExceptionCode(0);
2018-11-11 15:18:21 +03:00
$cityMethod->shouldBeCalledOnce();
$this->resolver->resolveIpLocation($ipAddress);
}
public function provideReaderExceptions(): array
{
return [
[AddressNotFoundException::class, 'Provided IP "1.2.3.4" is invalid'],
[InvalidDatabaseException::class, 'Provided GeoLite2 db file is invalid'],
];
}
/** @test */
public function resolvedCityIsProperlyMapped(): void
2018-11-11 15:18:21 +03:00
{
$ipAddress = '1.2.3.4';
$city = new City([]);
$cityMethod = $this->reader->city($ipAddress)->willReturn($city);
$result = $this->resolver->resolveIpLocation($ipAddress);
$this->assertEquals(Location::emptyInstance(), $result);
2018-11-11 15:18:21 +03:00
$cityMethod->shouldHaveBeenCalledOnce();
}
}