Files
pcm-geocode-bundle/tests/Service/GeocoderTest.php
2024-09-26 10:19:07 +01:00

97 lines
2.6 KiB
PHP

<?php
declare(strict_types=1);
namespace Pcm\GeocodeBundle\Tests;
use Pcm\GeocodeBundle\Interface\Entity\GeocodeInterface;
use Pcm\GeocodeBundle\Trait\Entity\GeocodeTrait;
use Pcm\GeocodeBundle\Exception\ApiErrorException;
use Pcm\GeocodeBundle\Exception\NoResultsFoundException;
use Pcm\GeocodeBundle\Model\GeoCoordinates;
use Pcm\GeocodeBundle\Service\Geocoder;
use Pcm\GeocodeBundle\Tests\AppKernel;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
/**
* We sleep 1 second after API calls to prevent breaking the API T&Cs.
*/
final class GeocoderTest extends KernelTestCase
{
// Buckingham Palace
private const string POSTCODE = 'SW1A 1AA';
private Geocoder $geocoder;
protected function setUp(): void
{
$kernel = new AppKernel('test', false);
$kernel->boot();
$this->geocoder = $kernel->getContainer()->get('pcm_geocode.geocoder');
}
public function testGeocodeThrowsOnEmptyInput(): void
{
sleep(1);
$this->expectException(ApiErrorException::class);
$entity = $this->createEntity('');
$this->expectExceptionMessageMatches("/Nothing to search for.$/");
$this->geocoder->geocode($entity);
}
public function testGeocodeThrowsOnInvalidPostcode(): void
{
sleep(1);
$this->expectException(NoResultsFoundException::class);
$this->expectExceptionMessageMatches("/No results found.$/");
$entity = $this->createEntity('Invalid Postcode');
$this->geocoder->geocode($entity);
}
public function testGeocodeReturnsGeoCoordinates(): GeoCoordinates
{
sleep(1);
$entity = $this->createEntity(self::POSTCODE);
$geoCoords = $this->geocoder->geocode($entity);
$this->assertNotNull($geoCoords);
return $geoCoords;
}
/**
* @depends testGeocodeReturnsGeoCoordinates
*/
public function testCoordinatesAreSet(GeoCoordinates $geoCoordinates): void
{
$this->assertIsFloat($geoCoordinates->latitude);
$this->assertIsFloat($geoCoordinates->longitude);
}
private function getGeocodableEntity(): GeocodeInterface
{
return new class implements GeocodeInterface
{
use GeocodeTrait;
};
}
private function createEntity(string $data): GeocodeInterface
{
$entity = new class implements GeocodeInterface {
use GeocodeTrait;
public string $data;
public function getGeocodeData(): string
{
return $this->data;
}
};
$entity->data = $data;
return $entity;
}
}