urlShortener = $this->prophesize(UrlShortener::class); $this->action = new CreateShortUrlAction($this->urlShortener->reveal(), [ 'schema' => 'http', 'hostname' => 'foo.com', ]); } /** @test */ public function missingLongUrlParamReturnsError(): void { $response = $this->action->handle(new ServerRequest()); $this->assertEquals(400, $response->getStatusCode()); } /** @test */ public function properShortcodeConversionReturnsData(): void { $this->urlShortener->urlToShortCode(Argument::type(Uri::class), Argument::type('array'), Argument::cetera()) ->willReturn( (new ShortUrl(''))->setShortCode('abc123') ) ->shouldBeCalledOnce(); $request = (new ServerRequest())->withParsedBody([ 'longUrl' => 'http://www.domain.com/foo/bar', ]); $response = $this->action->handle($request); $this->assertEquals(200, $response->getStatusCode()); $this->assertTrue(strpos($response->getBody()->getContents(), 'http://foo.com/abc123') > 0); } /** @test */ public function anInvalidUrlReturnsError(): void { $this->urlShortener->urlToShortCode(Argument::type(Uri::class), Argument::type('array'), Argument::cetera()) ->willThrow(InvalidUrlException::class) ->shouldBeCalledOnce(); $request = (new ServerRequest())->withParsedBody([ 'longUrl' => 'http://www.domain.com/foo/bar', ]); $response = $this->action->handle($request); $this->assertEquals(400, $response->getStatusCode()); $this->assertTrue(strpos($response->getBody()->getContents(), RestUtils::INVALID_URL_ERROR) > 0); } /** @test */ public function nonUniqueSlugReturnsError(): void { $this->urlShortener->urlToShortCode( Argument::type(Uri::class), Argument::type('array'), ShortUrlMeta::createFromRawData(['customSlug' => 'foo']), Argument::cetera() )->willThrow(NonUniqueSlugException::class)->shouldBeCalledOnce(); $request = (new ServerRequest())->withParsedBody([ 'longUrl' => 'http://www.domain.com/foo/bar', 'customSlug' => 'foo', ]); $response = $this->action->handle($request); $this->assertEquals(400, $response->getStatusCode()); $this->assertStringContainsString(RestUtils::INVALID_SLUG_ERROR, (string) $response->getBody()); } /** @test */ public function aGenericExceptionWillReturnError(): void { $this->urlShortener->urlToShortCode(Argument::type(Uri::class), Argument::type('array'), Argument::cetera()) ->willThrow(Exception::class) ->shouldBeCalledOnce(); $request = (new ServerRequest())->withParsedBody([ 'longUrl' => 'http://www.domain.com/foo/bar', ]); $response = $this->action->handle($request); $this->assertEquals(500, $response->getStatusCode()); $this->assertTrue(strpos($response->getBody()->getContents(), RestUtils::UNKNOWN_ERROR) > 0); } }