1
|
|
|
<?php |
2
|
|
|
declare(strict_types=1); |
3
|
|
|
|
4
|
|
|
namespace ShlinkioTest\Shlink\IpGeolocation\Resolver; |
5
|
|
|
|
6
|
|
|
use GuzzleHttp\Client; |
7
|
|
|
use GuzzleHttp\Exception\TransferException; |
8
|
|
|
use GuzzleHttp\Psr7\Response; |
9
|
|
|
use PHPUnit\Framework\TestCase; |
10
|
|
|
use Prophecy\Prophecy\ObjectProphecy; |
11
|
|
|
use Shlinkio\Shlink\Common\Exception\WrongIpException; |
12
|
|
|
use Shlinkio\Shlink\IpGeolocation\Model\Location; |
13
|
|
|
use Shlinkio\Shlink\IpGeolocation\Resolver\IpApiLocationResolver; |
14
|
|
|
|
15
|
|
|
use function json_encode; |
16
|
|
|
|
17
|
|
|
class IpApiLocationResolverTest extends TestCase |
18
|
|
|
{ |
19
|
|
|
/** @var IpApiLocationResolver */ |
20
|
|
|
private $ipResolver; |
21
|
|
|
/** @var ObjectProphecy */ |
22
|
|
|
private $client; |
23
|
|
|
|
24
|
|
|
public function setUp(): void |
25
|
|
|
{ |
26
|
|
|
$this->client = $this->prophesize(Client::class); |
27
|
|
|
$this->ipResolver = new IpApiLocationResolver($this->client->reveal()); |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
/** @test */ |
31
|
|
|
public function correctIpReturnsDecodedInfo(): void |
32
|
|
|
{ |
33
|
|
|
$actual = [ |
34
|
|
|
'countryCode' => 'bar', |
35
|
|
|
'lat' => 5, |
36
|
|
|
'lon' => 10, |
37
|
|
|
]; |
38
|
|
|
$expected = new Location('bar', '', '', '', 5, 10, ''); |
39
|
|
|
$response = new Response(); |
40
|
|
|
$response->getBody()->write(json_encode($actual)); |
41
|
|
|
$response->getBody()->rewind(); |
42
|
|
|
|
43
|
|
|
$this->client->get('http://ip-api.com/json/1.2.3.4')->willReturn($response) |
44
|
|
|
->shouldBeCalledOnce(); |
45
|
|
|
$this->assertEquals($expected, $this->ipResolver->resolveIpLocation('1.2.3.4')); |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
/** @test */ |
49
|
|
|
public function guzzleExceptionThrowsShlinkException(): void |
50
|
|
|
{ |
51
|
|
|
$this->client->get('http://ip-api.com/json/1.2.3.4')->willThrow(new TransferException()) |
52
|
|
|
->shouldBeCalledOnce(); |
53
|
|
|
$this->expectException(WrongIpException::class); |
54
|
|
|
$this->ipResolver->resolveIpLocation('1.2.3.4'); |
55
|
|
|
} |
56
|
|
|
} |
57
|
|
|
|