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

65 lines
1.9 KiB
PHP
Raw Normal View History

2016-07-30 18:45:48 +03:00
<?php
2017-10-12 11:13:20 +03:00
declare(strict_types=1);
namespace ShlinkioTest\Shlink\Common\IpGeolocation;
2016-07-30 18:45:48 +03:00
use GuzzleHttp\Client;
use GuzzleHttp\Exception\TransferException;
use GuzzleHttp\Psr7\Response;
2017-03-24 22:34:18 +03:00
use PHPUnit\Framework\TestCase;
2016-07-30 18:45:48 +03:00
use Prophecy\Prophecy\ObjectProphecy;
2019-02-16 12:53:45 +03:00
use Shlinkio\Shlink\Common\Exception\WrongIpException;
use Shlinkio\Shlink\Common\IpGeolocation\IpApiLocationResolver;
use function json_encode;
2016-07-30 18:45:48 +03:00
class IpApiLocationResolverTest extends TestCase
2016-07-30 18:45:48 +03:00
{
/** @var IpApiLocationResolver */
private $ipResolver;
/** @var ObjectProphecy */
private $client;
2016-07-30 18:45:48 +03:00
2019-02-16 12:53:45 +03:00
public function setUp(): void
2016-07-30 18:45:48 +03:00
{
$this->client = $this->prophesize(Client::class);
$this->ipResolver = new IpApiLocationResolver($this->client->reveal());
2016-07-30 18:45:48 +03:00
}
/**
* @test
*/
public function correctIpReturnsDecodedInfo()
{
$actual = [
'countryCode' => 'bar',
'lat' => 5,
'lon' => 10,
];
2016-07-30 18:45:48 +03:00
$expected = [
'country_code' => 'bar',
'country_name' => '',
'region_name' => '',
'city' => '',
'latitude' => 5,
'longitude' => 10,
'time_zone' => '',
2016-07-30 18:45:48 +03:00
];
$response = new Response();
$response->getBody()->write(json_encode($actual));
2016-07-30 18:45:48 +03:00
$response->getBody()->rewind();
$this->client->get('http://ip-api.com/json/1.2.3.4')->willReturn($response)
2018-11-11 15:18:21 +03:00
->shouldBeCalledOnce();
2016-07-30 18:45:48 +03:00
$this->assertEquals($expected, $this->ipResolver->resolveIpLocation('1.2.3.4'));
}
2019-02-16 12:53:45 +03:00
/** @test */
2016-07-30 18:45:48 +03:00
public function guzzleExceptionThrowsShlinkException()
{
$this->client->get('http://ip-api.com/json/1.2.3.4')->willThrow(new TransferException())
2018-11-11 15:18:21 +03:00
->shouldBeCalledOnce();
2019-02-16 12:53:45 +03:00
$this->expectException(WrongIpException::class);
2016-07-30 18:45:48 +03:00
$this->ipResolver->resolveIpLocation('1.2.3.4');
}
}