Reduced amount of dead lines in tests

This commit is contained in:
Alejandro Celaya 2019-02-17 20:28:34 +01:00
parent 1bcd03b150
commit 687a1cc9c7
100 changed files with 481 additions and 938 deletions

View File

@ -27,9 +27,7 @@ class DisableKeyCommandTest extends TestCase
$this->commandTester = new CommandTester($command); $this->commandTester = new CommandTester($command);
} }
/** /** @test */
* @test
*/
public function providedApiKeyIsDisabled() public function providedApiKeyIsDisabled()
{ {
$apiKey = 'abcd1234'; $apiKey = 'abcd1234';
@ -44,9 +42,7 @@ class DisableKeyCommandTest extends TestCase
$this->assertStringContainsString('API key "abcd1234" properly disabled', $output); $this->assertStringContainsString('API key "abcd1234" properly disabled', $output);
} }
/** /** @test */
* @test
*/
public function errorIsReturnedIfServiceThrowsException() public function errorIsReturnedIfServiceThrowsException()
{ {
$apiKey = 'abcd1234'; $apiKey = 'abcd1234';

View File

@ -29,9 +29,7 @@ class GenerateKeyCommandTest extends TestCase
$this->commandTester = new CommandTester($command); $this->commandTester = new CommandTester($command);
} }
/** /** @test */
* @test
*/
public function noExpirationDateIsDefinedIfNotProvided() public function noExpirationDateIsDefinedIfNotProvided()
{ {
$create = $this->apiKeyService->create(null)->willReturn(new ApiKey()); $create = $this->apiKeyService->create(null)->willReturn(new ApiKey());
@ -45,9 +43,7 @@ class GenerateKeyCommandTest extends TestCase
$create->shouldHaveBeenCalledOnce(); $create->shouldHaveBeenCalledOnce();
} }
/** /** @test */
* @test
*/
public function expirationDateIsDefinedIfProvided() public function expirationDateIsDefinedIfProvided()
{ {
$this->apiKeyService->create(Argument::type(Chronos::class))->shouldBeCalledOnce() $this->apiKeyService->create(Argument::type(Chronos::class))->shouldBeCalledOnce()

View File

@ -25,9 +25,7 @@ class GenerateCharsetCommandTest extends TestCase
$this->commandTester = new CommandTester($command); $this->commandTester = new CommandTester($command);
} }
/** /** @test */
* @test
*/
public function charactersAreGeneratedFromDefault() public function charactersAreGeneratedFromDefault()
{ {
$prefix = 'Character set: '; $prefix = 'Character set: ';

View File

@ -39,9 +39,7 @@ class GeneratePreviewCommandTest extends TestCase
$this->commandTester = new CommandTester($command); $this->commandTester = new CommandTester($command);
} }
/** /** @test */
* @test
*/
public function previewsForEveryUrlAreGenerated() public function previewsForEveryUrlAreGenerated()
{ {
$paginator = $this->createPaginator([ $paginator = $this->createPaginator([
@ -69,9 +67,7 @@ class GeneratePreviewCommandTest extends TestCase
$generatePreview3->shouldHaveBeenCalledOnce(); $generatePreview3->shouldHaveBeenCalledOnce();
} }
/** /** @test */
* @test
*/
public function exceptionWillOutputError() public function exceptionWillOutputError()
{ {
$items = [ $items = [

View File

@ -34,9 +34,7 @@ class GenerateShortUrlCommandTest extends TestCase
$this->commandTester = new CommandTester($command); $this->commandTester = new CommandTester($command);
} }
/** /** @test */
* @test
*/
public function properShortCodeIsCreatedIfLongUrlIsCorrect() public function properShortCodeIsCreatedIfLongUrlIsCorrect()
{ {
$urlToShortCode = $this->urlShortener->urlToShortCode(Argument::cetera())->willReturn( $urlToShortCode = $this->urlShortener->urlToShortCode(Argument::cetera())->willReturn(
@ -54,9 +52,7 @@ class GenerateShortUrlCommandTest extends TestCase
$urlToShortCode->shouldHaveBeenCalledOnce(); $urlToShortCode->shouldHaveBeenCalledOnce();
} }
/** /** @test */
* @test
*/
public function exceptionWhileParsingLongUrlOutputsError() public function exceptionWhileParsingLongUrlOutputsError()
{ {
$this->urlShortener->urlToShortCode(Argument::cetera())->willThrow(new InvalidUrlException()) $this->urlShortener->urlToShortCode(Argument::cetera())->willThrow(new InvalidUrlException())
@ -73,9 +69,7 @@ class GenerateShortUrlCommandTest extends TestCase
); );
} }
/** /** @test */
* @test
*/
public function properlyProcessesProvidedTags() public function properlyProcessesProvidedTags()
{ {
$urlToShortCode = $this->urlShortener->urlToShortCode( $urlToShortCode = $this->urlShortener->urlToShortCode(

View File

@ -37,9 +37,7 @@ class GetVisitsCommandTest extends TestCase
$this->commandTester = new CommandTester($command); $this->commandTester = new CommandTester($command);
} }
/** /** @test */
* @test
*/
public function noDateFlagsTriesToListWithoutDateRange() public function noDateFlagsTriesToListWithoutDateRange()
{ {
$shortCode = 'abc123'; $shortCode = 'abc123';
@ -53,9 +51,7 @@ class GetVisitsCommandTest extends TestCase
]); ]);
} }
/** /** @test */
* @test
*/
public function providingDateFlagsTheListGetsFiltered() public function providingDateFlagsTheListGetsFiltered()
{ {
$shortCode = 'abc123'; $shortCode = 'abc123';

View File

@ -30,9 +30,7 @@ class ListShortUrlsCommandTest extends TestCase
$this->commandTester = new CommandTester($command); $this->commandTester = new CommandTester($command);
} }
/** /** @test */
* @test
*/
public function noInputCallsListJustOnce() public function noInputCallsListJustOnce()
{ {
$this->shortUrlService->listShortUrls(1, null, [], null)->willReturn(new Paginator(new ArrayAdapter())) $this->shortUrlService->listShortUrls(1, null, [], null)->willReturn(new Paginator(new ArrayAdapter()))
@ -42,9 +40,7 @@ class ListShortUrlsCommandTest extends TestCase
$this->commandTester->execute(['command' => 'shortcode:list']); $this->commandTester->execute(['command' => 'shortcode:list']);
} }
/** /** @test */
* @test
*/
public function loadingMorePagesCallsListMoreTimes() public function loadingMorePagesCallsListMoreTimes()
{ {
// The paginator will return more than one page // The paginator will return more than one page
@ -66,9 +62,7 @@ class ListShortUrlsCommandTest extends TestCase
$this->assertStringContainsString('Continue with page 4?', $output); $this->assertStringContainsString('Continue with page 4?', $output);
} }
/** /** @test */
* @test
*/
public function havingMorePagesButAnsweringNoCallsListJustOnce() public function havingMorePagesButAnsweringNoCallsListJustOnce()
{ {
// The paginator will return more than one page // The paginator will return more than one page
@ -93,9 +87,7 @@ class ListShortUrlsCommandTest extends TestCase
$this->assertStringNotContainsString('Continue with page 3?', $output); $this->assertStringNotContainsString('Continue with page 3?', $output);
} }
/** /** @test */
* @test
*/
public function passingPageWillMakeListStartOnThatPage() public function passingPageWillMakeListStartOnThatPage()
{ {
$page = 5; $page = 5;
@ -109,9 +101,7 @@ class ListShortUrlsCommandTest extends TestCase
]); ]);
} }
/** /** @test */
* @test
*/
public function ifTagsFlagIsProvidedTagsColumnIsIncluded() public function ifTagsFlagIsProvidedTagsColumnIsIncluded()
{ {
$this->shortUrlService->listShortUrls(1, null, [], null)->willReturn(new Paginator(new ArrayAdapter())) $this->shortUrlService->listShortUrls(1, null, [], null)->willReturn(new Paginator(new ArrayAdapter()))

View File

@ -31,9 +31,7 @@ class ResolveUrlCommandTest extends TestCase
$this->commandTester = new CommandTester($command); $this->commandTester = new CommandTester($command);
} }
/** /** @test */
* @test
*/
public function correctShortCodeResolvesUrl() public function correctShortCodeResolvesUrl()
{ {
$shortCode = 'abc123'; $shortCode = 'abc123';
@ -50,9 +48,7 @@ class ResolveUrlCommandTest extends TestCase
$this->assertEquals('Long URL: ' . $expectedUrl . PHP_EOL, $output); $this->assertEquals('Long URL: ' . $expectedUrl . PHP_EOL, $output);
} }
/** /** @test */
* @test
*/
public function incorrectShortCodeOutputsErrorMessage() public function incorrectShortCodeOutputsErrorMessage()
{ {
$shortCode = 'abc123'; $shortCode = 'abc123';
@ -67,9 +63,7 @@ class ResolveUrlCommandTest extends TestCase
$this->assertStringContainsString('Provided short code "' . $shortCode . '" could not be found.', $output); $this->assertStringContainsString('Provided short code "' . $shortCode . '" could not be found.', $output);
} }
/** /** @test */
* @test
*/
public function wrongShortCodeFormatOutputsErrorMessage() public function wrongShortCodeFormatOutputsErrorMessage()
{ {
$shortCode = 'abc123'; $shortCode = 'abc123';

View File

@ -30,9 +30,7 @@ class CreateTagCommandTest extends TestCase
$this->commandTester = new CommandTester($command); $this->commandTester = new CommandTester($command);
} }
/** /** @test */
* @test
*/
public function errorIsReturnedWhenNoTagsAreProvided() public function errorIsReturnedWhenNoTagsAreProvided()
{ {
$this->commandTester->execute([]); $this->commandTester->execute([]);
@ -41,9 +39,7 @@ class CreateTagCommandTest extends TestCase
$this->assertStringContainsString('You have to provide at least one tag name', $output); $this->assertStringContainsString('You have to provide at least one tag name', $output);
} }
/** /** @test */
* @test
*/
public function serviceIsInvokedOnSuccess() public function serviceIsInvokedOnSuccess()
{ {
$tagNames = ['foo', 'bar']; $tagNames = ['foo', 'bar'];

View File

@ -31,9 +31,7 @@ class DeleteTagsCommandTest extends TestCase
$this->commandTester = new CommandTester($command); $this->commandTester = new CommandTester($command);
} }
/** /** @test */
* @test
*/
public function errorIsReturnedWhenNoTagsAreProvided() public function errorIsReturnedWhenNoTagsAreProvided()
{ {
$this->commandTester->execute([]); $this->commandTester->execute([]);
@ -42,9 +40,7 @@ class DeleteTagsCommandTest extends TestCase
$this->assertStringContainsString('You have to provide at least one tag name', $output); $this->assertStringContainsString('You have to provide at least one tag name', $output);
} }
/** /** @test */
* @test
*/
public function serviceIsInvokedOnSuccess() public function serviceIsInvokedOnSuccess()
{ {
$tagNames = ['foo', 'bar']; $tagNames = ['foo', 'bar'];

View File

@ -32,9 +32,7 @@ class ListTagsCommandTest extends TestCase
$this->commandTester = new CommandTester($command); $this->commandTester = new CommandTester($command);
} }
/** /** @test */
* @test
*/
public function noTagsPrintsEmptyMessage() public function noTagsPrintsEmptyMessage()
{ {
/** @var MethodProphecy $listTags */ /** @var MethodProphecy $listTags */
@ -47,9 +45,7 @@ class ListTagsCommandTest extends TestCase
$listTags->shouldHaveBeenCalled(); $listTags->shouldHaveBeenCalled();
} }
/** /** @test */
* @test
*/
public function listOfTagsIsPrinted() public function listOfTagsIsPrinted()
{ {
/** @var MethodProphecy $listTags */ /** @var MethodProphecy $listTags */

View File

@ -33,9 +33,7 @@ class RenameTagCommandTest extends TestCase
$this->commandTester = new CommandTester($command); $this->commandTester = new CommandTester($command);
} }
/** /** @test */
* @test
*/
public function errorIsPrintedIfExceptionIsThrown() public function errorIsPrintedIfExceptionIsThrown()
{ {
$oldName = 'foo'; $oldName = 'foo';
@ -53,9 +51,7 @@ class RenameTagCommandTest extends TestCase
$renameTag->shouldHaveBeenCalled(); $renameTag->shouldHaveBeenCalled();
} }
/** /** @test */
* @test
*/
public function successIsPrintedIfNoErrorOccurs() public function successIsPrintedIfNoErrorOccurs()
{ {
$oldName = 'foo'; $oldName = 'foo';

View File

@ -155,9 +155,7 @@ class ProcessVisitsCommandTest extends TestCase
$resolveIpLocation->shouldHaveBeenCalledOnce(); $resolveIpLocation->shouldHaveBeenCalledOnce();
} }
/** /** @test */
* @test
*/
public function noActionIsPerformedIfLockIsAcquired() public function noActionIsPerformedIfLockIsAcquired()
{ {
$this->lock->acquire()->willReturn(false); $this->lock->acquire()->willReturn(false);

View File

@ -30,9 +30,7 @@ class UpdateDbCommandTest extends TestCase
$this->commandTester = new CommandTester($command); $this->commandTester = new CommandTester($command);
} }
/** /** @test */
* @test
*/
public function successMessageIsPrintedIfEverythingWorks() public function successMessageIsPrintedIfEverythingWorks()
{ {
$download = $this->dbUpdater->downloadFreshCopy(Argument::type('callable'))->will(function () { $download = $this->dbUpdater->downloadFreshCopy(Argument::type('callable'))->will(function () {
@ -45,9 +43,7 @@ class UpdateDbCommandTest extends TestCase
$download->shouldHaveBeenCalledOnce(); $download->shouldHaveBeenCalledOnce();
} }
/** /** @test */
* @test
*/
public function errorMessageIsPrintedIfAnExceptionIsThrown() public function errorMessageIsPrintedIfAnExceptionIsThrown()
{ {
$download = $this->dbUpdater->downloadFreshCopy(Argument::type('callable'))->willThrow(RuntimeException::class); $download = $this->dbUpdater->downloadFreshCopy(Argument::type('callable'))->willThrow(RuntimeException::class);

View File

@ -16,9 +16,7 @@ class ConfigProviderTest extends TestCase
$this->configProvider = new ConfigProvider(); $this->configProvider = new ConfigProvider();
} }
/** /** @test */
* @test
*/
public function confiIsProperlyReturned() public function confiIsProperlyReturned()
{ {
$config = ($this->configProvider)(); $config = ($this->configProvider)();

View File

@ -23,18 +23,14 @@ class ApplicationFactoryTest extends TestCase
$this->factory = new ApplicationFactory(); $this->factory = new ApplicationFactory();
} }
/** /** @test */
* @test
*/
public function serviceIsCreated() public function serviceIsCreated()
{ {
$instance = ($this->factory)($this->createServiceManager(), ''); $instance = ($this->factory)($this->createServiceManager(), '');
$this->assertInstanceOf(Application::class, $instance); $this->assertInstanceOf(Application::class, $instance);
} }
/** /** @test */
* @test
*/
public function allCommandsWhichAreServicesAreAdded() public function allCommandsWhichAreServicesAreAdded()
{ {
$sm = $this->createServiceManager([ $sm = $this->createServiceManager([

View File

@ -16,9 +16,7 @@ class ConfigProviderTest extends TestCase
$this->configProvider = new ConfigProvider(); $this->configProvider = new ConfigProvider();
} }
/** /** @test */
* @test
*/
public function configIsReturned() public function configIsReturned()
{ {
$config = $this->configProvider->__invoke(); $config = $this->configProvider->__invoke();

View File

@ -25,9 +25,7 @@ class ShlinkTableTest extends TestCase
$this->shlinkTable = new ShlinkTable($this->baseTable->reveal()); $this->shlinkTable = new ShlinkTable($this->baseTable->reveal());
} }
/** /** @test */
* @test
*/
public function renderMakesTableToBeRenderedWithProvidedInfo() public function renderMakesTableToBeRenderedWithProvidedInfo()
{ {
$headers = []; $headers = [];
@ -54,9 +52,7 @@ class ShlinkTableTest extends TestCase
$render->shouldHaveBeenCalledOnce(); $render->shouldHaveBeenCalledOnce();
} }
/** /** @test */
* @test
*/
public function newTableIsCreatedForFactoryMethod() public function newTableIsCreatedForFactoryMethod()
{ {
$instance = ShlinkTable::fromOutput($this->prophesize(OutputInterface::class)->reveal()); $instance = ShlinkTable::fromOutput($this->prophesize(OutputInterface::class)->reveal());

View File

@ -9,9 +9,7 @@ use Shlinkio\Shlink\Common\Exception\WrongIpException;
class WrongIpExceptionTest extends TestCase class WrongIpExceptionTest extends TestCase
{ {
/** /** @test */
* @test
*/
public function fromIpAddressProperlyCreatesExceptionWithoutPrev() public function fromIpAddressProperlyCreatesExceptionWithoutPrev()
{ {
$e = WrongIpException::fromIpAddress('1.2.3.4'); $e = WrongIpException::fromIpAddress('1.2.3.4');
@ -20,9 +18,7 @@ class WrongIpExceptionTest extends TestCase
$this->assertEquals(0, $e->getCode()); $this->assertEquals(0, $e->getCode());
$this->assertNull($e->getPrevious()); $this->assertNull($e->getPrevious());
} }
/** /** @test */
* @test
*/
public function fromIpAddressProperlyCreatesExceptionWithPrev() public function fromIpAddressProperlyCreatesExceptionWithPrev()
{ {
$prev = new Exception('Previous error'); $prev = new Exception('Previous error');

View File

@ -32,9 +32,7 @@ class CacheFactoryTest extends TestCase
putenv('APP_ENV'); putenv('APP_ENV');
} }
/** /** @test */
* @test
*/
public function productionReturnsApcAdapter() public function productionReturnsApcAdapter()
{ {
putenv('APP_ENV=pro'); putenv('APP_ENV=pro');
@ -42,9 +40,7 @@ class CacheFactoryTest extends TestCase
$this->assertInstanceOf(ApcuCache::class, $instance); $this->assertInstanceOf(ApcuCache::class, $instance);
} }
/** /** @test */
* @test
*/
public function developmentReturnsArrayAdapter() public function developmentReturnsArrayAdapter()
{ {
putenv('APP_ENV=dev'); putenv('APP_ENV=dev');
@ -52,9 +48,7 @@ class CacheFactoryTest extends TestCase
$this->assertInstanceOf(ArrayCache::class, $instance); $this->assertInstanceOf(ArrayCache::class, $instance);
} }
/** /** @test */
* @test
*/
public function adapterDefinedInConfigIgnoresEnvironment() public function adapterDefinedInConfigIgnoresEnvironment()
{ {
putenv('APP_ENV=pro'); putenv('APP_ENV=pro');
@ -62,9 +56,7 @@ class CacheFactoryTest extends TestCase
$this->assertInstanceOf(ArrayCache::class, $instance); $this->assertInstanceOf(ArrayCache::class, $instance);
} }
/** /** @test */
* @test
*/
public function invalidAdapterDefinedInConfigFallbacksToEnvironment() public function invalidAdapterDefinedInConfigFallbacksToEnvironment()
{ {
putenv('APP_ENV=pro'); putenv('APP_ENV=pro');
@ -72,9 +64,7 @@ class CacheFactoryTest extends TestCase
$this->assertInstanceOf(ApcuCache::class, $instance); $this->assertInstanceOf(ApcuCache::class, $instance);
} }
/** /** @test */
* @test
*/
public function filesystemCacheAdaptersReadDirOption() public function filesystemCacheAdaptersReadDirOption()
{ {
$dir = realpath(sys_get_temp_dir()); $dir = realpath(sys_get_temp_dir());
@ -84,9 +74,7 @@ class CacheFactoryTest extends TestCase
$this->assertEquals($dir, $instance->getDirectory()); $this->assertEquals($dir, $instance->getDirectory());
} }
/** /** @test */
* @test
*/
public function memcachedCacheAdaptersReadServersOption() public function memcachedCacheAdaptersReadServersOption()
{ {
$servers = [ $servers = [

View File

@ -20,30 +20,23 @@ class DottedAccessConfigAbstractFactoryTest extends TestCase
} }
/** /**
* @param string $serviceName
* @param bool $canCreate
*
* @test * @test
* @dataProvider provideDotNames * @dataProvider provideDotNames
*/ */
public function canCreateOnlyServicesWithDot(string $serviceName, bool $canCreate) public function canCreateOnlyServicesWithDot(string $serviceName, bool $canCreate): void
{ {
$this->assertEquals($canCreate, $this->factory->canCreate(new ServiceManager(), $serviceName)); $this->assertEquals($canCreate, $this->factory->canCreate(new ServiceManager(), $serviceName));
} }
public function provideDotNames(): array public function provideDotNames(): iterable
{ {
return [ yield 'with a valid service' => ['foo.bar', true];
['foo.bar', true], yield 'with another valid service' => ['config.something', true];
['config.something', true], yield 'with an invalid service' => ['config_something', false];
['config_something', false], yield 'with another invalid service' => ['foo', false];
['foo', false],
];
} }
/** /** @test */
* @test
*/
public function throwsExceptionWhenFirstPartOfTheServiceIsNotRegistered() public function throwsExceptionWhenFirstPartOfTheServiceIsNotRegistered()
{ {
$this->expectException(ServiceNotCreatedException::class); $this->expectException(ServiceNotCreatedException::class);
@ -54,9 +47,7 @@ class DottedAccessConfigAbstractFactoryTest extends TestCase
$this->factory->__invoke(new ServiceManager(), 'foo.bar'); $this->factory->__invoke(new ServiceManager(), 'foo.bar');
} }
/** /** @test */
* @test
*/
public function dottedNotationIsRecursivelyResolvedUntilLastValueIsFoundAndReturned() public function dottedNotationIsRecursivelyResolvedUntilLastValueIsFoundAndReturned()
{ {
$expected = 'this is the result'; $expected = 'this is the result';
@ -70,9 +61,7 @@ class DottedAccessConfigAbstractFactoryTest extends TestCase
$this->assertEquals($expected, $result); $this->assertEquals($expected, $result);
} }
/** /** @test */
* @test
*/
public function exceptionIsThrownIfAnyStepCannotBeResolved() public function exceptionIsThrownIfAnyStepCannotBeResolved()
{ {
$this->expectException(InvalidArgumentException::class); $this->expectException(InvalidArgumentException::class);

View File

@ -20,18 +20,14 @@ class EmptyResponseImplicitOptionsMiddlewareFactoryTest extends TestCase
$this->factory = new EmptyResponseImplicitOptionsMiddlewareFactory(); $this->factory = new EmptyResponseImplicitOptionsMiddlewareFactory();
} }
/** /** @test */
* @test
*/
public function serviceIsCreated() public function serviceIsCreated()
{ {
$instance = $this->factory->__invoke(new ServiceManager(), ''); $instance = $this->factory->__invoke(new ServiceManager(), '');
$this->assertInstanceOf(ImplicitOptionsMiddleware::class, $instance); $this->assertInstanceOf(ImplicitOptionsMiddleware::class, $instance);
} }
/** /** @test */
* @test
*/
public function responsePrototypeIsEmptyResponse() public function responsePrototypeIsEmptyResponse()
{ {
$instance = $this->factory->__invoke(new ServiceManager(), ''); $instance = $this->factory->__invoke(new ServiceManager(), '');

View File

@ -18,9 +18,7 @@ class EntityManagerFactoryTest extends TestCase
$this->factory = new EntityManagerFactory(); $this->factory = new EntityManagerFactory();
} }
/** /** @test */
* @test
*/
public function serviceIsCreated() public function serviceIsCreated()
{ {
$sm = new ServiceManager(['services' => [ $sm = new ServiceManager(['services' => [

View File

@ -19,9 +19,7 @@ class LoggerFactoryTest extends TestCase
$this->factory = new LoggerFactory(); $this->factory = new LoggerFactory();
} }
/** /** @test */
* @test
*/
public function serviceIsCreated() public function serviceIsCreated()
{ {
/** @var Logger $instance */ /** @var Logger $instance */
@ -30,9 +28,7 @@ class LoggerFactoryTest extends TestCase
$this->assertEquals('Logger', $instance->getName()); $this->assertEquals('Logger', $instance->getName());
} }
/** /** @test */
* @test
*/
public function nameIsSetFromOptions() public function nameIsSetFromOptions()
{ {
/** @var Logger $instance */ /** @var Logger $instance */
@ -41,9 +37,7 @@ class LoggerFactoryTest extends TestCase
$this->assertEquals('Foo', $instance->getName()); $this->assertEquals('Foo', $instance->getName());
} }
/** /** @test */
* @test
*/
public function serviceNameOverwritesOptionsLoggerName() public function serviceNameOverwritesOptionsLoggerName()
{ {
/** @var Logger $instance */ /** @var Logger $instance */

View File

@ -18,9 +18,7 @@ class TranslatorFactoryTest extends TestCase
$this->factory = new TranslatorFactory(); $this->factory = new TranslatorFactory();
} }
/** /** @test */
* @test
*/
public function serviceIsCreated() public function serviceIsCreated()
{ {
$instance = $this->factory->__invoke(new ServiceManager(['services' => [ $instance = $this->factory->__invoke(new ServiceManager(['services' => [

View File

@ -18,9 +18,7 @@ class ImageBuilderFactoryTest extends TestCase
$this->factory = new ImageBuilderFactory(); $this->factory = new ImageBuilderFactory();
} }
/** /** @test */
* @test
*/
public function serviceIsCreated() public function serviceIsCreated()
{ {
$instance = $this->factory->__invoke(new ServiceManager(), ''); $instance = $this->factory->__invoke(new ServiceManager(), '');

View File

@ -19,9 +19,7 @@ class ImageFactoryTest extends TestCase
$this->factory = new ImageFactory(); $this->factory = new ImageFactory();
} }
/** /** @test */
* @test
*/
public function noPageIsSetWhenOptionsAreNotProvided() public function noPageIsSetWhenOptionsAreNotProvided()
{ {
/** @var Image $image */ /** @var Image $image */
@ -36,9 +34,7 @@ class ImageFactoryTest extends TestCase
$this->assertNull($page->getValue($image)); $this->assertNull($page->getValue($image));
} }
/** /** @test */
* @test
*/
public function aPageIsSetWhenOptionsIncludeTheUrl() public function aPageIsSetWhenOptionsIncludeTheUrl()
{ {
$expectedPage = 'foo/bar.html'; $expectedPage = 'foo/bar.html';

View File

@ -30,9 +30,7 @@ class ChainIpLocationResolverTest extends TestCase
); );
} }
/** /** @test */
* @test
*/
public function throwsExceptionWhenNoInnerResolverCanHandleTheResolution() public function throwsExceptionWhenNoInnerResolverCanHandleTheResolution()
{ {
$ipAddress = '1.2.3.4'; $ipAddress = '1.2.3.4';

View File

@ -26,7 +26,7 @@ class EmptyIpLocationResolverTest extends TestCase
* @test * @test
* @dataProvider provideEmptyResponses * @dataProvider provideEmptyResponses
*/ */
public function alwaysReturnsAnEmptyResponse(string $ipAddress): void public function alwaysReturnsAnEmptyLocation(string $ipAddress): void
{ {
$this->assertEquals(Location::emptyInstance(), $this->resolver->resolveIpLocation($ipAddress)); $this->assertEquals(Location::emptyInstance(), $this->resolver->resolveIpLocation($ipAddress));
} }

View File

@ -39,10 +39,8 @@ class DbUpdaterTest extends TestCase
$this->dbUpdater = new DbUpdater($this->httpClient->reveal(), $this->filesystem->reveal(), $this->options); $this->dbUpdater = new DbUpdater($this->httpClient->reveal(), $this->filesystem->reveal(), $this->options);
} }
/** /** @test */
* @test public function anExceptionIsThrownIfFreshDbCannotBeDownloaded(): void
*/
public function anExceptionIsThrownIfFreshDbCannotBeDownloaded()
{ {
$request = $this->httpClient->request(Argument::cetera())->willThrow(ClientException::class); $request = $this->httpClient->request(Argument::cetera())->willThrow(ClientException::class);
@ -56,10 +54,8 @@ class DbUpdaterTest extends TestCase
$this->dbUpdater->downloadFreshCopy(); $this->dbUpdater->downloadFreshCopy();
} }
/** /** @test */
* @test public function anExceptionIsThrownIfFreshDbCannotBeExtracted(): void
*/
public function anExceptionIsThrownIfFreshDbCannotBeExtracted()
{ {
$this->options->tempDir = '__invalid__'; $this->options->tempDir = '__invalid__';
@ -79,7 +75,7 @@ class DbUpdaterTest extends TestCase
* @test * @test
* @dataProvider provideFilesystemExceptions * @dataProvider provideFilesystemExceptions
*/ */
public function anExceptionIsThrownIfFreshDbCannotBeCopiedToDestination(string $e) public function anExceptionIsThrownIfFreshDbCannotBeCopiedToDestination(string $e): void
{ {
$request = $this->httpClient->request(Argument::cetera())->willReturn(new Response()); $request = $this->httpClient->request(Argument::cetera())->willReturn(new Response());
$copy = $this->filesystem->copy(Argument::cetera())->willThrow($e); $copy = $this->filesystem->copy(Argument::cetera())->willThrow($e);
@ -93,18 +89,14 @@ class DbUpdaterTest extends TestCase
$this->dbUpdater->downloadFreshCopy(); $this->dbUpdater->downloadFreshCopy();
} }
public function provideFilesystemExceptions(): array public function provideFilesystemExceptions(): iterable
{ {
return [ yield 'file not found' => [FilesystemException\FileNotFoundException::class];
[FilesystemException\FileNotFoundException::class], yield 'IO error' => [FilesystemException\IOException::class];
[FilesystemException\IOException::class],
];
} }
/** /** @test */
* @test public function noExceptionsAreThrownIfEverythingWorksFine(): void
*/
public function noExceptionsAreThrownIfEverythingWorksFine()
{ {
$request = $this->httpClient->request(Argument::cetera())->willReturn(new Response()); $request = $this->httpClient->request(Argument::cetera())->willReturn(new Response());
$copy = $this->filesystem->copy(Argument::cetera())->will(function () { $copy = $this->filesystem->copy(Argument::cetera())->will(function () {

View File

@ -30,7 +30,7 @@ class GeoLite2LocationResolverTest extends TestCase
* @test * @test
* @dataProvider provideReaderExceptions * @dataProvider provideReaderExceptions
*/ */
public function exceptionIsThrownIfReaderThrowsException(string $e, string $message) public function exceptionIsThrownIfReaderThrowsException(string $e, string $message): void
{ {
$ipAddress = '1.2.3.4'; $ipAddress = '1.2.3.4';
@ -44,12 +44,10 @@ class GeoLite2LocationResolverTest extends TestCase
$this->resolver->resolveIpLocation($ipAddress); $this->resolver->resolveIpLocation($ipAddress);
} }
public function provideReaderExceptions(): array public function provideReaderExceptions(): iterable
{ {
return [ yield 'invalid IP address' => [AddressNotFoundException::class, 'Provided IP "1.2.3.4" is invalid'];
[AddressNotFoundException::class, 'Provided IP "1.2.3.4" is invalid'], yield 'invalid geolite DB' => [InvalidDatabaseException::class, 'Provided GeoLite2 db file is invalid'];
[InvalidDatabaseException::class, 'Provided GeoLite2 db file is invalid'],
];
} }
/** @test */ /** @test */

View File

@ -5,10 +5,15 @@ namespace ShlinkioTest\Shlink\Common\Logger\Processor;
use PHPUnit\Framework\TestCase; use PHPUnit\Framework\TestCase;
use Shlinkio\Shlink\Common\Logger\Processor\ExceptionWithNewLineProcessor; use Shlinkio\Shlink\Common\Logger\Processor\ExceptionWithNewLineProcessor;
use Shlinkio\Shlink\Common\Util\StringUtilsTrait;
use const PHP_EOL; use const PHP_EOL;
use function Functional\map;
use function range;
class ExceptionWithNewLineProcessorTest extends TestCase class ExceptionWithNewLineProcessorTest extends TestCase
{ {
use StringUtilsTrait;
/** @var ExceptionWithNewLineProcessor */ /** @var ExceptionWithNewLineProcessor */
private $processor; private $processor;
@ -21,44 +26,40 @@ class ExceptionWithNewLineProcessorTest extends TestCase
* @test * @test
* @dataProvider provideNoPlaceholderRecords * @dataProvider provideNoPlaceholderRecords
*/ */
public function keepsRecordAsIsWhenNoPlaceholderExists(array $record) public function keepsRecordAsIsWhenNoPlaceholderExists(array $record): void
{ {
$this->assertSame($record, ($this->processor)($record)); $this->assertSame($record, ($this->processor)($record));
} }
public function provideNoPlaceholderRecords(): array public function provideNoPlaceholderRecords(): iterable
{ {
return [ return map(range(1, 5), function () {
[['message' => 'Hello World']], return [['message' => $this->generateRandomString()]];
[['message' => 'Shlink']], });
[['message' => 'Foo bar']],
];
} }
/** /**
* @test * @test
* @dataProvider providePlaceholderRecords * @dataProvider providePlaceholderRecords
*/ */
public function properlyReplacesExceptionPlaceholderAddingNewLine(array $record, array $expected) public function properlyReplacesExceptionPlaceholderAddingNewLine(array $record, array $expected): void
{ {
$this->assertEquals($expected, ($this->processor)($record)); $this->assertEquals($expected, ($this->processor)($record));
} }
public function providePlaceholderRecords(): array public function providePlaceholderRecords(): iterable
{ {
return [ yield [
[ ['message' => 'Hello World with placeholder {e}'],
['message' => 'Hello World with placeholder {e}'], ['message' => 'Hello World with placeholder ' . PHP_EOL . '{e}'],
['message' => 'Hello World with placeholder ' . PHP_EOL . '{e}'], ];
], yield [
[ ['message' => '{e} Shlink'],
['message' => '{e} Shlink'], ['message' => PHP_EOL . '{e} Shlink'],
['message' => PHP_EOL . '{e} Shlink'], ];
], yield [
[ ['message' => 'Foo {e} bar'],
['message' => 'Foo {e} bar'], ['message' => 'Foo ' . PHP_EOL . '{e} bar'],
['message' => 'Foo ' . PHP_EOL . '{e} bar'],
],
]; ];
} }
} }

View File

@ -29,9 +29,7 @@ class CloseDbConnectionMiddlewareTest extends TestCase
$this->middleware = new CloseDbConnectionMiddleware($this->em->reveal()); $this->middleware = new CloseDbConnectionMiddleware($this->em->reveal());
} }
/** /** @test */
* @test
*/
public function connectionIsClosedWhenMiddlewareIsProcessed() public function connectionIsClosedWhenMiddlewareIsProcessed()
{ {
$req = new ServerRequest(); $req = new ServerRequest();

View File

@ -18,9 +18,7 @@ class IpAddressMiddlewareFactoryTest extends TestCase
$this->factory = new IpAddressMiddlewareFactory(); $this->factory = new IpAddressMiddlewareFactory();
} }
/** /** @test */
* @test
*/
public function returnedInstanceIsProperlyConfigured() public function returnedInstanceIsProperlyConfigured()
{ {
$instance = $this->factory->__invoke(new ServiceManager(), ''); $instance = $this->factory->__invoke(new ServiceManager(), '');

View File

@ -22,20 +22,16 @@ class LocaleMiddlewareTest extends TestCase
$this->middleware = new LocaleMiddleware($this->translator); $this->middleware = new LocaleMiddleware($this->translator);
} }
/** /** @test */
* @test public function whenNoHeaderIsPresentLocaleIsNotChanged(): void
*/
public function whenNoHeaderIsPresentLocaleIsNotChanged()
{ {
$this->assertEquals('ru', $this->translator->getLocale()); $this->assertEquals('ru', $this->translator->getLocale());
$this->middleware->process(new ServerRequest(), TestUtils::createReqHandlerMock()->reveal()); $this->middleware->process(new ServerRequest(), TestUtils::createReqHandlerMock()->reveal());
$this->assertEquals('ru', $this->translator->getLocale()); $this->assertEquals('ru', $this->translator->getLocale());
} }
/** /** @test */
* @test public function whenTheHeaderIsPresentLocaleIsChanged(): void
*/
public function whenTheHeaderIsPresentLocaleIsChanged()
{ {
$this->assertEquals('ru', $this->translator->getLocale()); $this->assertEquals('ru', $this->translator->getLocale());
$request = (new ServerRequest())->withHeader('Accept-Language', 'es'); $request = (new ServerRequest())->withHeader('Accept-Language', 'es');
@ -47,7 +43,7 @@ class LocaleMiddlewareTest extends TestCase
* @test * @test
* @dataProvider provideLanguages * @dataProvider provideLanguages
*/ */
public function localeGetsNormalized(string $lang, string $expected) public function localeGetsNormalized(string $lang, string $expected): void
{ {
$handler = TestUtils::createReqHandlerMock(); $handler = TestUtils::createReqHandlerMock();
@ -58,12 +54,10 @@ class LocaleMiddlewareTest extends TestCase
$this->assertEquals($expected, $this->translator->getLocale()); $this->assertEquals($expected, $this->translator->getLocale());
} }
public function provideLanguages(): array public function provideLanguages(): iterable
{ {
return [ yield 'language only' => ['ru', 'ru'];
['ru', 'ru'], yield 'country and language with underscore' => ['es_ES', 'es'];
['es_ES', 'es'], yield 'country and language with dash' => ['en-US', 'en'];
['en-US', 'en'],
];
} }
} }

View File

@ -21,18 +21,14 @@ class PaginableRepositoryAdapterTest extends TestCase
$this->adapter = new PaginableRepositoryAdapter($this->repo->reveal(), 'search', ['foo', 'bar'], 'order'); $this->adapter = new PaginableRepositoryAdapter($this->repo->reveal(), 'search', ['foo', 'bar'], 'order');
} }
/** /** @test */
* @test
*/
public function getItemsFallbacksToFindList() public function getItemsFallbacksToFindList()
{ {
$this->repo->findList(10, 5, 'search', ['foo', 'bar'], 'order')->shouldBeCalledOnce(); $this->repo->findList(10, 5, 'search', ['foo', 'bar'], 'order')->shouldBeCalledOnce();
$this->adapter->getItems(5, 10); $this->adapter->getItems(5, 10);
} }
/** /** @test */
* @test
*/
public function countFallbacksToCountList() public function countFallbacksToCountList()
{ {
$this->repo->countList('search', ['foo', 'bar'])->shouldBeCalledOnce(); $this->repo->countList('search', ['foo', 'bar'])->shouldBeCalledOnce();

View File

@ -16,9 +16,7 @@ class PixelResponseTest extends TestCase
$this->resp = new PixelResponse(); $this->resp = new PixelResponse();
} }
/** /** @test */
* @test
*/
public function responseHasGifTypeAndIsNotEmpty() public function responseHasGifTypeAndIsNotEmpty()
{ {
$this->assertEquals('image/gif', $this->resp->getHeaderLine('Content-Type')); $this->assertEquals('image/gif', $this->resp->getHeaderLine('Content-Type'));

View File

@ -9,9 +9,7 @@ use Shlinkio\Shlink\Common\Response\QrCodeResponse;
class QrCodeResponseTest extends TestCase class QrCodeResponseTest extends TestCase
{ {
/** /** @test */
* @test
*/
public function providedQrCoideIsSetAsBody() public function providedQrCoideIsSetAsBody()
{ {
$qrCode = new QrCode('Hello'); $qrCode = new QrCode('Hello');

View File

@ -38,9 +38,7 @@ class PreviewGeneratorTest extends TestCase
]), $this->filesystem->reveal(), 'dir'); ]), $this->filesystem->reveal(), 'dir');
} }
/** /** @test */
* @test
*/
public function alreadyProcessedElementsAreNotProcessed() public function alreadyProcessedElementsAreNotProcessed()
{ {
$url = 'http://foo.com'; $url = 'http://foo.com';
@ -50,9 +48,7 @@ class PreviewGeneratorTest extends TestCase
$this->assertEquals(sprintf('dir/preview_%s.png', urlencode($url)), $this->generator->generatePreview($url)); $this->assertEquals(sprintf('dir/preview_%s.png', urlencode($url)), $this->generator->generatePreview($url));
} }
/** /** @test */
* @test
*/
public function nonProcessedElementsAreProcessed() public function nonProcessedElementsAreProcessed()
{ {
$url = 'http://foo.com'; $url = 'http://foo.com';

View File

@ -19,9 +19,7 @@ class TranslatorExtensionTest extends TestCase
$this->extension = new TranslatorExtension($this->prophesize(Translator::class)->reveal()); $this->extension = new TranslatorExtension($this->prophesize(Translator::class)->reveal());
} }
/** /** @test */
* @test
*/
public function properFunctionsAreReturned() public function properFunctionsAreReturned()
{ {
$engine = $this->prophesize(Engine::class); $engine = $this->prophesize(Engine::class);

View File

@ -28,10 +28,8 @@ class ChronosDateTimeTypeTest extends TestCase
$this->type = Type::getType(ChronosDateTimeType::CHRONOS_DATETIME); $this->type = Type::getType(ChronosDateTimeType::CHRONOS_DATETIME);
} }
/** /** @test */
* @test public function nameIsReturned(): void
*/
public function nameIsReturned()
{ {
$this->assertEquals(ChronosDateTimeType::CHRONOS_DATETIME, $this->type->getName()); $this->assertEquals(ChronosDateTimeType::CHRONOS_DATETIME, $this->type->getName());
} }
@ -40,7 +38,7 @@ class ChronosDateTimeTypeTest extends TestCase
* @test * @test
* @dataProvider provideValues * @dataProvider provideValues
*/ */
public function valueIsConverted(?string $value, ?string $expected) public function valueIsConverted(?string $value, ?string $expected): void
{ {
$platform = $this->prophesize(AbstractPlatform::class); $platform = $this->prophesize(AbstractPlatform::class);
$platform->getDateTimeFormatString()->willReturn('Y-m-d H:i:s'); $platform->getDateTimeFormatString()->willReturn('Y-m-d H:i:s');
@ -54,20 +52,18 @@ class ChronosDateTimeTypeTest extends TestCase
} }
} }
public function provideValues(): array public function provideValues(): iterable
{ {
return [ yield 'null date' => [null, null];
[null, null], yield 'human friendly date' => ['now', Chronos::class];
['now', Chronos::class], yield 'numeric date' => ['2017-01-01', Chronos::class];
['2017-01-01', Chronos::class],
];
} }
/** /**
* @test * @test
* @dataProvider providePhpValues * @dataProvider providePhpValues
*/ */
public function valueIsConvertedToDatabaseFormat(?DateTimeInterface $value, ?string $expected) public function valueIsConvertedToDatabaseFormat(?DateTimeInterface $value, ?string $expected): void
{ {
$platform = $this->prophesize(AbstractPlatform::class); $platform = $this->prophesize(AbstractPlatform::class);
$platform->getDateTimeFormatString()->willReturn('Y-m-d'); $platform->getDateTimeFormatString()->willReturn('Y-m-d');
@ -75,20 +71,16 @@ class ChronosDateTimeTypeTest extends TestCase
$this->assertEquals($expected, $this->type->convertToDatabaseValue($value, $platform->reveal())); $this->assertEquals($expected, $this->type->convertToDatabaseValue($value, $platform->reveal()));
} }
public function providePhpValues(): array public function providePhpValues(): iterable
{ {
return [ yield 'null date' => [null, null];
[null, null], yield 'DateTimeImmutable date' => [new DateTimeImmutable('2017-01-01'), '2017-01-01'];
[new DateTimeImmutable('2017-01-01'), '2017-01-01'], yield 'Chronos date' => [Chronos::parse('2017-02-01'), '2017-02-01'];
[Chronos::parse('2017-02-01'), '2017-02-01'], yield 'DateTime date' => [new DateTime('2017-03-01'), '2017-03-01'];
[new DateTime('2017-03-01'), '2017-03-01'],
];
} }
/** /** @test */
* @test public function exceptionIsThrownIfInvalidValueIsParsedToDatabase(): void
*/
public function exceptionIsThrownIfInvalidValueIsParsedToDatabase()
{ {
$this->expectException(ConversionException::class); $this->expectException(ConversionException::class);
$this->type->convertToDatabaseValue(new stdClass(), $this->prophesize(AbstractPlatform::class)->reveal()); $this->type->convertToDatabaseValue(new stdClass(), $this->prophesize(AbstractPlatform::class)->reveal());

View File

@ -9,9 +9,7 @@ use Shlinkio\Shlink\Common\Util\DateRange;
class DateRangeTest extends TestCase class DateRangeTest extends TestCase
{ {
/** /** @test */
* @test
*/
public function defaultConstructorSetDatesToNull() public function defaultConstructorSetDatesToNull()
{ {
$range = new DateRange(); $range = new DateRange();
@ -20,9 +18,7 @@ class DateRangeTest extends TestCase
$this->assertTrue($range->isEmpty()); $this->assertTrue($range->isEmpty());
} }
/** /** @test */
* @test
*/
public function providedDatesAreSet() public function providedDatesAreSet()
{ {
$startDate = Chronos::now(); $startDate = Chronos::now();
@ -37,19 +33,20 @@ class DateRangeTest extends TestCase
* @test * @test
* @dataProvider provideDates * @dataProvider provideDates
*/ */
public function isConsideredEmptyOnlyIfNoneOfTheDatesIsSet(?Chronos $startDate, ?Chronos $endDate, bool $isEmpty) public function isConsideredEmptyOnlyIfNoneOfTheDatesIsSet(
{ ?Chronos $startDate,
?Chronos $endDate,
bool $isEmpty
): void {
$range = new DateRange($startDate, $endDate); $range = new DateRange($startDate, $endDate);
$this->assertEquals($isEmpty, $range->isEmpty()); $this->assertEquals($isEmpty, $range->isEmpty());
} }
public function provideDates(): array public function provideDates(): iterable
{ {
return [ yield 'both are null' => [null, null, true];
[null, null, true], yield 'start is null' => [null, Chronos::now(), false];
[null, Chronos::now(), false], yield 'end is null' => [Chronos::now(), null, false];
[Chronos::now(), null, false], yield 'none are null' => [Chronos::now(), Chronos::now(), false];
[Chronos::now(), Chronos::now(), false],
];
} }
} }

View File

@ -5,6 +5,8 @@ namespace ShlinkioTest\Shlink\Common\Util;
use PHPUnit\Framework\TestCase; use PHPUnit\Framework\TestCase;
use Shlinkio\Shlink\Common\Util\StringUtilsTrait; use Shlinkio\Shlink\Common\Util\StringUtilsTrait;
use function Functional\map;
use function range;
use function strlen; use function strlen;
class StringUtilsTraitTest extends TestCase class StringUtilsTraitTest extends TestCase
@ -15,23 +17,19 @@ class StringUtilsTraitTest extends TestCase
* @test * @test
* @dataProvider provideLengths * @dataProvider provideLengths
*/ */
public function generateRandomStringGeneratesStringOfProvidedLength(int $length) public function generateRandomStringGeneratesStringOfProvidedLength(int $length): void
{ {
$this->assertEquals($length, strlen($this->generateRandomString($length))); $this->assertEquals($length, strlen($this->generateRandomString($length)));
} }
public function provideLengths(): array public function provideLengths(): array
{ {
return [ return map(range(10, 50, 5), function (int $i) {
[1], return [$i];
[10], });
[15],
];
} }
/** /** @test */
* @test
*/
public function generatesUuidV4() public function generatesUuidV4()
{ {
$uuidPattern = '/[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}/'; $uuidPattern = '/[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}/';

View File

@ -82,7 +82,7 @@ class Visit extends AbstractEntity implements JsonSerializable
{ {
return [ return [
'referer' => $this->referer, 'referer' => $this->referer,
'date' => isset($this->date) ? $this->date->toAtomString() : null, 'date' => $this->date !== null ? $this->date->toAtomString() : null,
'userAgent' => $this->userAgent, 'userAgent' => $this->userAgent,
'visitLocation' => $this->visitLocation, 'visitLocation' => $this->visitLocation,

View File

@ -3,12 +3,12 @@ declare(strict_types=1);
namespace Shlinkio\Shlink\Core\Exception; namespace Shlinkio\Shlink\Core\Exception;
use Exception; use Throwable;
use function sprintf; use function sprintf;
class InvalidShortCodeException extends RuntimeException class InvalidShortCodeException extends RuntimeException
{ {
public static function fromCharset(string $shortCode, string $charSet, Exception $previous = null): self public static function fromCharset(string $shortCode, string $charSet, ?Throwable $previous = null): self
{ {
$code = $previous !== null ? $previous->getCode() : -1; $code = $previous !== null ? $previous->getCode() : -1;
return new static( return new static(

View File

@ -8,7 +8,7 @@ use function sprintf;
class InvalidUrlException extends RuntimeException class InvalidUrlException extends RuntimeException
{ {
public static function fromUrl(string $url, Throwable $previous = null) public static function fromUrl(string $url, Throwable $previous = null): self
{ {
$code = $previous !== null ? $previous->getCode() : -1; $code = $previous !== null ? $previous->getCode() : -1;
return new static(sprintf('Provided URL "%s" is not an existing and valid URL', $url), $code, $previous); return new static(sprintf('Provided URL "%s" is not an existing and valid URL', $url), $code, $previous);

View File

@ -30,9 +30,7 @@ class ShortUrlRepositoryTest extends DatabaseTestCase
$this->repo = $this->getEntityManager()->getRepository(ShortUrl::class); $this->repo = $this->getEntityManager()->getRepository(ShortUrl::class);
} }
/** /** @test */
* @test
*/
public function findOneByShortCodeReturnsProperData() public function findOneByShortCodeReturnsProperData()
{ {
$foo = new ShortUrl('foo'); $foo = new ShortUrl('foo');
@ -62,9 +60,7 @@ class ShortUrlRepositoryTest extends DatabaseTestCase
$this->assertNull($this->repo->findOneByShortCode($baz->getShortCode())); $this->assertNull($this->repo->findOneByShortCode($baz->getShortCode()));
} }
/** /** @test */
* @test
*/
public function countListReturnsProperNumberOfResults() public function countListReturnsProperNumberOfResults()
{ {
$count = 5; $count = 5;
@ -78,9 +74,7 @@ class ShortUrlRepositoryTest extends DatabaseTestCase
$this->assertEquals($count, $this->repo->countList()); $this->assertEquals($count, $this->repo->countList());
} }
/** /** @test */
* @test
*/
public function findListProperlyFiltersByTagAndSearchTerm() public function findListProperlyFiltersByTagAndSearchTerm()
{ {
$tag = new Tag('bar'); $tag = new Tag('bar');
@ -125,9 +119,7 @@ class ShortUrlRepositoryTest extends DatabaseTestCase
$this->assertSame($bar, $result[0]); $this->assertSame($bar, $result[0]);
} }
/** /** @test */
* @test
*/
public function findListProperlyMapsFieldNamesToColumnNamesWhenOrdering() public function findListProperlyMapsFieldNamesToColumnNamesWhenOrdering()
{ {
$urls = ['a', 'z', 'c', 'b']; $urls = ['a', 'z', 'c', 'b'];

View File

@ -21,17 +21,13 @@ class TagRepositoryTest extends DatabaseTestCase
$this->repo = $this->getEntityManager()->getRepository(Tag::class); $this->repo = $this->getEntityManager()->getRepository(Tag::class);
} }
/** /** @test */
* @test
*/
public function deleteByNameDoesNothingWhenEmptyListIsProvided() public function deleteByNameDoesNothingWhenEmptyListIsProvided()
{ {
$this->assertEquals(0, $this->repo->deleteByName([])); $this->assertEquals(0, $this->repo->deleteByName([]));
} }
/** /** @test */
* @test
*/
public function allTagsWhichMatchNameAreDeleted() public function allTagsWhichMatchNameAreDeleted()
{ {
$names = ['foo', 'bar', 'baz']; $names = ['foo', 'bar', 'baz'];

View File

@ -37,9 +37,7 @@ class PixelActionTest extends TestCase
); );
} }
/** /** @test */
* @test
*/
public function imageIsReturned() public function imageIsReturned()
{ {
$shortCode = 'abc123'; $shortCode = 'abc123';

View File

@ -37,9 +37,7 @@ class PreviewActionTest extends TestCase
$this->action = new PreviewAction($this->previewGenerator->reveal(), $this->urlShortener->reveal()); $this->action = new PreviewAction($this->previewGenerator->reveal(), $this->urlShortener->reveal());
} }
/** /** @test */
* @test
*/
public function invalidShortCodeFallsBackToNextMiddleware() public function invalidShortCodeFallsBackToNextMiddleware()
{ {
$shortCode = 'abc123'; $shortCode = 'abc123';
@ -52,9 +50,7 @@ class PreviewActionTest extends TestCase
$this->action->process((new ServerRequest())->withAttribute('shortCode', $shortCode), $delegate->reveal()); $this->action->process((new ServerRequest())->withAttribute('shortCode', $shortCode), $delegate->reveal());
} }
/** /** @test */
* @test
*/
public function correctShortCodeReturnsImageResponse() public function correctShortCodeReturnsImageResponse()
{ {
$shortCode = 'abc123'; $shortCode = 'abc123';
@ -73,9 +69,7 @@ class PreviewActionTest extends TestCase
$this->assertEquals((new finfo(FILEINFO_MIME))->file($path), $resp->getHeaderLine('Content-type')); $this->assertEquals((new finfo(FILEINFO_MIME))->file($path), $resp->getHeaderLine('Content-type'));
} }
/** /** @test */
* @test
*/
public function invalidShortCodeExceptionFallsBackToNextMiddleware() public function invalidShortCodeExceptionFallsBackToNextMiddleware()
{ {
$shortCode = 'abc123'; $shortCode = 'abc123';

View File

@ -35,9 +35,7 @@ class QrCodeActionTest extends TestCase
$this->action = new QrCodeAction($router->reveal(), $this->urlShortener->reveal()); $this->action = new QrCodeAction($router->reveal(), $this->urlShortener->reveal());
} }
/** /** @test */
* @test
*/
public function aNotFoundShortCodeWillDelegateIntoNextMiddleware() public function aNotFoundShortCodeWillDelegateIntoNextMiddleware()
{ {
$shortCode = 'abc123'; $shortCode = 'abc123';
@ -51,9 +49,7 @@ class QrCodeActionTest extends TestCase
$process->shouldHaveBeenCalledOnce(); $process->shouldHaveBeenCalledOnce();
} }
/** /** @test */
* @test
*/
public function anInvalidShortCodeWillReturnNotFoundResponse() public function anInvalidShortCodeWillReturnNotFoundResponse()
{ {
$shortCode = 'abc123'; $shortCode = 'abc123';
@ -68,9 +64,7 @@ class QrCodeActionTest extends TestCase
$process->shouldHaveBeenCalledOnce(); $process->shouldHaveBeenCalledOnce();
} }
/** /** @test */
* @test
*/
public function aCorrectRequestReturnsTheQrCodeResponse() public function aCorrectRequestReturnsTheQrCodeResponse()
{ {
$shortCode = 'abc123'; $shortCode = 'abc123';

View File

@ -42,9 +42,7 @@ class RedirectActionTest extends TestCase
); );
} }
/** /** @test */
* @test
*/
public function redirectionIsPerformedToLongUrl() public function redirectionIsPerformedToLongUrl()
{ {
$shortCode = 'abc123'; $shortCode = 'abc123';
@ -63,9 +61,7 @@ class RedirectActionTest extends TestCase
$this->assertEquals($expectedUrl, $response->getHeaderLine('Location')); $this->assertEquals($expectedUrl, $response->getHeaderLine('Location'));
} }
/** /** @test */
* @test
*/
public function nextMiddlewareIsInvokedIfLongUrlIsNotFound() public function nextMiddlewareIsInvokedIfLongUrlIsNotFound()
{ {
$shortCode = 'abc123'; $shortCode = 'abc123';
@ -82,9 +78,7 @@ class RedirectActionTest extends TestCase
$handle->shouldHaveBeenCalledOnce(); $handle->shouldHaveBeenCalledOnce();
} }
/** /** @test */
* @test
*/
public function redirectToCustomUrlIsReturnedIfConfiguredSoAndShortUrlIsNotFound() public function redirectToCustomUrlIsReturnedIfConfiguredSoAndShortUrlIsNotFound()
{ {
$shortCode = 'abc123'; $shortCode = 'abc123';
@ -107,9 +101,7 @@ class RedirectActionTest extends TestCase
$handle->shouldNotHaveBeenCalled(); $handle->shouldNotHaveBeenCalled();
} }
/** /** @test */
* @test
*/
public function visitIsNotTrackedIfDisableParamIsProvided() public function visitIsNotTrackedIfDisableParamIsProvided()
{ {
$shortCode = 'abc123'; $shortCode = 'abc123';

View File

@ -16,9 +16,7 @@ class ConfigProviderTest extends TestCase
$this->configProvider = new ConfigProvider(); $this->configProvider = new ConfigProvider();
} }
/** /** @test */
* @test
*/
public function properConfigIsReturned() public function properConfigIsReturned()
{ {
$config = $this->configProvider->__invoke(); $config = $this->configProvider->__invoke();

View File

@ -8,9 +8,7 @@ use Shlinkio\Shlink\Core\Entity\Tag;
class TagTest extends TestCase class TagTest extends TestCase
{ {
/** /** @test */
* @test
*/
public function jsonSerializationOfTagsReturnsItsStringRepresentation() public function jsonSerializationOfTagsReturnsItsStringRepresentation()
{ {
$tag = new Tag('This is my name'); $tag = new Tag('This is my name');

View File

@ -15,7 +15,7 @@ class VisitTest extends TestCase
* @test * @test
* @dataProvider provideDates * @dataProvider provideDates
*/ */
public function isProperlyJsonSerialized(?Chronos $date) public function isProperlyJsonSerialized(?Chronos $date): void
{ {
$visit = new Visit(new ShortUrl(''), new Visitor('Chrome', 'some site', '1.2.3.4'), $date); $visit = new Visit(new ShortUrl(''), new Visitor('Chrome', 'some site', '1.2.3.4'), $date);
@ -30,11 +30,9 @@ class VisitTest extends TestCase
], $visit->jsonSerialize()); ], $visit->jsonSerialize());
} }
public function provideDates(): array public function provideDates(): iterable
{ {
return [ yield 'null date' => [null];
[null], yield 'not null date' => [Chronos::now()->subDays(10)];
[Chronos::now()->subDays(10)],
];
} }
} }

View File

@ -4,61 +4,56 @@ declare(strict_types=1);
namespace ShlinkioTest\Shlink\Core\Exception; namespace ShlinkioTest\Shlink\Core\Exception;
use PHPUnit\Framework\TestCase; use PHPUnit\Framework\TestCase;
use Shlinkio\Shlink\Common\Util\StringUtilsTrait;
use Shlinkio\Shlink\Core\Exception\DeleteShortUrlException; use Shlinkio\Shlink\Core\Exception\DeleteShortUrlException;
use function Functional\map; use function Functional\map;
use function range; use function range;
use function sprintf;
class DeleteShortUrlExceptionTest extends TestCase class DeleteShortUrlExceptionTest extends TestCase
{ {
use StringUtilsTrait;
/** /**
* @test * @test
* @dataProvider provideMessages * @dataProvider provideThresholds
*/ */
public function fromVisitsThresholdGeneratesMessageProperly( public function fromVisitsThresholdGeneratesMessageProperly(
int $threshold, int $threshold,
string $shortCode, string $shortCode,
string $expectedMessage string $expectedMessage
) { ): void {
$e = DeleteShortUrlException::fromVisitsThreshold($threshold, $shortCode); $e = DeleteShortUrlException::fromVisitsThreshold($threshold, $shortCode);
$this->assertEquals($threshold, $e->getVisitsThreshold());
$this->assertEquals($expectedMessage, $e->getMessage()); $this->assertEquals($expectedMessage, $e->getMessage());
$this->assertEquals(0, $e->getCode()); $this->assertEquals(0, $e->getCode());
} $this->assertNull($e->getPrevious());
public function provideMessages(): array
{
return [
[
50,
'abc123',
'Impossible to delete short URL with short code "abc123" since it has more than "50" visits.',
],
[
33,
'def456',
'Impossible to delete short URL with short code "def456" since it has more than "33" visits.',
],
[
5713,
'foobar',
'Impossible to delete short URL with short code "foobar" since it has more than "5713" visits.',
],
];
} }
/** /**
* @test * @test
* @dataProvider provideThresholds * @dataProvider provideThresholds
*/ */
public function visitsThresholdIsProperlyReturned(int $threshold) public function visitsThresholdIsProperlyReturned(int $threshold): void
{ {
$e = new DeleteShortUrlException($threshold); $e = new DeleteShortUrlException($threshold);
$this->assertEquals($threshold, $e->getVisitsThreshold()); $this->assertEquals($threshold, $e->getVisitsThreshold());
$this->assertEquals('', $e->getMessage());
$this->assertEquals(0, $e->getCode());
$this->assertNull($e->getPrevious());
} }
public function provideThresholds(): array public function provideThresholds(): array
{ {
return map(range(5, 50, 5), function (int $number) { return map(range(5, 50, 5), function (int $number) {
return [$number]; $shortCode = $this->generateRandomString(6);
return [$number, $shortCode, sprintf(
'Impossible to delete short URL with short code "%s" since it has more than "%s" visits.',
$shortCode,
$number
)];
}); });
} }
} }

View File

@ -14,7 +14,7 @@ class InvalidShortCodeExceptionTest extends TestCase
* @test * @test
* @dataProvider providePrevious * @dataProvider providePrevious
*/ */
public function properlyCreatesExceptionFromCharset(?Throwable $prev) public function properlyCreatesExceptionFromCharset(?Throwable $prev): void
{ {
$e = InvalidShortCodeException::fromCharset('abc123', 'def456', $prev); $e = InvalidShortCodeException::fromCharset('abc123', 'def456', $prev);
@ -23,18 +23,14 @@ class InvalidShortCodeExceptionTest extends TestCase
$this->assertEquals($prev, $e->getPrevious()); $this->assertEquals($prev, $e->getPrevious());
} }
public function providePrevious(): array public function providePrevious(): iterable
{ {
return [ yield 'null previous' => [null];
[null], yield 'instance previous' => [new Exception('Previous error', 10)];
[new Exception('Previos error', 10)],
];
} }
/** /** @test */
* @test public function properlyCreatesExceptionFromNotFoundShortCode(): void
*/
public function properlyCreatesExceptionFromNotFoundShortCode()
{ {
$e = InvalidShortCodeException::fromNotFoundShortCode('abc123'); $e = InvalidShortCodeException::fromNotFoundShortCode('abc123');

View File

@ -14,7 +14,7 @@ class InvalidUrlExceptionTest extends TestCase
* @test * @test
* @dataProvider providePrevious * @dataProvider providePrevious
*/ */
public function properlyCreatesExceptionFromUrl(?Throwable $prev) public function properlyCreatesExceptionFromUrl(?Throwable $prev): void
{ {
$e = InvalidUrlException::fromUrl('http://the_url.com', $prev); $e = InvalidUrlException::fromUrl('http://the_url.com', $prev);
@ -23,11 +23,9 @@ class InvalidUrlExceptionTest extends TestCase
$this->assertEquals($prev, $e->getPrevious()); $this->assertEquals($prev, $e->getPrevious());
} }
public function providePrevious(): array public function providePrevious(): iterable
{ {
return [ yield 'null previous' => [null];
[null], yield 'instance previous' => [new Exception('Previous error', 10)];
[new Exception('Previos error', 10)],
];
} }
} }

View File

@ -26,9 +26,7 @@ class QrCodeCacheMiddlewareTest extends TestCase
$this->middleware = new QrCodeCacheMiddleware($this->cache); $this->middleware = new QrCodeCacheMiddleware($this->cache);
} }
/** /** @test */
* @test
*/
public function noCachedPathFallsBackToNextMiddleware() public function noCachedPathFallsBackToNextMiddleware()
{ {
$delegate = $this->prophesize(RequestHandlerInterface::class); $delegate = $this->prophesize(RequestHandlerInterface::class);
@ -39,9 +37,7 @@ class QrCodeCacheMiddlewareTest extends TestCase
$this->assertTrue($this->cache->contains('/foo/bar')); $this->assertTrue($this->cache->contains('/foo/bar'));
} }
/** /** @test */
* @test
*/
public function cachedPathReturnsCacheContent() public function cachedPathReturnsCacheContent()
{ {
$isCalled = false; $isCalled = false;

View File

@ -16,32 +16,28 @@ class ShortUrlMetaTest extends TestCase
* @test * @test
* @dataProvider provideInvalidData * @dataProvider provideInvalidData
*/ */
public function exceptionIsThrownIfProvidedDataIsInvalid(array $data) public function exceptionIsThrownIfProvidedDataIsInvalid(array $data): void
{ {
$this->expectException(ValidationException::class); $this->expectException(ValidationException::class);
ShortUrlMeta::createFromRawData($data); ShortUrlMeta::createFromRawData($data);
} }
public function provideInvalidData(): array public function provideInvalidData(): iterable
{ {
return [ yield [[
[[ ShortUrlMetaInputFilter::VALID_SINCE => '',
ShortUrlMetaInputFilter::VALID_SINCE => '', ShortUrlMetaInputFilter::VALID_UNTIL => '',
ShortUrlMetaInputFilter::VALID_UNTIL => '', ShortUrlMetaInputFilter::CUSTOM_SLUG => 'foobar',
ShortUrlMetaInputFilter::CUSTOM_SLUG => 'foobar', ShortUrlMetaInputFilter::MAX_VISITS => 'invalid',
ShortUrlMetaInputFilter::MAX_VISITS => 'invalid', ]];
]], yield [[
[[ ShortUrlMetaInputFilter::VALID_SINCE => '2017',
ShortUrlMetaInputFilter::VALID_SINCE => '2017', ShortUrlMetaInputFilter::MAX_VISITS => 5,
ShortUrlMetaInputFilter::MAX_VISITS => 5, ]];
]],
];
} }
/** /** @test */
* @test public function properlyCreatedInstanceReturnsValues(): void
*/
public function properlyCreatedInstanceReturnsValues()
{ {
$meta = ShortUrlMeta::createFromParams(Chronos::parse('2015-01-01')->toAtomString(), null, 'foobar'); $meta = ShortUrlMeta::createFromParams(Chronos::parse('2015-01-01')->toAtomString(), null, 'foobar');

View File

@ -5,7 +5,6 @@ namespace ShlinkioTest\Shlink\Core\Response;
use PHPUnit\Framework\TestCase; use PHPUnit\Framework\TestCase;
use Prophecy\Argument; use Prophecy\Argument;
use Prophecy\Prophecy\MethodProphecy;
use Prophecy\Prophecy\ObjectProphecy; use Prophecy\Prophecy\ObjectProphecy;
use Shlinkio\Shlink\Core\Response\NotFoundHandler; use Shlinkio\Shlink\Core\Response\NotFoundHandler;
use Zend\Diactoros\Response; use Zend\Diactoros\Response;
@ -26,17 +25,12 @@ class NotFoundHandlerTest extends TestCase
} }
/** /**
* @param string $expectedResponse
* @param string $accept
* @param int $renderCalls
*
* @test * @test
* @dataProvider provideResponses * @dataProvider provideResponses
*/ */
public function properResponseTypeIsReturned(string $expectedResponse, string $accept, int $renderCalls) public function properResponseTypeIsReturned(string $expectedResponse, string $accept, int $renderCalls): void
{ {
$request = (new ServerRequest())->withHeader('Accept', $accept); $request = (new ServerRequest())->withHeader('Accept', $accept);
/** @var MethodProphecy $render */
$render = $this->renderer->render(Argument::cetera())->willReturn(''); $render = $this->renderer->render(Argument::cetera())->willReturn('');
$resp = $this->delegate->handle($request); $resp = $this->delegate->handle($request);
@ -45,13 +39,11 @@ class NotFoundHandlerTest extends TestCase
$render->shouldHaveBeenCalledTimes($renderCalls); $render->shouldHaveBeenCalledTimes($renderCalls);
} }
public function provideResponses(): array public function provideResponses(): iterable
{ {
return [ yield 'application/json' => [Response\JsonResponse::class, 'application/json', 0];
[Response\JsonResponse::class, 'application/json', 0], yield 'text/json' => [Response\JsonResponse::class, 'text/json', 0];
[Response\JsonResponse::class, 'text/json', 0], yield 'application/x-json' => [Response\JsonResponse::class, 'application/x-json', 0];
[Response\JsonResponse::class, 'application/x-json', 0], yield 'text/html' => [Response\HtmlResponse::class, 'text/html', 1];
[Response\HtmlResponse::class, 'text/html', 1],
];
} }
} }

View File

@ -39,9 +39,7 @@ class DeleteShortUrlServiceTest extends TestCase
$this->em->getRepository(ShortUrl::class)->willReturn($repo->reveal()); $this->em->getRepository(ShortUrl::class)->willReturn($repo->reveal());
} }
/** /** @test */
* @test
*/
public function deleteByShortCodeThrowsExceptionWhenThresholdIsReached() public function deleteByShortCodeThrowsExceptionWhenThresholdIsReached()
{ {
$service = $this->createService(); $service = $this->createService();
@ -54,9 +52,7 @@ class DeleteShortUrlServiceTest extends TestCase
$service->deleteByShortCode('abc123'); $service->deleteByShortCode('abc123');
} }
/** /** @test */
* @test
*/
public function deleteByShortCodeDeletesUrlWhenThresholdIsReachedButExplicitlyIgnored() public function deleteByShortCodeDeletesUrlWhenThresholdIsReachedButExplicitlyIgnored()
{ {
$service = $this->createService(); $service = $this->createService();
@ -70,9 +66,7 @@ class DeleteShortUrlServiceTest extends TestCase
$flush->shouldHaveBeenCalledOnce(); $flush->shouldHaveBeenCalledOnce();
} }
/** /** @test */
* @test
*/
public function deleteByShortCodeDeletesUrlWhenThresholdIsReachedButCheckIsDisabled() public function deleteByShortCodeDeletesUrlWhenThresholdIsReachedButCheckIsDisabled()
{ {
$service = $this->createService(false); $service = $this->createService(false);
@ -86,9 +80,7 @@ class DeleteShortUrlServiceTest extends TestCase
$flush->shouldHaveBeenCalledOnce(); $flush->shouldHaveBeenCalledOnce();
} }
/** /** @test */
* @test
*/
public function deleteByShortCodeDeletesUrlWhenThresholdIsNotReached() public function deleteByShortCodeDeletesUrlWhenThresholdIsNotReached()
{ {
$service = $this->createService(true, 100); $service = $this->createService(true, 100);

View File

@ -32,9 +32,7 @@ class ShortUrlServiceTest extends TestCase
$this->service = new ShortUrlService($this->em->reveal()); $this->service = new ShortUrlService($this->em->reveal());
} }
/** /** @test */
* @test
*/
public function listedUrlsAreReturnedFromEntityManager() public function listedUrlsAreReturnedFromEntityManager()
{ {
$list = [ $list = [
@ -53,9 +51,7 @@ class ShortUrlServiceTest extends TestCase
$this->assertEquals(4, $list->getCurrentItemCount()); $this->assertEquals(4, $list->getCurrentItemCount());
} }
/** /** @test */
* @test
*/
public function exceptionIsThrownWhenSettingTagsOnInvalidShortcode() public function exceptionIsThrownWhenSettingTagsOnInvalidShortcode()
{ {
$shortCode = 'abc123'; $shortCode = 'abc123';
@ -68,9 +64,7 @@ class ShortUrlServiceTest extends TestCase
$this->service->setTagsByShortCode($shortCode); $this->service->setTagsByShortCode($shortCode);
} }
/** /** @test */
* @test
*/
public function providedTagsAreGetFromRepoAndSetToTheShortUrl() public function providedTagsAreGetFromRepoAndSetToTheShortUrl()
{ {
$shortUrl = $this->prophesize(ShortUrl::class); $shortUrl = $this->prophesize(ShortUrl::class);
@ -89,9 +83,7 @@ class ShortUrlServiceTest extends TestCase
$this->service->setTagsByShortCode($shortCode, ['foo', 'bar']); $this->service->setTagsByShortCode($shortCode, ['foo', 'bar']);
} }
/** /** @test */
* @test
*/
public function updateMetadataByShortCodeUpdatesProvidedData() public function updateMetadataByShortCodeUpdatesProvidedData()
{ {
$shortUrl = new ShortUrl(''); $shortUrl = new ShortUrl('');

View File

@ -27,9 +27,7 @@ class TagServiceTest extends TestCase
$this->service = new TagService($this->em->reveal()); $this->service = new TagService($this->em->reveal());
} }
/** /** @test */
* @test
*/
public function listTagsDelegatesOnRepository() public function listTagsDelegatesOnRepository()
{ {
$expected = [new Tag('foo'), new Tag('bar')]; $expected = [new Tag('foo'), new Tag('bar')];
@ -47,9 +45,7 @@ class TagServiceTest extends TestCase
$getRepo->shouldHaveBeenCalled(); $getRepo->shouldHaveBeenCalled();
} }
/** /** @test */
* @test
*/
public function deleteTagsDelegatesOnRepository() public function deleteTagsDelegatesOnRepository()
{ {
$repo = $this->prophesize(TagRepository::class); $repo = $this->prophesize(TagRepository::class);
@ -64,9 +60,7 @@ class TagServiceTest extends TestCase
$getRepo->shouldHaveBeenCalled(); $getRepo->shouldHaveBeenCalled();
} }
/** /** @test */
* @test
*/
public function createTagsPersistsEntities() public function createTagsPersistsEntities()
{ {
$repo = $this->prophesize(TagRepository::class); $repo = $this->prophesize(TagRepository::class);
@ -88,9 +82,7 @@ class TagServiceTest extends TestCase
$flush->shouldHaveBeenCalled(); $flush->shouldHaveBeenCalled();
} }
/** /** @test */
* @test
*/
public function renameInvalidTagThrowsException() public function renameInvalidTagThrowsException()
{ {
$repo = $this->prophesize(TagRepository::class); $repo = $this->prophesize(TagRepository::class);
@ -106,9 +98,7 @@ class TagServiceTest extends TestCase
$this->service->renameTag('foo', 'bar'); $this->service->renameTag('foo', 'bar');
} }
/** /** @test */
* @test
*/
public function renameValidTagChangesItsName() public function renameValidTagChangesItsName()
{ {
$expected = new Tag('foo'); $expected = new Tag('foo');

View File

@ -60,7 +60,7 @@ class UrlShortenerTest extends TestCase
$this->setUrlShortener(false); $this->setUrlShortener(false);
} }
public function setUrlShortener(bool $urlValidationEnabled): void private function setUrlShortener(bool $urlValidationEnabled): void
{ {
$this->urlShortener = new UrlShortener( $this->urlShortener = new UrlShortener(
$this->httpClient->reveal(), $this->httpClient->reveal(),
@ -69,9 +69,7 @@ class UrlShortenerTest extends TestCase
); );
} }
/** /** @test */
* @test
*/
public function urlIsProperlyShortened(): void public function urlIsProperlyShortened(): void
{ {
// 10 -> 0Q1Y // 10 -> 0Q1Y
@ -119,9 +117,7 @@ class UrlShortenerTest extends TestCase
); );
} }
/** /** @test */
* @test
*/
public function exceptionIsThrownWhenNonUniqueSlugIsProvided(): void public function exceptionIsThrownWhenNonUniqueSlugIsProvided(): void
{ {
$repo = $this->prophesize(ShortUrlRepository::class); $repo = $this->prophesize(ShortUrlRepository::class);
@ -143,7 +139,7 @@ class UrlShortenerTest extends TestCase
/** /**
* @test * @test
* @dataProvider provideExsitingShortUrls * @dataProvider provideExistingShortUrls
*/ */
public function existingShortUrlIsReturnedWhenRequested( public function existingShortUrlIsReturnedWhenRequested(
string $url, string $url,
@ -162,58 +158,54 @@ class UrlShortenerTest extends TestCase
$getRepo->shouldHaveBeenCalledOnce(); $getRepo->shouldHaveBeenCalledOnce();
} }
public function provideExsitingShortUrls(): array public function provideExistingShortUrls(): iterable
{ {
$url = 'http://foo.com'; $url = 'http://foo.com';
return [ yield [$url, [], ShortUrlMeta::createFromRawData(['findIfExists' => true]), new ShortUrl($url)];
[$url, [], ShortUrlMeta::createFromRawData(['findIfExists' => true]), new ShortUrl($url)], yield [$url, [], ShortUrlMeta::createFromRawData(
[$url, [], ShortUrlMeta::createFromRawData( ['findIfExists' => true, 'customSlug' => 'foo']
['findIfExists' => true, 'customSlug' => 'foo'] ), new ShortUrl($url)];
), new ShortUrl($url)], yield [
[ $url,
$url, ['foo', 'bar'],
['foo', 'bar'], ShortUrlMeta::createFromRawData(['findIfExists' => true]),
ShortUrlMeta::createFromRawData(['findIfExists' => true]), (new ShortUrl($url))->setTags(new ArrayCollection([new Tag('bar'), new Tag('foo')])),
(new ShortUrl($url))->setTags(new ArrayCollection([new Tag('bar'), new Tag('foo')])), ];
], yield [
[ $url,
$url, [],
[], ShortUrlMeta::createFromRawData(['findIfExists' => true, 'maxVisits' => 3]),
ShortUrlMeta::createFromRawData(['findIfExists' => true, 'maxVisits' => 3]), new ShortUrl($url, ShortUrlMeta::createFromRawData(['maxVisits' => 3])),
new ShortUrl($url, ShortUrlMeta::createFromRawData(['maxVisits' => 3])), ];
], yield [
[ $url,
$url, [],
[], ShortUrlMeta::createFromRawData(['findIfExists' => true, 'validSince' => Chronos::parse('2017-01-01')]),
ShortUrlMeta::createFromRawData(['findIfExists' => true, 'validSince' => Chronos::parse('2017-01-01')]), new ShortUrl($url, ShortUrlMeta::createFromRawData(['validSince' => Chronos::parse('2017-01-01')])),
new ShortUrl($url, ShortUrlMeta::createFromRawData(['validSince' => Chronos::parse('2017-01-01')])), ];
], yield [
[ $url,
$url, [],
[], ShortUrlMeta::createFromRawData(['findIfExists' => true, 'validUntil' => Chronos::parse('2017-01-01')]),
ShortUrlMeta::createFromRawData(['findIfExists' => true, 'validUntil' => Chronos::parse('2017-01-01')]), new ShortUrl($url, ShortUrlMeta::createFromRawData(['validUntil' => Chronos::parse('2017-01-01')])),
new ShortUrl($url, ShortUrlMeta::createFromRawData(['validUntil' => Chronos::parse('2017-01-01')])), ];
], yield [
[ $url,
$url, ['baz', 'foo', 'bar'],
['baz', 'foo', 'bar'], ShortUrlMeta::createFromRawData([
ShortUrlMeta::createFromRawData([ 'findIfExists' => true,
'findIfExists' => true, 'validUntil' => Chronos::parse('2017-01-01'),
'validUntil' => Chronos::parse('2017-01-01'), 'maxVisits' => 4,
'maxVisits' => 4, ]),
]), (new ShortUrl($url, ShortUrlMeta::createFromRawData([
(new ShortUrl($url, ShortUrlMeta::createFromRawData([ 'validUntil' => Chronos::parse('2017-01-01'),
'validUntil' => Chronos::parse('2017-01-01'), 'maxVisits' => 4,
'maxVisits' => 4, ])))->setTags(new ArrayCollection([new Tag('foo'), new Tag('bar'), new Tag('baz')])),
])))->setTags(new ArrayCollection([new Tag('foo'), new Tag('bar'), new Tag('baz')])),
],
]; ];
} }
/** /** @test */
* @test
*/
public function shortCodeIsProperlyParsed(): void public function shortCodeIsProperlyParsed(): void
{ {
$shortCode = '12C1c'; $shortCode = '12C1c';

View File

@ -67,9 +67,7 @@ class VisitServiceTest extends TestCase
$clear->shouldHaveBeenCalledTimes(count($unlocatedVisits)); $clear->shouldHaveBeenCalledTimes(count($unlocatedVisits));
} }
/** /** @test */
* @test
*/
public function visitsWhichCannotBeLocatedAreIgnored() public function visitsWhichCannotBeLocatedAreIgnored()
{ {
$unlocatedVisits = [ $unlocatedVisits = [

View File

@ -31,9 +31,7 @@ class VisitsTrackerTest extends TestCase
$this->visitsTracker = new VisitsTracker($this->em->reveal()); $this->visitsTracker = new VisitsTracker($this->em->reveal());
} }
/** /** @test */
* @test
*/
public function trackPersistsVisit() public function trackPersistsVisit()
{ {
$shortCode = '123ABC'; $shortCode = '123ABC';
@ -47,9 +45,7 @@ class VisitsTrackerTest extends TestCase
$this->visitsTracker->track($shortCode, Visitor::emptyInstance()); $this->visitsTracker->track($shortCode, Visitor::emptyInstance());
} }
/** /** @test */
* @test
*/
public function trackedIpAddressGetsObfuscated() public function trackedIpAddressGetsObfuscated()
{ {
$shortCode = '123ABC'; $shortCode = '123ABC';
@ -67,9 +63,7 @@ class VisitsTrackerTest extends TestCase
$this->visitsTracker->track($shortCode, new Visitor('', '', '4.3.2.1')); $this->visitsTracker->track($shortCode, new Visitor('', '', '4.3.2.1'));
} }
/** /** @test */
* @test
*/
public function infoReturnsVisistForCertainShortCode() public function infoReturnsVisistForCertainShortCode()
{ {
$shortCode = '123ABC'; $shortCode = '123ABC';

View File

@ -6,12 +6,12 @@ namespace ShlinkioApiTest\Shlink\Rest\Action;
use Cake\Chronos\Chronos; use Cake\Chronos\Chronos;
use GuzzleHttp\RequestOptions; use GuzzleHttp\RequestOptions;
use ShlinkioTest\Shlink\Common\ApiTest\ApiTestCase; use ShlinkioTest\Shlink\Common\ApiTest\ApiTestCase;
use function Functional\map;
use function range;
class CreateShortUrlActionTest extends ApiTestCase class CreateShortUrlActionTest extends ApiTestCase
{ {
/** /** @test */
* @test
*/
public function createsNewShortUrlWhenOnlyLongUrlIsProvided(): void public function createsNewShortUrlWhenOnlyLongUrlIsProvided(): void
{ {
$expectedKeys = ['shortCode', 'shortUrl', 'longUrl', 'dateCreated', 'visitsCount', 'tags']; $expectedKeys = ['shortCode', 'shortUrl', 'longUrl', 'dateCreated', 'visitsCount', 'tags'];
@ -23,9 +23,7 @@ class CreateShortUrlActionTest extends ApiTestCase
} }
} }
/** /** @test */
* @test
*/
public function createsNewShortUrlWithCustomSlug(): void public function createsNewShortUrlWithCustomSlug(): void
{ {
[$statusCode, $payload] = $this->createShortUrl(['customSlug' => 'my cool slug']); [$statusCode, $payload] = $this->createShortUrl(['customSlug' => 'my cool slug']);
@ -34,9 +32,7 @@ class CreateShortUrlActionTest extends ApiTestCase
$this->assertEquals('my-cool-slug', $payload['shortCode']); $this->assertEquals('my-cool-slug', $payload['shortCode']);
} }
/** /** @test */
* @test
*/
public function createsNewShortUrlWithTags(): void public function createsNewShortUrlWithTags(): void
{ {
[$statusCode, $payload] = $this->createShortUrl(['tags' => ['foo', 'bar', 'baz']]); [$statusCode, $payload] = $this->createShortUrl(['tags' => ['foo', 'bar', 'baz']]);
@ -65,16 +61,12 @@ class CreateShortUrlActionTest extends ApiTestCase
public function provideMaxVisits(): array public function provideMaxVisits(): array
{ {
return [ return map(range(1, 20), function (int $i) {
[1], return [$i];
[5], });
[3],
];
} }
/** /** @test */
* @test
*/
public function createsShortUrlWithValidSince(): void public function createsShortUrlWithValidSince(): void
{ {
[$statusCode, ['shortCode' => $shortCode]] = $this->createShortUrl([ [$statusCode, ['shortCode' => $shortCode]] = $this->createShortUrl([
@ -88,9 +80,7 @@ class CreateShortUrlActionTest extends ApiTestCase
$this->assertEquals(self::STATUS_NOT_FOUND, $lastResp->getStatusCode()); $this->assertEquals(self::STATUS_NOT_FOUND, $lastResp->getStatusCode());
} }
/** /** @test */
* @test
*/
public function createsShortUrlWithValidUntil(): void public function createsShortUrlWithValidUntil(): void
{ {
[$statusCode, ['shortCode' => $shortCode]] = $this->createShortUrl([ [$statusCode, ['shortCode' => $shortCode]] = $this->createShortUrl([
@ -110,7 +100,6 @@ class CreateShortUrlActionTest extends ApiTestCase
*/ */
public function returnsAnExistingShortUrlWhenRequested(array $body): void public function returnsAnExistingShortUrlWhenRequested(array $body): void
{ {
[$firstStatusCode, ['shortCode' => $firstShortCode]] = $this->createShortUrl($body); [$firstStatusCode, ['shortCode' => $firstShortCode]] = $this->createShortUrl($body);
$body['findIfExists'] = true; $body['findIfExists'] = true;
@ -121,26 +110,22 @@ class CreateShortUrlActionTest extends ApiTestCase
$this->assertEquals($firstShortCode, $secondShortCode); $this->assertEquals($firstShortCode, $secondShortCode);
} }
public function provideMatchingBodies(): array public function provideMatchingBodies(): iterable
{ {
$longUrl = 'https://www.alejandrocelaya.com'; $longUrl = 'https://www.alejandrocelaya.com';
return [ yield 'only long URL' => [['longUrl' => $longUrl]];
'only long URL' => [['longUrl' => $longUrl]], yield 'long URL and tags' => [['longUrl' => $longUrl, 'tags' => ['boo', 'far']]];
'long URL and tags' => [['longUrl' => $longUrl, 'tags' => ['boo', 'far']]], yield 'long URL and custom slug' => [['longUrl' => $longUrl, 'customSlug' => 'my cool slug']];
'long URL custom slug' => [['longUrl' => $longUrl, 'customSlug' => 'my cool slug']], yield 'several params' => [[
'several params' => [[ 'longUrl' => $longUrl,
'longUrl' => $longUrl, 'tags' => ['boo', 'far'],
'tags' => ['boo', 'far'], 'validSince' => Chronos::now()->toAtomString(),
'validSince' => Chronos::now()->toAtomString(), 'maxVisits' => 7,
'maxVisits' => 7, ]];
]],
];
} }
/** /** @test */
* @test
*/
public function returnsErrorWhenRequestingReturnExistingButCustomSlugIsInUse(): void public function returnsErrorWhenRequestingReturnExistingButCustomSlugIsInUse(): void
{ {
$longUrl = 'https://www.alejandrocelaya.com'; $longUrl = 'https://www.alejandrocelaya.com';
@ -156,9 +141,7 @@ class CreateShortUrlActionTest extends ApiTestCase
$this->assertEquals(self::STATUS_BAD_REQUEST, $secondStatusCode); $this->assertEquals(self::STATUS_BAD_REQUEST, $secondStatusCode);
} }
/** /** @test */
* @test
*/
public function createsNewShortUrlIfRequestedToFindButThereIsNoMatch(): void public function createsNewShortUrlIfRequestedToFindButThereIsNoMatch(): void
{ {
[$firstStatusCode, ['shortCode' => $firstShortCode]] = $this->createShortUrl([ [$firstStatusCode, ['shortCode' => $firstShortCode]] = $this->createShortUrl([

View File

@ -7,9 +7,7 @@ use ShlinkioTest\Shlink\Common\ApiTest\ApiTestCase;
class ListShortUrlsTest extends ApiTestCase class ListShortUrlsTest extends ApiTestCase
{ {
/** /** @test */
* @test
*/
public function shortUrlsAreProperlyListed() public function shortUrlsAreProperlyListed()
{ {
$resp = $this->callApiWithKey(self::METHOD_GET, '/short-urls'); $resp = $this->callApiWithKey(self::METHOD_GET, '/short-urls');

View File

@ -12,10 +12,8 @@ use function sprintf;
class AuthenticationTest extends ApiTestCase class AuthenticationTest extends ApiTestCase
{ {
/** /** @test */
* @test public function authorizationErrorIsReturnedIfNoApiKeyIsSent(): void
*/
public function authorizationErrorIsReturnedIfNoApiKeyIsSent()
{ {
$resp = $this->callApi(self::METHOD_GET, '/short-codes'); $resp = $this->callApi(self::METHOD_GET, '/short-codes');
['error' => $error, 'message' => $message] = $this->getJsonResponsePayload($resp); ['error' => $error, 'message' => $message] = $this->getJsonResponsePayload($resp);
@ -35,7 +33,7 @@ class AuthenticationTest extends ApiTestCase
* @test * @test
* @dataProvider provideInvalidApiKeys * @dataProvider provideInvalidApiKeys
*/ */
public function apiKeyErrorIsReturnedWhenProvidedApiKeyIsInvalid(string $apiKey) public function apiKeyErrorIsReturnedWhenProvidedApiKeyIsInvalid(string $apiKey): void
{ {
$resp = $this->callApi(self::METHOD_GET, '/short-codes', [ $resp = $this->callApi(self::METHOD_GET, '/short-codes', [
'headers' => [ 'headers' => [
@ -49,12 +47,10 @@ class AuthenticationTest extends ApiTestCase
$this->assertEquals('Provided API key does not exist or is invalid.', $message); $this->assertEquals('Provided API key does not exist or is invalid.', $message);
} }
public function provideInvalidApiKeys(): array public function provideInvalidApiKeys(): iterable
{ {
return [ yield 'key which does not exist' => ['invalid'];
'key which does not exist' => ['invalid'], yield 'key which is expired' => ['expired_api_key'];
'key which is expired' => ['expired_api_key'], yield 'key which is disabled' => ['disabled_api_key'];
'key which is disabled' => ['disabled_api_key'],
];
} }
} }

View File

@ -31,18 +31,14 @@ class AuthenticateActionTest extends TestCase
$this->action = new AuthenticateAction($this->apiKeyService->reveal(), $this->jwtService->reveal()); $this->action = new AuthenticateAction($this->apiKeyService->reveal(), $this->jwtService->reveal());
} }
/** /** @test */
* @test
*/
public function notProvidingAuthDataReturnsError() public function notProvidingAuthDataReturnsError()
{ {
$resp = $this->action->handle(new ServerRequest()); $resp = $this->action->handle(new ServerRequest());
$this->assertEquals(400, $resp->getStatusCode()); $this->assertEquals(400, $resp->getStatusCode());
} }
/** /** @test */
* @test
*/
public function properApiKeyReturnsTokenInResponse() public function properApiKeyReturnsTokenInResponse()
{ {
$this->apiKeyService->getByKey('foo')->willReturn((new ApiKey())->setId('5')) $this->apiKeyService->getByKey('foo')->willReturn((new ApiKey())->setId('5'))
@ -58,9 +54,7 @@ class AuthenticateActionTest extends TestCase
$this->assertTrue(strpos($response->getBody()->getContents(), '"token"') > 0); $this->assertTrue(strpos($response->getBody()->getContents(), '"token"') > 0);
} }
/** /** @test */
* @test
*/
public function invalidApiKeyReturnsErrorResponse() public function invalidApiKeyReturnsErrorResponse()
{ {
$this->apiKeyService->getByKey('foo')->willReturn((new ApiKey())->disable()) $this->apiKeyService->getByKey('foo')->willReturn((new ApiKey())->disable())

View File

@ -21,9 +21,7 @@ class HealthActionFactoryTest extends TestCase
$this->factory = new Action\HealthActionFactory(); $this->factory = new Action\HealthActionFactory();
} }
/** /** @test */
* @test
*/
public function serviceIsCreatedExtractingConnectionFromEntityManager() public function serviceIsCreatedExtractingConnectionFromEntityManager()
{ {
$em = $this->prophesize(EntityManager::class); $em = $this->prophesize(EntityManager::class);

View File

@ -25,9 +25,7 @@ class HealthActionTest extends TestCase
$this->action = new HealthAction($this->conn->reveal(), new AppOptions(['version' => '1.2.3'])); $this->action = new HealthAction($this->conn->reveal(), new AppOptions(['version' => '1.2.3']));
} }
/** /** @test */
* @test
*/
public function passResponseIsReturnedWhenConnectionSucceeds() public function passResponseIsReturnedWhenConnectionSucceeds()
{ {
$ping = $this->conn->ping()->willReturn(true); $ping = $this->conn->ping()->willReturn(true);
@ -47,9 +45,7 @@ class HealthActionTest extends TestCase
$ping->shouldHaveBeenCalledOnce(); $ping->shouldHaveBeenCalledOnce();
} }
/** /** @test */
* @test
*/
public function failResponseIsReturnedWhenConnectionFails() public function failResponseIsReturnedWhenConnectionFails()
{ {
$ping = $this->conn->ping()->willReturn(false); $ping = $this->conn->ping()->willReturn(false);
@ -69,9 +65,7 @@ class HealthActionTest extends TestCase
$ping->shouldHaveBeenCalledOnce(); $ping->shouldHaveBeenCalledOnce();
} }
/** /** @test */
* @test
*/
public function failResponseIsReturnedWhenConnectionThrowsException() public function failResponseIsReturnedWhenConnectionThrowsException()
{ {
$ping = $this->conn->ping()->willThrow(Exception::class); $ping = $this->conn->ping()->willThrow(Exception::class);

View File

@ -34,18 +34,14 @@ class CreateShortUrlActionTest extends TestCase
]); ]);
} }
/** /** @test */
* @test
*/
public function missingLongUrlParamReturnsError() public function missingLongUrlParamReturnsError()
{ {
$response = $this->action->handle(new ServerRequest()); $response = $this->action->handle(new ServerRequest());
$this->assertEquals(400, $response->getStatusCode()); $this->assertEquals(400, $response->getStatusCode());
} }
/** /** @test */
* @test
*/
public function properShortcodeConversionReturnsData() public function properShortcodeConversionReturnsData()
{ {
$this->urlShortener->urlToShortCode(Argument::type(Uri::class), Argument::type('array'), Argument::cetera()) $this->urlShortener->urlToShortCode(Argument::type(Uri::class), Argument::type('array'), Argument::cetera())
@ -62,9 +58,7 @@ class CreateShortUrlActionTest extends TestCase
$this->assertTrue(strpos($response->getBody()->getContents(), 'http://foo.com/abc123') > 0); $this->assertTrue(strpos($response->getBody()->getContents(), 'http://foo.com/abc123') > 0);
} }
/** /** @test */
* @test
*/
public function anInvalidUrlReturnsError() public function anInvalidUrlReturnsError()
{ {
$this->urlShortener->urlToShortCode(Argument::type(Uri::class), Argument::type('array'), Argument::cetera()) $this->urlShortener->urlToShortCode(Argument::type(Uri::class), Argument::type('array'), Argument::cetera())
@ -79,9 +73,7 @@ class CreateShortUrlActionTest extends TestCase
$this->assertTrue(strpos($response->getBody()->getContents(), RestUtils::INVALID_URL_ERROR) > 0); $this->assertTrue(strpos($response->getBody()->getContents(), RestUtils::INVALID_URL_ERROR) > 0);
} }
/** /** @test */
* @test
*/
public function nonUniqueSlugReturnsError() public function nonUniqueSlugReturnsError()
{ {
$this->urlShortener->urlToShortCode( $this->urlShortener->urlToShortCode(
@ -100,9 +92,7 @@ class CreateShortUrlActionTest extends TestCase
$this->assertStringContainsString(RestUtils::INVALID_SLUG_ERROR, (string) $response->getBody()); $this->assertStringContainsString(RestUtils::INVALID_SLUG_ERROR, (string) $response->getBody());
} }
/** /** @test */
* @test
*/
public function aGenericExceptionWillReturnError() public function aGenericExceptionWillReturnError()
{ {
$this->urlShortener->urlToShortCode(Argument::type(Uri::class), Argument::type('array'), Argument::cetera()) $this->urlShortener->urlToShortCode(Argument::type(Uri::class), Argument::type('array'), Argument::cetera())

View File

@ -27,10 +27,8 @@ class DeleteShortUrlActionTest extends TestCase
$this->action = new DeleteShortUrlAction($this->service->reveal()); $this->action = new DeleteShortUrlAction($this->service->reveal());
} }
/** /** @test */
* @test public function emptyResponseIsReturnedIfProperlyDeleted(): void
*/
public function emptyResponseIsReturnedIfProperlyDeleted()
{ {
$deleteByShortCode = $this->service->deleteByShortCode(Argument::any())->will(function () { $deleteByShortCode = $this->service->deleteByShortCode(Argument::any())->will(function () {
}); });
@ -45,7 +43,7 @@ class DeleteShortUrlActionTest extends TestCase
* @test * @test
* @dataProvider provideExceptions * @dataProvider provideExceptions
*/ */
public function returnsErrorResponseInCaseOfException(Throwable $e, string $error, int $statusCode) public function returnsErrorResponseInCaseOfException(Throwable $e, string $error, int $statusCode): void
{ {
$deleteByShortCode = $this->service->deleteByShortCode(Argument::any())->willThrow($e); $deleteByShortCode = $this->service->deleteByShortCode(Argument::any())->willThrow($e);
@ -58,11 +56,13 @@ class DeleteShortUrlActionTest extends TestCase
$deleteByShortCode->shouldHaveBeenCalledOnce(); $deleteByShortCode->shouldHaveBeenCalledOnce();
} }
public function provideExceptions(): array public function provideExceptions(): iterable
{ {
return [ yield 'not found' => [new Exception\InvalidShortCodeException(), RestUtils::INVALID_SHORTCODE_ERROR, 404];
[new Exception\InvalidShortCodeException(), RestUtils::INVALID_SHORTCODE_ERROR, 404], yield 'bad request' => [
[new Exception\DeleteShortUrlException(5), RestUtils::INVALID_SHORTCODE_DELETION_ERROR, 400], new Exception\DeleteShortUrlException(5),
RestUtils::INVALID_SHORTCODE_DELETION_ERROR,
400,
]; ];
} }
} }

View File

@ -27,9 +27,7 @@ class EditShortUrlActionTest extends TestCase
$this->action = new EditShortUrlAction($this->shortUrlService->reveal()); $this->action = new EditShortUrlAction($this->shortUrlService->reveal());
} }
/** /** @test */
* @test
*/
public function invalidDataReturnsError() public function invalidDataReturnsError()
{ {
$request = (new ServerRequest())->withParsedBody([ $request = (new ServerRequest())->withParsedBody([
@ -45,9 +43,7 @@ class EditShortUrlActionTest extends TestCase
$this->assertEquals('Provided data is invalid.', $payload['message']); $this->assertEquals('Provided data is invalid.', $payload['message']);
} }
/** /** @test */
* @test
*/
public function incorrectShortCodeReturnsError() public function incorrectShortCodeReturnsError()
{ {
$request = (new ServerRequest())->withAttribute('shortCode', 'abc123') $request = (new ServerRequest())->withAttribute('shortCode', 'abc123')
@ -68,9 +64,7 @@ class EditShortUrlActionTest extends TestCase
$updateMeta->shouldHaveBeenCalled(); $updateMeta->shouldHaveBeenCalled();
} }
/** /** @test */
* @test
*/
public function correctShortCodeReturnsSuccess() public function correctShortCodeReturnsSuccess()
{ {
$request = (new ServerRequest())->withAttribute('shortCode', 'abc123') $request = (new ServerRequest())->withAttribute('shortCode', 'abc123')

View File

@ -24,18 +24,14 @@ class EditShortUrlTagsActionTest extends TestCase
$this->action = new EditShortUrlTagsAction($this->shortUrlService->reveal()); $this->action = new EditShortUrlTagsAction($this->shortUrlService->reveal());
} }
/** /** @test */
* @test
*/
public function notProvidingTagsReturnsError() public function notProvidingTagsReturnsError()
{ {
$response = $this->action->handle((new ServerRequest())->withAttribute('shortCode', 'abc123')); $response = $this->action->handle((new ServerRequest())->withAttribute('shortCode', 'abc123'));
$this->assertEquals(400, $response->getStatusCode()); $this->assertEquals(400, $response->getStatusCode());
} }
/** /** @test */
* @test
*/
public function anInvalidShortCodeReturnsNotFound() public function anInvalidShortCodeReturnsNotFound()
{ {
$shortCode = 'abc123'; $shortCode = 'abc123';
@ -49,9 +45,7 @@ class EditShortUrlTagsActionTest extends TestCase
$this->assertEquals(404, $response->getStatusCode()); $this->assertEquals(404, $response->getStatusCode());
} }
/** /** @test */
* @test
*/
public function tagsListIsReturnedIfCorrectShortCodeIsProvided() public function tagsListIsReturnedIfCorrectShortCodeIsProvided()
{ {
$shortCode = 'abc123'; $shortCode = 'abc123';

View File

@ -28,9 +28,7 @@ class ListShortUrlsActionTest extends TestCase
]); ]);
} }
/** /** @test */
* @test
*/
public function properListReturnsSuccessResponse() public function properListReturnsSuccessResponse()
{ {
$page = 3; $page = 3;
@ -43,9 +41,7 @@ class ListShortUrlsActionTest extends TestCase
$this->assertEquals(200, $response->getStatusCode()); $this->assertEquals(200, $response->getStatusCode());
} }
/** /** @test */
* @test
*/
public function anExceptionsReturnsErrorResponse() public function anExceptionsReturnsErrorResponse()
{ {
$page = 3; $page = 3;

View File

@ -28,9 +28,7 @@ class ResolveShortUrlActionTest extends TestCase
$this->action = new ResolveShortUrlAction($this->urlShortener->reveal(), []); $this->action = new ResolveShortUrlAction($this->urlShortener->reveal(), []);
} }
/** /** @test */
* @test
*/
public function incorrectShortCodeReturnsError() public function incorrectShortCodeReturnsError()
{ {
$shortCode = 'abc123'; $shortCode = 'abc123';
@ -43,9 +41,7 @@ class ResolveShortUrlActionTest extends TestCase
$this->assertTrue(strpos($response->getBody()->getContents(), RestUtils::INVALID_ARGUMENT_ERROR) > 0); $this->assertTrue(strpos($response->getBody()->getContents(), RestUtils::INVALID_ARGUMENT_ERROR) > 0);
} }
/** /** @test */
* @test
*/
public function correctShortCodeReturnsSuccess() public function correctShortCodeReturnsSuccess()
{ {
$shortCode = 'abc123'; $shortCode = 'abc123';
@ -59,9 +55,7 @@ class ResolveShortUrlActionTest extends TestCase
$this->assertTrue(strpos($response->getBody()->getContents(), 'http://domain.com/foo/bar') > 0); $this->assertTrue(strpos($response->getBody()->getContents(), 'http://domain.com/foo/bar') > 0);
} }
/** /** @test */
* @test
*/
public function invalidShortCodeExceptionReturnsError() public function invalidShortCodeExceptionReturnsError()
{ {
$shortCode = 'abc123'; $shortCode = 'abc123';
@ -74,9 +68,7 @@ class ResolveShortUrlActionTest extends TestCase
$this->assertTrue(strpos($response->getBody()->getContents(), RestUtils::INVALID_SHORTCODE_ERROR) > 0); $this->assertTrue(strpos($response->getBody()->getContents(), RestUtils::INVALID_SHORTCODE_ERROR) > 0);
} }
/** /** @test */
* @test
*/
public function unexpectedExceptionWillReturnError() public function unexpectedExceptionWillReturnError()
{ {
$shortCode = 'abc123'; $shortCode = 'abc123';

View File

@ -40,9 +40,7 @@ class SingleStepCreateShortUrlActionTest extends TestCase
); );
} }
/** /** @test */
* @test
*/
public function errorResponseIsReturnedIfInvalidApiKeyIsProvided() public function errorResponseIsReturnedIfInvalidApiKeyIsProvided()
{ {
$request = (new ServerRequest())->withQueryParams(['apiKey' => 'abc123']); $request = (new ServerRequest())->withQueryParams(['apiKey' => 'abc123']);
@ -58,9 +56,7 @@ class SingleStepCreateShortUrlActionTest extends TestCase
$findApiKey->shouldHaveBeenCalled(); $findApiKey->shouldHaveBeenCalled();
} }
/** /** @test */
* @test
*/
public function errorResponseIsReturnedIfNoUrlIsProvided() public function errorResponseIsReturnedIfNoUrlIsProvided()
{ {
$request = (new ServerRequest())->withQueryParams(['apiKey' => 'abc123']); $request = (new ServerRequest())->withQueryParams(['apiKey' => 'abc123']);
@ -76,9 +72,7 @@ class SingleStepCreateShortUrlActionTest extends TestCase
$findApiKey->shouldHaveBeenCalled(); $findApiKey->shouldHaveBeenCalled();
} }
/** /** @test */
* @test
*/
public function properDataIsPassedWhenGeneratingShortCode() public function properDataIsPassedWhenGeneratingShortCode()
{ {
$request = (new ServerRequest())->withQueryParams([ $request = (new ServerRequest())->withQueryParams([

View File

@ -5,7 +5,6 @@ namespace ShlinkioTest\Shlink\Rest\Action\Tag;
use Doctrine\Common\Collections\ArrayCollection; use Doctrine\Common\Collections\ArrayCollection;
use PHPUnit\Framework\TestCase; use PHPUnit\Framework\TestCase;
use Prophecy\Prophecy\MethodProphecy;
use Prophecy\Prophecy\ObjectProphecy; use Prophecy\Prophecy\ObjectProphecy;
use Shlinkio\Shlink\Core\Service\Tag\TagServiceInterface; use Shlinkio\Shlink\Core\Service\Tag\TagServiceInterface;
use Shlinkio\Shlink\Rest\Action\Tag\CreateTagsAction; use Shlinkio\Shlink\Rest\Action\Tag\CreateTagsAction;
@ -27,12 +26,10 @@ class CreateTagsActionTest extends TestCase
/** /**
* @test * @test
* @dataProvider provideTags * @dataProvider provideTags
* @param array|null $tags
*/ */
public function processDelegatesIntoService($tags) public function processDelegatesIntoService(?array $tags): void
{ {
$request = (new ServerRequest())->withParsedBody(['tags' => $tags]); $request = (new ServerRequest())->withParsedBody(['tags' => $tags]);
/** @var MethodProphecy $deleteTags */
$deleteTags = $this->tagService->createTags($tags ?: [])->willReturn(new ArrayCollection()); $deleteTags = $this->tagService->createTags($tags ?: [])->willReturn(new ArrayCollection());
$response = $this->action->handle($request); $response = $this->action->handle($request);
@ -41,13 +38,11 @@ class CreateTagsActionTest extends TestCase
$deleteTags->shouldHaveBeenCalled(); $deleteTags->shouldHaveBeenCalled();
} }
public function provideTags() public function provideTags(): iterable
{ {
return [ yield 'three tags' => [['foo', 'bar', 'baz']];
[['foo', 'bar', 'baz']], yield 'two tags' => [['some', 'thing']];
[['some', 'thing']], yield 'null tags' => [null];
[null], yield 'empty tags' => [[]];
[[]],
];
} }
} }

View File

@ -26,9 +26,8 @@ class DeleteTagsActionTest extends TestCase
/** /**
* @test * @test
* @dataProvider provideTags * @dataProvider provideTags
* @param array|null $tags
*/ */
public function processDelegatesIntoService($tags) public function processDelegatesIntoService(?array $tags): void
{ {
$request = (new ServerRequest())->withQueryParams(['tags' => $tags]); $request = (new ServerRequest())->withQueryParams(['tags' => $tags]);
/** @var MethodProphecy $deleteTags */ /** @var MethodProphecy $deleteTags */
@ -40,13 +39,11 @@ class DeleteTagsActionTest extends TestCase
$deleteTags->shouldHaveBeenCalled(); $deleteTags->shouldHaveBeenCalled();
} }
public function provideTags() public function provideTags(): iterable
{ {
return [ yield 'three tags' => [['foo', 'bar', 'baz']];
[['foo', 'bar', 'baz']], yield 'two tags' => [['some', 'thing']];
[['some', 'thing']], yield 'null tags' => [null];
[null], yield 'empty tags' => [[]];
[[]],
];
} }
} }

View File

@ -25,9 +25,7 @@ class ListTagsActionTest extends TestCase
$this->action = new ListTagsAction($this->tagService->reveal()); $this->action = new ListTagsAction($this->tagService->reveal());
} }
/** /** @test */
* @test
*/
public function returnsDataFromService() public function returnsDataFromService()
{ {
/** @var MethodProphecy $listTags */ /** @var MethodProphecy $listTags */

View File

@ -28,9 +28,8 @@ class UpdateTagActionTest extends TestCase
/** /**
* @test * @test
* @dataProvider provideParams * @dataProvider provideParams
* @param array $bodyParams
*/ */
public function whenInvalidParamsAreProvidedAnErrorIsReturned(array $bodyParams) public function whenInvalidParamsAreProvidedAnErrorIsReturned(array $bodyParams): void
{ {
$request = (new ServerRequest())->withParsedBody($bodyParams); $request = (new ServerRequest())->withParsedBody($bodyParams);
$resp = $this->action->handle($request); $resp = $this->action->handle($request);
@ -38,19 +37,15 @@ class UpdateTagActionTest extends TestCase
$this->assertEquals(400, $resp->getStatusCode()); $this->assertEquals(400, $resp->getStatusCode());
} }
public function provideParams() public function provideParams(): iterable
{ {
return [ yield 'old name only' => [['oldName' => 'foo']];
[['oldName' => 'foo']], yield 'new name only' => [['newName' => 'foo']];
[['newName' => 'foo']], yield 'no params' => [[]];
[[]],
];
} }
/** /** @test */
* @test public function requestingInvalidTagReturnsError(): void
*/
public function requestingInvalidTagReturnsError()
{ {
$request = (new ServerRequest())->withParsedBody([ $request = (new ServerRequest())->withParsedBody([
'oldName' => 'foo', 'oldName' => 'foo',
@ -65,10 +60,8 @@ class UpdateTagActionTest extends TestCase
$rename->shouldHaveBeenCalled(); $rename->shouldHaveBeenCalled();
} }
/** /** @test */
* @test public function correctInvocationRenamesTag(): void
*/
public function correctInvocationRenamesTag()
{ {
$request = (new ServerRequest())->withParsedBody([ $request = (new ServerRequest())->withParsedBody([
'oldName' => 'foo', 'oldName' => 'foo',

View File

@ -29,9 +29,7 @@ class GetVisitsActionTest extends TestCase
$this->action = new GetVisitsAction($this->visitsTracker->reveal()); $this->action = new GetVisitsAction($this->visitsTracker->reveal());
} }
/** /** @test */
* @test
*/
public function providingCorrectShortCodeReturnsVisits() public function providingCorrectShortCodeReturnsVisits()
{ {
$shortCode = 'abc123'; $shortCode = 'abc123';
@ -43,9 +41,7 @@ class GetVisitsActionTest extends TestCase
$this->assertEquals(200, $response->getStatusCode()); $this->assertEquals(200, $response->getStatusCode());
} }
/** /** @test */
* @test
*/
public function providingInvalidShortCodeReturnsError() public function providingInvalidShortCodeReturnsError()
{ {
$shortCode = 'abc123'; $shortCode = 'abc123';
@ -57,9 +53,7 @@ class GetVisitsActionTest extends TestCase
$this->assertEquals(404, $response->getStatusCode()); $this->assertEquals(404, $response->getStatusCode());
} }
/** /** @test */
* @test
*/
public function paramsAreReadFromQuery() public function paramsAreReadFromQuery()
{ {
$shortCode = 'abc123'; $shortCode = 'abc123';

View File

@ -18,9 +18,7 @@ class AuthenticationPluginManagerFactoryTest extends TestCase
$this->factory = new AuthenticationPluginManagerFactory(); $this->factory = new AuthenticationPluginManagerFactory();
} }
/** /** @test */
* @test
*/
public function serviceIsProperlyCreated() public function serviceIsProperlyCreated()
{ {
$instance = $this->factory->__invoke(new ServiceManager(['services' => [ $instance = $this->factory->__invoke(new ServiceManager(['services' => [

View File

@ -25,9 +25,7 @@ class JWTServiceTest extends TestCase
])); ]));
} }
/** /** @test */
* @test
*/
public function tokenIsProperlyCreated() public function tokenIsProperlyCreated()
{ {
$id = '34'; $id = '34';
@ -40,9 +38,7 @@ class JWTServiceTest extends TestCase
$this->assertEquals('ShlinkTest:v10000.3.1', $payload['iss']); $this->assertEquals('ShlinkTest:v10000.3.1', $payload['iss']);
} }
/** /** @test */
* @test
*/
public function refreshIncreasesExpiration() public function refreshIncreasesExpiration()
{ {
$originalLifetime = 10; $originalLifetime = 10;
@ -55,25 +51,19 @@ class JWTServiceTest extends TestCase
$this->assertGreaterThan($originalPayload['exp'], $newPayload['exp']); $this->assertGreaterThan($originalPayload['exp'], $newPayload['exp']);
} }
/** /** @test */
* @test
*/
public function verifyReturnsTrueWhenTheTokenIsCorrect() public function verifyReturnsTrueWhenTheTokenIsCorrect()
{ {
$this->assertTrue($this->service->verify(JWT::encode([], 'foo'))); $this->assertTrue($this->service->verify(JWT::encode([], 'foo')));
} }
/** /** @test */
* @test
*/
public function verifyReturnsFalseWhenTheTokenIsCorrect() public function verifyReturnsFalseWhenTheTokenIsCorrect()
{ {
$this->assertFalse($this->service->verify('invalidToken')); $this->assertFalse($this->service->verify('invalidToken'));
} }
/** /** @test */
* @test
*/
public function getPayloadWorksWithCorrectTokens() public function getPayloadWorksWithCorrectTokens()
{ {
$originalPayload = [ $originalPayload = [

View File

@ -25,9 +25,7 @@ class ApiKeyHeaderPluginTest extends TestCase
$this->plugin = new ApiKeyHeaderPlugin($this->apiKeyService->reveal()); $this->plugin = new ApiKeyHeaderPlugin($this->apiKeyService->reveal());
} }
/** /** @test */
* @test
*/
public function verifyThrowsExceptionWhenApiKeyIsNotValid() public function verifyThrowsExceptionWhenApiKeyIsNotValid()
{ {
$apiKey = 'abc-ABC'; $apiKey = 'abc-ABC';
@ -40,9 +38,7 @@ class ApiKeyHeaderPluginTest extends TestCase
$this->plugin->verify($this->createRequest($apiKey)); $this->plugin->verify($this->createRequest($apiKey));
} }
/** /** @test */
* @test
*/
public function verifyDoesNotThrowExceptionWhenApiKeyIsValid() public function verifyDoesNotThrowExceptionWhenApiKeyIsValid()
{ {
$apiKey = 'abc-ABC'; $apiKey = 'abc-ABC';
@ -53,9 +49,7 @@ class ApiKeyHeaderPluginTest extends TestCase
$check->shouldHaveBeenCalledOnce(); $check->shouldHaveBeenCalledOnce();
} }
/** /** @test */
* @test
*/
public function updateReturnsResponseAsIs() public function updateReturnsResponseAsIs()
{ {
$apiKey = 'abc-ABC'; $apiKey = 'abc-ABC';

View File

@ -25,9 +25,7 @@ class AuthorizationHeaderPluginTest extends TestCase
$this->plugin = new AuthorizationHeaderPlugin($this->jwtService->reveal()); $this->plugin = new AuthorizationHeaderPlugin($this->jwtService->reveal());
} }
/** /** @test */
* @test
*/
public function verifyAnAuthorizationWithoutBearerTypeThrowsException() public function verifyAnAuthorizationWithoutBearerTypeThrowsException()
{ {
$authToken = 'ABC-abc'; $authToken = 'ABC-abc';
@ -45,9 +43,7 @@ class AuthorizationHeaderPluginTest extends TestCase
$this->plugin->verify($request); $this->plugin->verify($request);
} }
/** /** @test */
* @test
*/
public function verifyAnAuthorizationWithWrongTypeThrowsException() public function verifyAnAuthorizationWithWrongTypeThrowsException()
{ {
$authToken = 'Basic ABC-abc'; $authToken = 'Basic ABC-abc';
@ -64,9 +60,7 @@ class AuthorizationHeaderPluginTest extends TestCase
$this->plugin->verify($request); $this->plugin->verify($request);
} }
/** /** @test */
* @test
*/
public function verifyAnExpiredTokenThrowsException() public function verifyAnExpiredTokenThrowsException()
{ {
$authToken = 'Bearer ABC-abc'; $authToken = 'Bearer ABC-abc';
@ -88,9 +82,7 @@ class AuthorizationHeaderPluginTest extends TestCase
$jwtVerify->shouldHaveBeenCalledOnce(); $jwtVerify->shouldHaveBeenCalledOnce();
} }
/** /** @test */
* @test
*/
public function verifyValidTokenDoesNotThrowException() public function verifyValidTokenDoesNotThrowException()
{ {
$authToken = 'Bearer ABC-abc'; $authToken = 'Bearer ABC-abc';
@ -105,9 +97,7 @@ class AuthorizationHeaderPluginTest extends TestCase
$jwtVerify->shouldHaveBeenCalledOnce(); $jwtVerify->shouldHaveBeenCalledOnce();
} }
/** /** @test */
* @test
*/
public function updateReturnsAnUpdatedResponseWithNewJwt() public function updateReturnsAnUpdatedResponseWithNewJwt()
{ {
$authToken = 'Bearer ABC-abc'; $authToken = 'Bearer ABC-abc';

View File

@ -28,10 +28,8 @@ class RequestToAuthPluginTest extends TestCase
$this->requestToPlugin = new RequestToHttpAuthPlugin($this->pluginManager->reveal()); $this->requestToPlugin = new RequestToHttpAuthPlugin($this->pluginManager->reveal());
} }
/** /** @test */
* @test public function exceptionIsFoundWhenNoneOfTheSupportedMethodsIsFound(): void
*/
public function exceptionIsFoundWhenNoneOfTheSupportedMethodsIsFound()
{ {
$request = new ServerRequest(); $request = new ServerRequest();
@ -48,7 +46,7 @@ class RequestToAuthPluginTest extends TestCase
* @test * @test
* @dataProvider provideHeaders * @dataProvider provideHeaders
*/ */
public function properPluginIsFetchedWhenAnyAuthTypeIsFound(array $headers, string $expectedHeader) public function properPluginIsFetchedWhenAnyAuthTypeIsFound(array $headers, string $expectedHeader): void
{ {
$request = new ServerRequest(); $request = new ServerRequest();
foreach ($headers as $header => $value) { foreach ($headers as $header => $value) {
@ -63,19 +61,17 @@ class RequestToAuthPluginTest extends TestCase
$getPlugin->shouldHaveBeenCalledOnce(); $getPlugin->shouldHaveBeenCalledOnce();
} }
public function provideHeaders(): array public function provideHeaders(): iterable
{ {
return [ yield 'API key header only' => [[
'API key header only' => [[ ApiKeyHeaderPlugin::HEADER_NAME => 'foobar',
ApiKeyHeaderPlugin::HEADER_NAME => 'foobar', ], ApiKeyHeaderPlugin::HEADER_NAME];
], ApiKeyHeaderPlugin::HEADER_NAME], yield 'Authorization header only' => [[
'Authorization header only' => [[ AuthorizationHeaderPlugin::HEADER_NAME => 'foobar',
AuthorizationHeaderPlugin::HEADER_NAME => 'foobar', ], AuthorizationHeaderPlugin::HEADER_NAME];
], AuthorizationHeaderPlugin::HEADER_NAME], yield 'Both headers' => [[
'Both headers' => [[ AuthorizationHeaderPlugin::HEADER_NAME => 'foobar',
AuthorizationHeaderPlugin::HEADER_NAME => 'foobar', ApiKeyHeaderPlugin::HEADER_NAME => 'foobar',
ApiKeyHeaderPlugin::HEADER_NAME => 'foobar', ], ApiKeyHeaderPlugin::HEADER_NAME];
], ApiKeyHeaderPlugin::HEADER_NAME],
];
} }
} }

View File

@ -16,9 +16,7 @@ class ConfigProviderTest extends TestCase
$this->configProvider = new ConfigProvider(); $this->configProvider = new ConfigProvider();
} }
/** /** @test */
* @test
*/
public function properConfigIsReturned() public function properConfigIsReturned()
{ {
$config = $this->configProvider->__invoke(); $config = $this->configProvider->__invoke();

View File

@ -23,7 +23,7 @@ class AuthenticationExceptionTest extends TestCase
$this->assertEquals('The token has expired.', $e->getMessage()); $this->assertEquals('The token has expired.', $e->getMessage());
} }
public function providePrev() public function providePrev(): iterable
{ {
yield 'with previous exception' => [new Exception('Prev')]; yield 'with previous exception' => [new Exception('Prev')];
yield 'without previous exception' => [null]; yield 'without previous exception' => [null];

View File

@ -21,6 +21,7 @@ use Shlinkio\Shlink\Rest\Exception\NoAuthenticationException;
use Shlinkio\Shlink\Rest\Exception\VerifyAuthenticationException; use Shlinkio\Shlink\Rest\Exception\VerifyAuthenticationException;
use Shlinkio\Shlink\Rest\Middleware\AuthenticationMiddleware; use Shlinkio\Shlink\Rest\Middleware\AuthenticationMiddleware;
use Shlinkio\Shlink\Rest\Util\RestUtils; use Shlinkio\Shlink\Rest\Util\RestUtils;
use Throwable;
use Zend\Diactoros\Response; use Zend\Diactoros\Response;
use Zend\Diactoros\ServerRequest; use Zend\Diactoros\ServerRequest;
use Zend\Expressive\Router\Route; use Zend\Expressive\Router\Route;
@ -49,7 +50,7 @@ class AuthenticationMiddlewareTest extends TestCase
* @test * @test
* @dataProvider provideWhitelistedRequests * @dataProvider provideWhitelistedRequests
*/ */
public function someWhiteListedSituationsFallbackToNextMiddleware(ServerRequestInterface $request) public function someWhiteListedSituationsFallbackToNextMiddleware(ServerRequestInterface $request): void
{ {
$handler = $this->prophesize(RequestHandlerInterface::class); $handler = $this->prophesize(RequestHandlerInterface::class);
$handle = $handler->handle($request)->willReturn(new Response()); $handle = $handler->handle($request)->willReturn(new Response());
@ -63,34 +64,32 @@ class AuthenticationMiddlewareTest extends TestCase
$fromRequest->shouldNotHaveBeenCalled(); $fromRequest->shouldNotHaveBeenCalled();
} }
public function provideWhitelistedRequests(): array public function provideWhitelistedRequests(): iterable
{ {
$dummyMiddleware = $this->getDummyMiddleware(); $dummyMiddleware = $this->getDummyMiddleware();
return [ yield 'with no route result' => [new ServerRequest()];
'with no route result' => [new ServerRequest()], yield 'with failure route result' => [(new ServerRequest())->withAttribute(
'with failure route result' => [(new ServerRequest())->withAttribute( RouteResult::class,
RouteResult::class, RouteResult::fromRouteFailure([RequestMethodInterface::METHOD_GET])
RouteResult::fromRouteFailure([RequestMethodInterface::METHOD_GET]) )];
)], yield 'with whitelisted route' => [(new ServerRequest())->withAttribute(
'with whitelisted route' => [(new ServerRequest())->withAttribute( RouteResult::class,
RouteResult::class, RouteResult::fromRoute(
RouteResult::fromRoute( new Route('foo', $dummyMiddleware, Route::HTTP_METHOD_ANY, AuthenticateAction::class)
new Route('foo', $dummyMiddleware, Route::HTTP_METHOD_ANY, AuthenticateAction::class) )
) )];
)], yield 'with OPTIONS method' => [(new ServerRequest())->withAttribute(
'with OPTIONS method' => [(new ServerRequest())->withAttribute( RouteResult::class,
RouteResult::class, RouteResult::fromRoute(new Route('bar', $dummyMiddleware), [])
RouteResult::fromRoute(new Route('bar', $dummyMiddleware), []) )->withMethod(RequestMethodInterface::METHOD_OPTIONS)];
)->withMethod(RequestMethodInterface::METHOD_OPTIONS)],
];
} }
/** /**
* @test * @test
* @dataProvider provideExceptions * @dataProvider provideExceptions
*/ */
public function errorIsReturnedWhenNoValidAuthIsProvided($e) public function errorIsReturnedWhenNoValidAuthIsProvided(Throwable $e): void
{ {
$request = (new ServerRequest())->withAttribute( $request = (new ServerRequest())->withAttribute(
RouteResult::class, RouteResult::class,
@ -110,19 +109,15 @@ class AuthenticationMiddlewareTest extends TestCase
$fromRequest->shouldHaveBeenCalledOnce(); $fromRequest->shouldHaveBeenCalledOnce();
} }
public function provideExceptions(): array public function provideExceptions(): iterable
{ {
return [ yield 'container exception' => [new class extends Exception implements ContainerExceptionInterface {
[new class extends Exception implements ContainerExceptionInterface { }];
}], yield 'authentication exception' => [NoAuthenticationException::fromExpectedTypes([])];
[NoAuthenticationException::fromExpectedTypes([])],
];
} }
/** /** @test */
* @test public function errorIsReturnedWhenVerificationFails(): void
*/
public function errorIsReturnedWhenVerificationFails()
{ {
$request = (new ServerRequest())->withAttribute( $request = (new ServerRequest())->withAttribute(
RouteResult::class, RouteResult::class,
@ -145,10 +140,8 @@ class AuthenticationMiddlewareTest extends TestCase
$fromRequest->shouldHaveBeenCalledOnce(); $fromRequest->shouldHaveBeenCalledOnce();
} }
/** /** @test */
* @test public function updatedResponseIsReturnedWhenVerificationPasses(): void
*/
public function updatedResponseIsReturnedWhenVerificationPasses()
{ {
$newResponse = new Response(); $newResponse = new Response();
$request = (new ServerRequest())->withAttribute( $request = (new ServerRequest())->withAttribute(

View File

@ -36,9 +36,9 @@ class BodyParserMiddlewareTest extends TestCase
public function provideIgnoredRequestMethods(): iterable public function provideIgnoredRequestMethods(): iterable
{ {
yield 'with GET' => ['GET']; yield 'GET' => ['GET'];
yield 'with HEAD' => ['HEAD']; yield 'HEAD' => ['HEAD'];
yield 'with OPTIONS' => ['OPTIONS']; yield 'OPTIONS' => ['OPTIONS'];
} }
/** @test */ /** @test */

View File

@ -24,9 +24,7 @@ class CrossDomainMiddlewareTest extends TestCase
$this->delegate = $this->prophesize(RequestHandlerInterface::class); $this->delegate = $this->prophesize(RequestHandlerInterface::class);
} }
/** /** @test */
* @test
*/
public function nonCrossDomainRequestsAreNotAffected() public function nonCrossDomainRequestsAreNotAffected()
{ {
$originalResponse = new Response(); $originalResponse = new Response();
@ -40,9 +38,7 @@ class CrossDomainMiddlewareTest extends TestCase
$this->assertArrayNotHasKey('Access-Control-Allow-Headers', $headers); $this->assertArrayNotHasKey('Access-Control-Allow-Headers', $headers);
} }
/** /** @test */
* @test
*/
public function anyRequestIncludesTheAllowAccessHeader() public function anyRequestIncludesTheAllowAccessHeader()
{ {
$originalResponse = new Response(); $originalResponse = new Response();
@ -59,9 +55,7 @@ class CrossDomainMiddlewareTest extends TestCase
$this->assertArrayNotHasKey('Access-Control-Allow-Headers', $headers); $this->assertArrayNotHasKey('Access-Control-Allow-Headers', $headers);
} }
/** /** @test */
* @test
*/
public function optionsRequestIncludesMoreHeaders() public function optionsRequestIncludesMoreHeaders()
{ {
$originalResponse = new Response(); $originalResponse = new Response();

View File

@ -24,9 +24,7 @@ class PathVersionMiddlewareTest extends TestCase
$this->middleware = new PathVersionMiddleware(); $this->middleware = new PathVersionMiddleware();
} }
/** /** @test */
* @test
*/
public function whenVersionIsProvidedRequestRemainsUnchanged() public function whenVersionIsProvidedRequestRemainsUnchanged()
{ {
$request = (new ServerRequest())->withUri(new Uri('/v2/foo')); $request = (new ServerRequest())->withUri(new Uri('/v2/foo'));
@ -39,9 +37,7 @@ class PathVersionMiddlewareTest extends TestCase
$process->shouldHaveBeenCalled(); $process->shouldHaveBeenCalled();
} }
/** /** @test */
* @test
*/
public function versionOneIsPrependedWhenNoVersionIsDefined() public function versionOneIsPrependedWhenNoVersionIsDefined()
{ {
$request = (new ServerRequest())->withUri(new Uri('/bar/baz')); $request = (new ServerRequest())->withUri(new Uri('/bar/baz'));

View File

@ -25,10 +25,8 @@ class CreateShortUrlContentNegotiationMiddlewareTest extends TestCase
$this->requestHandler = $this->prophesize(RequestHandlerInterface::class); $this->requestHandler = $this->prophesize(RequestHandlerInterface::class);
} }
/** /** @test */
* @test public function whenNoJsonResponseIsReturnedNoFurtherOperationsArePerformed(): void
*/
public function whenNoJsonResponseIsReturnedNoFurtherOperationsArePerformed()
{ {
$expectedResp = new Response(); $expectedResp = new Response();
$this->requestHandler->handle(Argument::type(ServerRequestInterface::class))->willReturn($expectedResp); $this->requestHandler->handle(Argument::type(ServerRequestInterface::class))->willReturn($expectedResp);
@ -43,7 +41,7 @@ class CreateShortUrlContentNegotiationMiddlewareTest extends TestCase
* @dataProvider provideData * @dataProvider provideData
* @param array $query * @param array $query
*/ */
public function properResponseIsReturned(?string $accept, array $query, string $expectedContentType) public function properResponseIsReturned(?string $accept, array $query, string $expectedContentType): void
{ {
$request = (new ServerRequest())->withQueryParams($query); $request = (new ServerRequest())->withQueryParams($query);
if ($accept !== null) { if ($accept !== null) {
@ -60,18 +58,16 @@ class CreateShortUrlContentNegotiationMiddlewareTest extends TestCase
$handle->shouldHaveBeenCalled(); $handle->shouldHaveBeenCalled();
} }
public function provideData(): array public function provideData(): iterable
{ {
return [ yield [null, [], 'application/json'];
[null, [], 'application/json'], yield [null, ['format' => 'json'], 'application/json'];
[null, ['format' => 'json'], 'application/json'], yield [null, ['format' => 'invalid'], 'application/json'];
[null, ['format' => 'invalid'], 'application/json'], yield [null, ['format' => 'txt'], 'text/plain'];
[null, ['format' => 'txt'], 'text/plain'], yield ['application/json', [], 'application/json'];
['application/json', [], 'application/json'], yield ['application/xml', [], 'application/json'];
['application/xml', [], 'application/json'], yield ['text/plain', [], 'text/plain'];
['text/plain', [], 'text/plain'], yield ['application/json', ['format' => 'txt'], 'text/plain'];
['application/json', ['format' => 'txt'], 'text/plain'],
];
} }
/** /**
@ -79,7 +75,7 @@ class CreateShortUrlContentNegotiationMiddlewareTest extends TestCase
* @dataProvider provideTextBodies * @dataProvider provideTextBodies
* @param array $json * @param array $json
*/ */
public function properBodyIsReturnedInPlainTextResponses(array $json, string $expectedBody) public function properBodyIsReturnedInPlainTextResponses(array $json, string $expectedBody): void
{ {
$request = (new ServerRequest())->withQueryParams(['format' => 'txt']); $request = (new ServerRequest())->withQueryParams(['format' => 'txt']);
@ -93,12 +89,10 @@ class CreateShortUrlContentNegotiationMiddlewareTest extends TestCase
$handle->shouldHaveBeenCalled(); $handle->shouldHaveBeenCalled();
} }
public function provideTextBodies(): array public function provideTextBodies(): iterable
{ {
return [ yield 'shortUrl key' => [['shortUrl' => 'foobar'], 'foobar'];
[['shortUrl' => 'foobar'], 'foobar'], yield 'error key' => [['error' => 'FOO_BAR'], 'FOO_BAR'];
[['error' => 'FOO_BAR'], 'FOO_BAR'], yield 'no shortUrl or error keys' => [[], ''];
[[], ''],
];
} }
} }

View File

@ -25,9 +25,7 @@ class ShortCodePathMiddlewareTest extends TestCase
$this->requestHandler->handle(Argument::type(ServerRequestInterface::class))->willReturn(new Response()); $this->requestHandler->handle(Argument::type(ServerRequestInterface::class))->willReturn(new Response());
} }
/** /** @test */
* @test
*/
public function properlyReplacesTheOldPathByTheNewOne() public function properlyReplacesTheOldPathByTheNewOne()
{ {
$uri = new Uri('/short-codes/foo'); $uri = new Uri('/short-codes/foo');

View File

@ -26,9 +26,7 @@ class ApiKeyServiceTest extends TestCase
$this->service = new ApiKeyService($this->em->reveal()); $this->service = new ApiKeyService($this->em->reveal());
} }
/** /** @test */
* @test
*/
public function keyIsProperlyCreated() public function keyIsProperlyCreated()
{ {
$this->em->flush()->shouldBeCalledOnce(); $this->em->flush()->shouldBeCalledOnce();
@ -38,9 +36,7 @@ class ApiKeyServiceTest extends TestCase
$this->assertNull($key->getExpirationDate()); $this->assertNull($key->getExpirationDate());
} }
/** /** @test */
* @test
*/
public function keyIsProperlyCreatedWithExpirationDate() public function keyIsProperlyCreatedWithExpirationDate()
{ {
$this->em->flush()->shouldBeCalledOnce(); $this->em->flush()->shouldBeCalledOnce();
@ -51,9 +47,7 @@ class ApiKeyServiceTest extends TestCase
$this->assertSame($date, $key->getExpirationDate()); $this->assertSame($date, $key->getExpirationDate());
} }
/** /** @test */
* @test
*/
public function checkReturnsFalseWhenKeyIsInvalid() public function checkReturnsFalseWhenKeyIsInvalid()
{ {
$repo = $this->prophesize(EntityRepository::class); $repo = $this->prophesize(EntityRepository::class);
@ -64,9 +58,7 @@ class ApiKeyServiceTest extends TestCase
$this->assertFalse($this->service->check('12345')); $this->assertFalse($this->service->check('12345'));
} }
/** /** @test */
* @test
*/
public function checkReturnsFalseWhenKeyIsDisabled() public function checkReturnsFalseWhenKeyIsDisabled()
{ {
$key = new ApiKey(); $key = new ApiKey();
@ -79,9 +71,7 @@ class ApiKeyServiceTest extends TestCase
$this->assertFalse($this->service->check('12345')); $this->assertFalse($this->service->check('12345'));
} }
/** /** @test */
* @test
*/
public function checkReturnsFalseWhenKeyIsExpired() public function checkReturnsFalseWhenKeyIsExpired()
{ {
$key = new ApiKey(Chronos::now()->subDay()); $key = new ApiKey(Chronos::now()->subDay());
@ -93,9 +83,7 @@ class ApiKeyServiceTest extends TestCase
$this->assertFalse($this->service->check('12345')); $this->assertFalse($this->service->check('12345'));
} }
/** /** @test */
* @test
*/
public function checkReturnsTrueWhenConditionsAreFavorable() public function checkReturnsTrueWhenConditionsAreFavorable()
{ {
$repo = $this->prophesize(EntityRepository::class); $repo = $this->prophesize(EntityRepository::class);
@ -118,9 +106,7 @@ class ApiKeyServiceTest extends TestCase
$this->service->disable('12345'); $this->service->disable('12345');
} }
/** /** @test */
* @test
*/
public function disableReturnsDisabledKeyWhenFOund() public function disableReturnsDisabledKeyWhenFOund()
{ {
$key = new ApiKey(); $key = new ApiKey();
@ -137,9 +123,7 @@ class ApiKeyServiceTest extends TestCase
$this->assertSame($key, $returnedKey); $this->assertSame($key, $returnedKey);
} }
/** /** @test */
* @test
*/
public function listFindsAllApiKeys() public function listFindsAllApiKeys()
{ {
$repo = $this->prophesize(EntityRepository::class); $repo = $this->prophesize(EntityRepository::class);
@ -150,9 +134,7 @@ class ApiKeyServiceTest extends TestCase
$this->service->listKeys(); $this->service->listKeys();
} }
/** /** @test */
* @test
*/
public function listEnabledFindsOnlyEnabledApiKeys() public function listEnabledFindsOnlyEnabledApiKeys()
{ {
$repo = $this->prophesize(EntityRepository::class); $repo = $this->prophesize(EntityRepository::class);

View File

@ -13,9 +13,7 @@ use Shlinkio\Shlink\Rest\Util\RestUtils;
class RestUtilsTest extends TestCase class RestUtilsTest extends TestCase
{ {
/** /** @test */
* @test
*/
public function correctCodeIsReturnedFromException() public function correctCodeIsReturnedFromException()
{ {
$this->assertEquals( $this->assertEquals(