-
Notifications
You must be signed in to change notification settings - Fork 266
/
Copy pathBaseTestCase.php
383 lines (343 loc) · 14.1 KB
/
BaseTestCase.php
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
<?php declare(strict_types=1);
namespace App\Tests\Unit\Controller\API;
use App\Entity\Contest;
use App\Tests\Unit\BaseTestCase as BaseBaseTestCase;
use Doctrine\ORM\EntityManagerInterface;
use Generator;
use JsonException;
use Symfony\Bundle\FrameworkBundle\KernelBrowser;
abstract class BaseTestCase extends BaseBaseTestCase
{
protected static array $rootEndpoints = ['contests', 'judgehosts', 'users'];
protected static string $testedRole = 'unset';
/** @var KernelBrowser */
protected KernelBrowser $client;
/** The API endpoint to query for this test */
protected ?string $apiEndpoint = null;
/**
* The username of the user to use for the tests.
* Currently, only admin and demo are supported.
* Leave set to null to use no user.
*/
protected ?string $apiUser = null;
/**
* Fill this array with expected objects the API should return, indexed on ID.
*/
protected array $expectedObjects = [];
protected ?string $objectClassForExternalId = null;
/**
* When using a non-local data source this is used to look up external IDs.
* Set it to an array where keys are fields and values are classes.
*
* @var string[]
*/
protected array $entityReferences = [];
/**
* Fill this array with IDs of object that should not be present.
*
* @var string[]
*/
protected array $expectedAbsent = [];
protected Contest $demoContest;
protected function setUp(): void
{
parent::setUp();
// Load the contest used in tests.
$this->demoContest = static::getContainer()->get(EntityManagerInterface::class)
->getRepository(Contest::class)
->findOneBy(['shortname' => 'demo']);
}
/**
* Get the contest ID of the demo contest based on the data source setting.
*
* @return string
*/
protected function getDemoContestId(): string
{
return $this->demoContest->getExternalid();
}
/**
* Verify the given API URL produces the given status code and return the body.
*
* @param string $method The HTTP method to use.
* @param string $apiUri The API URL to use. Will be prefixed with /api.
* @param int $status The status code to expect.
* @param string|null $user The username to use. Currently, only admin and demo are supported.
* @param mixed $jsonData The JSON data to set as a body, if any.
* @param array $files The files to upload, if any.
*
* @return mixed The returned data
*/
protected function verifyApiResponse(
string $method,
string $apiUri,
int $status,
?string $user = null,
mixed $jsonData = null,
array $files = [],
bool $attachment = false,
?string $password = 'unset_password_for_test'
) {
$server = ['CONTENT_TYPE' => 'application/json'];
// The API doesn't use cookie based logins, so we need to set a username/password.
// For the admin, we can get it from initial_admin_password.secret and for the demo user we know it's 'demo'.
if ($user === 'admin') {
$adminPasswordFile = sprintf(
'%s/%s',
static::getContainer()->getParameter('domjudge.etcdir'),
'initial_admin_password.secret'
);
$server['PHP_AUTH_USER'] = 'admin';
$server['PHP_AUTH_PW'] = trim(file_get_contents($adminPasswordFile));
} else {
$server['PHP_AUTH_USER'] = $user;
$server['PHP_AUTH_PW'] = ($password === 'unset_password_for_test') ? $user : $password;
}
$this->client->request($method, '/api' . $apiUri, [], $files, $server, $jsonData ? json_encode($jsonData, JSON_THROW_ON_ERROR) : null);
$response = $this->client->getResponse();
$message = var_export($response, true);
self::assertEquals($status, $response->getStatusCode(), $message);
if ($attachment) {
return $this->client->getInternalResponse()->getContent();
}
return $response->getContent();
}
/**
* Verify the given API URL produces the given status code and return the body as JSON.
*
* @param string $method The HTTP method to use.
* @param string $apiUri The API URL to use. Will be prefixed with /api.
* @param int $status The status code to expect.
* @param string|null $user The username to use. Currently, only admin and demo are supported.
* @param mixed $jsonData The JSON data to set as a body, if any.
* @param array $files The files to upload, if any.
*
* @return mixed The returned JSON data.
*/
protected function verifyApiJsonResponse(
string $method,
string $apiUri,
int $status,
?string $user = null,
mixed $jsonData = null,
array $files = [],
?string $password = 'unset_password_for_test'
) {
$response = $this->verifyApiResponse($method, $apiUri, $status, $user, $jsonData, $files, false, $password);
try {
return json_decode($response, true, 512, JSON_THROW_ON_ERROR);
} catch (JsonException) {
return null;
}
}
public function helperGetEndpointURL(string $apiEndpoint, ?string $id = null, ?string $cid = null): string
{
if (in_array($apiEndpoint, static::$rootEndpoints)) {
$url = "/$apiEndpoint";
} else {
$contestId = $cid ?? $this->getDemoContestId();
$url = "/contests/$contestId/$apiEndpoint";
}
if ($apiEndpoint === 'judgehosts') {
return is_null($id) ? $url : "$url?hostname=$id";
}
return is_null($id) ? $url : "$url/$id";
}
/**
* Test that the list action returns the expected objects.
*/
public function testList(): void
{
if (($apiEndpoint = $this->apiEndpoint) === null) {
static::markTestSkipped('No endpoint defined.');
}
$url = $this->helperGetEndpointURL($apiEndpoint);
$objects = $this->verifyApiJsonResponse('GET', $url, 200, $this->apiUser);
static::assertIsArray($objects);
foreach ($this->expectedObjects as $expectedObjectId => $expectedObject) {
foreach ($this->entityReferences as $field => $class) {
$expectedObject[$field] = $this->resolveEntityId($class, $expectedObject[$field]);
}
$expectedObjectId = $this->resolveReference($expectedObjectId);
if ($this->objectClassForExternalId !== null) {
$expectedObjectId = $this->resolveEntityId($this->objectClassForExternalId, (string)$expectedObjectId);
}
$object = null;
foreach ($objects as $potentialObject) {
if ($potentialObject['id'] == $expectedObjectId) {
$object = $potentialObject;
break;
}
}
static::assertNotNull($object);
static::assertEquals($expectedObjectId, $object['id']);
foreach ($expectedObject as $key => $value) {
// Null values can also be absent.
static::assertEquals($value, $object[$key] ?? null, $key . ' has correct value.');
}
}
foreach ($this->expectedAbsent as $expectedAbsentId) {
$object = null;
foreach ($objects as $potentialObject) {
if ($potentialObject['id'] == $expectedAbsentId) {
$object = $potentialObject;
break;
}
}
static::assertNull($object);
}
}
/**
* Test that the list action returns the expected objects if IDs are passed.
*/
public function testListWithIds(): void
{
if (($apiEndpoint = $this->apiEndpoint) === null) {
static::markTestSkipped('No endpoint defined.');
}
$expectedObjectIds = array_map(function ($id) {
$id = $this->resolveReference($id);
if ($this->objectClassForExternalId !== null) {
$id = $this->resolveEntityId($this->objectClassForExternalId, (string)$id);
}
return $id;
}, array_keys($this->expectedObjects));
$url = $this->helperGetEndpointURL($apiEndpoint);
$objects = $this->verifyApiJsonResponse('GET', $url . "?" . http_build_query(['ids' => $expectedObjectIds]), 200, $this->apiUser);
// Verify we got exactly enough objects.
static::assertIsArray($objects);
static::assertCount(count($this->expectedObjects), $objects);
// Verify all objects are present.
foreach ($expectedObjectIds as $expectedObjectId) {
$object = null;
foreach ($objects as $potentialObject) {
if ($potentialObject['id'] == $expectedObjectId) {
$object = $potentialObject;
break;
}
}
static::assertNotNull($object);
}
}
/**
* Test that the list action returns the correct error when the contest is not found.
*/
public function testListContestNotFound(): void
{
if (($apiEndpoint = $this->apiEndpoint) === null) {
static::markTestSkipped('No endpoint defined.');
}
if (in_array($apiEndpoint, static::$rootEndpoints)) {
// We can not test this, since e.g. /contests always exists. Assert that true is true to not make the test
// risky.
static::assertTrue(true);
return;
}
// Note that the 42 here is a contest that doesn't exist.
$response = $this->verifyApiJsonResponse('GET', "/contests/42/$apiEndpoint", 404, $this->apiUser);
static::assertEquals('Contest with ID \'42\' not found', $response['message']);
}
/**
* Test that the list method returns the correct error when the IDs parameter is not an array.
*/
public function testListWithIdsNotArray(): void
{
if (($apiEndpoint = $this->apiEndpoint) === null) {
static::markTestSkipped('No endpoint defined.');
}
$url = $this->helperGetEndpointURL($apiEndpoint);
$response = $this->verifyApiJsonResponse('GET', $url . "?" . http_build_query(['ids' => 2]), 400, $this->apiUser);
static::assertEquals('Unexpected value for parameter "ids": expecting "array", got "string".', $response['message']);
}
/**
* Test that the list method returns the correct error when passing IDs that don't exist.
*/
public function testListWithAbsentIds(): void
{
if (($apiEndpoint = $this->apiEndpoint) === null) {
static::markTestSkipped('No endpoint defined.');
}
$expectedObjectIds = array_map(
fn($id) => $this->resolveReference($id),
array_keys($this->expectedObjects)
);
$ids = [...$expectedObjectIds, ...$this->expectedAbsent];
$url = $this->helperGetEndpointURL($apiEndpoint);
$response = $this->verifyApiJsonResponse('GET', $url . "?" . http_build_query(['ids' => $ids]), 404, $this->apiUser);
static::assertEquals('One or more objects not found', $response['message']);
}
/**
* Test that the single action returns the correct data.
*
* @dataProvider provideSingle
*/
public function testSingle(int|string $id, array $expectedProperties): void
{
foreach ($this->entityReferences as $field => $class) {
$expectedProperties[$field] = $this->resolveEntityId($class, $expectedProperties[$field]);
}
$id = $this->resolveReference($id);
if ($this->objectClassForExternalId !== null) {
$id = $this->resolveEntityId($this->objectClassForExternalId, (string)$id);
}
if (($apiEndpoint = $this->apiEndpoint) === null) {
static::markTestSkipped('No endpoint defined.');
}
$url = $this->helperGetEndpointURL($apiEndpoint, (string)$id);
$object = $this->verifyApiJsonResponse('GET', $url, 200, $this->apiUser);
static::assertIsArray($object);
$object = is_array($object) && count($object)===1 ? $object[0] : $object;
foreach ($expectedProperties as $key => $value) {
// Null values can also be absent.
static::assertEquals($value, $object[$key] ?? null, $key . ' has correct value.');
}
}
public function provideSingle(): Generator
{
foreach ($this->expectedObjects as $id => $expectedProperties) {
yield [$id, $expectedProperties];
}
}
/**
* Test that the single action returns the correct error when the contest is not found.
*/
public function testSingleContestNotFound(): void
{
if (($apiEndpoint = $this->apiEndpoint) === null) {
static::markTestSkipped('No endpoint defined.');
}
if (in_array($apiEndpoint, static::$rootEndpoints)) {
static::markTestSkipped('Endpoint does not have contests prefix.');
}
// Note that the 42 here is a contest that doesn't exist.
$url = "/contests/42/$apiEndpoint/123";
$message = 'Contest with ID \'42\' not found';
$response = $this->verifyApiJsonResponse('GET', $url, 404, $this->apiUser);
static::assertEquals($message, $response['message']);
}
/**
* Test that the endpoint does not return anything for objects that don't exist.
*
* @dataProvider provideSingleNotFound
*/
public function testSingleNotFound(string $id): void
{
$id = $this->resolveReference($id);
if (($apiEndpoint = $this->apiEndpoint) === null) {
static::markTestSkipped('No endpoint defined.');
}
$url = $this->helperGetEndpointURL($apiEndpoint, $id);
$this->verifyApiJsonResponse('GET', $url, 404, $this->apiUser);
}
public function provideSingleNotFound(): Generator
{
foreach ($this->expectedAbsent as $id) {
yield [$id];
}
}
protected function provideAllowedUsers(): Generator
{
yield ['admin', ['admin']];
yield ['team', [static::$testedRole]];
}
}