From 54010fe7e4b94d4207a5b92b51eac259efe3d649 Mon Sep 17 00:00:00 2001 From: Jan Jakes Date: Thu, 31 Mar 2022 14:15:36 +0200 Subject: [PATCH] Add abstract class for REST API integration tests [MAILPOET-4207] --- mailpoet/tests/integration/REST/Test.php | 69 +++++++++++++++++++++++ mailpoet/tests/integration/_bootstrap.php | 1 + 2 files changed, 70 insertions(+) create mode 100644 mailpoet/tests/integration/REST/Test.php diff --git a/mailpoet/tests/integration/REST/Test.php b/mailpoet/tests/integration/REST/Test.php new file mode 100644 index 0000000000..e482c012c2 --- /dev/null +++ b/mailpoet/tests/integration/REST/Test.php @@ -0,0 +1,69 @@ +request($path, 'GET', $options); + } + + /** @param array{query?: array, post?: array, json?: array} $options */ + protected function post(string $path, array $options = []) { + return $this->request($path, 'POST', $options); + } + + /** @param array{query?: array, post?: array, json?: array} $options */ + protected function put(string $path, array $options = []) { + return $this->request($path, 'PUT', $options); + } + + /** @param array{query?: array, post?: array, json?: array} $options */ + protected function patch(string $path, array $options = []) { + return $this->request($path, 'PATCH', $options); + } + + /** @param array{query?: array, post?: array, json?: array} $options */ + protected function delete(string $path, array $options = []) { + return $this->request($path, 'DELETE', $options); + } + + /** @param array{query?: array, post?: array, json?: array} $options */ + protected function request(string $path, string $method, array $options = []) { + $_SERVER['REQUEST_METHOD'] = $method; + $_SERVER['HTTP_CONTENT_TYPE'] = 'application/json'; + + if (isset($options['query'])) { + $_GET = $options['query']; + } + + if (isset($options['post'])) { + $_POST = $options['post']; + } + + if (isset($options['json'])) { + $GLOBALS['HTTP_RAW_POST_DATA'] = json_encode($options['json']); + } + + $server = rest_get_server(); + ob_start(); + $server->serve_request($path); + $response = ob_get_clean(); + + if (!$response) { + throw new RuntimeException(); + } + + $value = json_decode($response, true); + $error = json_last_error(); + if ($error) { + throw new RuntimeException(json_last_error_msg(), $error); + } + return $value; + } +} diff --git a/mailpoet/tests/integration/_bootstrap.php b/mailpoet/tests/integration/_bootstrap.php index 956c678ccc..cafb7d8362 100644 --- a/mailpoet/tests/integration/_bootstrap.php +++ b/mailpoet/tests/integration/_bootstrap.php @@ -101,6 +101,7 @@ abstract class MailPoetTest extends \Codeception\TestCase\Test { // phpcs:ignore '_FILES', '_REQUEST', '_SERVER', + 'HTTP_RAW_POST_DATA', ]; protected $backupGlobals = false;