. */ declare(strict_types=1); namespace Fisharebest\Webtrees\Http\RequestHandlers; use Fig\Http\Message\StatusCodeInterface; use Fisharebest\Webtrees\Auth; use Fisharebest\Webtrees\Services\UserService; use Fisharebest\Webtrees\Session; use Fisharebest\Webtrees\TestCase; use Fisharebest\Webtrees\User; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; /** * @covers \Fisharebest\Webtrees\Http\RequestHandlers\Masquerade */ class MasqueradeTest extends TestCase { /** * @return void */ public function testMasqueradeAsUser(): void { $user1 = $this->createMock(User::class); $user1->method('id')->willReturn(1); $user2 = $this->createMock(User::class); $user2->method('id')->willReturn(2); $user_service = $this->createMock(UserService::class); $user_service->expects($this->once())->method('find')->willReturn($user2); $request = self::createRequest() ->withAttribute('user', $user1) ->withAttribute('user_id', $user2->id()); $handler = new Masquerade($user_service); $response = $handler->handle($request); self::assertSame(StatusCodeInterface::STATUS_NO_CONTENT, $response->getStatusCode()); self::assertSame($user2->id(), Auth::id()); self::assertSame('1', Session::get('masquerade')); } /** * @return void */ public function testCannotMasqueradeAsSelf(): void { $user = $this->createMock(User::class); $user->method('id')->willReturn(1); $user_service = $this->createMock(UserService::class); $user_service->expects($this->once())->method('find')->willReturn($user); $request = self::createRequest() ->withAttribute('user', $user) ->withAttribute('user_id', $user->id()); $handler = new Masquerade($user_service); $response = $handler->handle($request); self::assertSame(StatusCodeInterface::STATUS_NO_CONTENT, $response->getStatusCode()); self::assertNull(Session::get('masquerade')); } /** * @return void */ public function testMasqueradeAsNonExistingUser(): void { $this->expectException(NotFoundHttpException::class); $this->expectExceptionMessage('User ID 2 not found'); $user = $this->createMock(User::class); $user->method('id')->willReturn(1); $user_service = $this->createMock(UserService::class); $user_service->expects($this->once())->method('find')->willReturn(null); $request = self::createRequest() ->withAttribute('user', $user) ->withAttribute('user_id', 2); $handler = new Masquerade($user_service); $handler->handle($request); } }