From fe8df6df4e2c028e57c723d36703e83a11423fa4 Mon Sep 17 00:00:00 2001 From: Alexander Skvortsov Date: Fri, 20 Mar 2020 17:16:29 +0100 Subject: [PATCH] Add Authenticated Test Case utility --- .../integration/AuthenticatedTestCase.php | 72 +++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 framework/core/tests/integration/AuthenticatedTestCase.php diff --git a/framework/core/tests/integration/AuthenticatedTestCase.php b/framework/core/tests/integration/AuthenticatedTestCase.php new file mode 100644 index 000000000..3f2ce4e5f --- /dev/null +++ b/framework/core/tests/integration/AuthenticatedTestCase.php @@ -0,0 +1,72 @@ +firstOrCreate([ + 'key' => Str::random(), + 'user_id' => $user_id, + 'created_at' => Carbon::now() + ]); + }); + } + + /** + * Build an authenticated HTTP request that can be passed through middleware. + * + * This method simplifies building HTTP request for use in our HTTP-level + * integration tests. It provides options for all features repeatedly being + * used in those tests. + * + * @param string $method + * @param string $path + * @param array $options + * An array of optional request properties. + * Currently supported: + * - "json" should point to a JSON-serializable object that will be + * serialized and used as request body. The corresponding Content-Type + * header will be set automatically. + * - "cookiesFrom" should hold a response object from a previous HTTP + * interaction. All cookies returned from the server in that response + * (via the "Set-Cookie" header) will be copied to the cookie params of + * the new request. + * @param int $userId Which user should be emulated? User ID 1 will return a + * user with admin perms unless this has been modified in your test case. + * @return ServerRequestInterface + */ + protected function authenticatedRequest(string $method, string $path, array $options = [], int $userId = 1): ServerRequestInterface + { + $request = $this->request($method, $path, $options); + + $this->prepareDatabase([ + 'users' => [ + $this->adminUser(), + $this->normalUser(), + ], + ]); + + if (! isset($this->key)) { + $this->key = $this->genKey(); + } + + return $request->withAddedHeader('Authorization', "Token {$this->key->key}; userId=$userId"); + } +}