about summary refs log tree commit diff stats
path: root/tests_integration/ApiTestCase.php
blob: 90ac35724c5ecc60dbf6b6ca2bb560c13bd306c7 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
<?php
use PHPUnit\Framework\TestCase;

abstract class ApiTestCase extends TestCase {
	protected string $apiUrl;

	private string $cookieFile;
	private string $csrfToken = "";

	protected function setUp(): void
	{
		$this->apiUrl = getenv('API_URL') ?: 'http://localhost:9080/backend.php';
		$this->cookieFile = tempnam(sys_get_temp_dir(), 'epube_cookie_');
	}

	protected function tearDown(): void {
		if (file_exists($this->cookieFile))
			unlink($this->cookieFile);
	}

	/**
	 * Make an HTTP POST request and return [status_code, decoded_body, headers].
	 * Includes CSRF token automatically unless passed via $data
	 *
	 * @param array<string, string|int> $data
	 * @param bool $parseJson parse returned body as JSON object
	 * @return array<int, mixed>
	 */
	protected function post(string $endpoint, array $data, bool $parseJson = true): array
	{

		// allow overring automatic csrf_token to fail requests or w/e
		if ($this->csrfToken && !isset($data['csrf_token']))
			$data['csrf_token'] = $this->csrfToken;

		$ch = curl_init($endpoint);
		curl_setopt_array($ch, [
			CURLOPT_RETURNTRANSFER => true,
			CURLOPT_POST           => true,
			CURLOPT_POSTFIELDS     => http_build_query($data),
			CURLOPT_TIMEOUT        => 10,
			CURLOPT_CONNECTTIMEOUT => 5,
			CURLOPT_COOKIEFILE     => $this->cookieFile,
			CURLOPT_COOKIEJAR      => $this->cookieFile,
			CURLOPT_HEADER         => true,
		]);
		$response = curl_exec($ch);
		$status  = curl_getinfo($ch, CURLINFO_HTTP_CODE);
		$errno   = curl_errno($ch);
		$error   = curl_error($ch);
		curl_close($ch);

		if ($errno) {
			$this->fail("cURL error ($errno): $error");
		}

		// Split headers and body
		$headerEnd = strpos($response, "\r\n\r\n");
		if ($headerEnd === false) {
			return [$status, '', []];
		}

		$headerText = substr($response, 0, $headerEnd);
		$body       = substr($response, $headerEnd + 4);

		// Parse headers into associative array
		$headers = [];
		foreach (explode("\r\n", trim($headerText)) as $line) {
			if (strpos($line, ':') !== false) {
				[$key, $value] = explode(':', $line, 2);
				$headers[trim($key)] = trim($value);
			}
		}

		if ($parseJson) {
			/** @var array<string, mixed>|null $decoded */
			$decoded = json_decode($body, true);

			if (isset($decoded["csrf_token"]))
				$this->csrfToken = $decoded["csrf_token"];

			return [$status, $decoded ?? [], $headers];

		} else {
			return [$status, $body, $headers];
		}
	}
}