-
Notifications
You must be signed in to change notification settings - Fork 4
/
TestCase.php
463 lines (382 loc) · 15.4 KB
/
TestCase.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
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
<?php
namespace Tests;
use App\Audits;
use App\Brands;
use App\Category;
use App\Device;
use App\DeviceBarrier;
use App\EventsUsers;
use App\Group;
use App\GroupNetwork;
use App\GroupTags;
use App\Images;
use App\Network;
use App\Party;
use App\Role;
use App\Skills;
use App\UsersSkills;
use App\User;
use App\UserGroups;
use App\Xref;
use Auth;
use Carbon\Carbon;
use DB;
use Hash;
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Queue;
use Symfony\Component\DomCrawler\Crawler;
use Osteel\OpenApi\Testing\ValidatorBuilder;
use Osteel\OpenApi\Testing\Exceptions\ValidationException;
abstract class TestCase extends BaseTestCase
{
use CreatesApplication;
private $userCount = 0;
public $groupCount = 0;
private $DOM = null;
public $lastResponse = null;
protected function setUp(): void
{
parent::setUp();
DB::statement('SET foreign_key_checks=0');
Network::truncate();
Group::truncate();
User::truncate();
Audits::truncate();
EventsUsers::truncate();
UserGroups::truncate();
DeviceBarrier::truncate();
Device::truncate();
Party::truncate();
GroupNetwork::truncate();
Category::truncate();
Brands::truncate();
GroupTags::truncate();
Xref::truncate();
Images::truncate();
UsersSkills::truncate();
Skills::truncate();
DB::statement('delete from audits');
DB::delete('delete from user_network');
DB::delete('delete from grouptags_groups');
DB::table('notifications')->truncate();
DB::statement('SET foreign_key_checks=1');
DB::delete('delete from devices_faults_vacuums_ora_opinions');
// Set up random auto increment values. This avoids tests working because everything is 1.
//
// Some tables (e.g. network) have a tinyint as the ID, so we must be careful not to create values that
// overflow this. Also avoid the magic 29 value, which is a "superhero" user (see ExportController).
$tables = DB::select('SHOW TABLES');
foreach ($tables as $table)
{
foreach ($table as $field => $tablename) {
try {
do {
$val = rand(1, 100);
} while ($val == 29);
// This will throw an exception if the table doesn't have auto increment.
DB::update("ALTER TABLE $tablename AUTO_INCREMENT = " . $val . ";");
} catch (\Exception $e) {
}
}
}
if (!Network::where('name', 'Restarters')->first()) {
$network = new Network();
$network->name = 'Restarters';
$network->shortname = 'restarters';
$network->save();
}
$this->withoutExceptionHandling();
app('honeypot')->disable();
Category::factory()->count(1)->cat1()->create();
Category::factory()->count(1)->cat2()->create();
Category::factory()->count(1)->cat3()->create();
Category::factory()->count(1)->mobile()->create();
Category::factory()->count(1)->misc()->create();
Category::factory()->count(1)->desktopComputer()->create();
// We manipulate some globals for image upload testing.
\FixometerFile::$uploadTesting = FALSE;
if (isset($_FILES)) {
unset($_FILES);
}
$this->processQueuedNotifications();
$this->OpenAPIValidator = ValidatorBuilder::fromJson(storage_path('api-docs/api-docs.json'))->getValidator();
// Some tests may override the queue.
$queueManager = $this->app['queue'];
$queueManager->setDefaultDriver('database');
// Clear any jobs queued in earlier tests.
$max = 1000;
do {
$job = Queue::pop('database');
if ($job) {
try {
$job->fail('removed in UT');
} catch (\Exception $e) {}
}
$max--;
}
while (Queue::size() > 0 && $max > 0);
}
public function userAttributes()
{
// Return a test user.
$userAttributes = [];
$userAttributes['name'] = 'Test'.uniqid($this->userCount++, true);
$userAttributes['email'] = $userAttributes['name'].'@restarters.dev';
$userAttributes['age'] = '1982';
$userAttributes['country'] = 'GB';
$userAttributes['password'] = 'letmein';
$userAttributes['password_confirmation'] = 'letmein';
$userAttributes['my_time'] = Carbon::now();
$userAttributes['consent_gdpr'] = true;
$userAttributes['consent_future_data'] = true;
$userAttributes['city'] = 'London';
$userAttributes['wiki_sync_status'] = 0;
return $userAttributes;
}
public function loginAsTestUser($role = Role::RESTARTER)
{
// This is testing the external interface, whereas actingAs() wouldn't be.
$response = $this->get('/logout');
$response = $this->post('/user/register/', $this->userAttributes($role));
$response->assertStatus(302);
$response->assertRedirect('dashboard');
// Set the role.
Auth::user()->role = $role;
// Ensure API token in case we need to make API calls.
Auth::user()->ensureAPIToken();
return Auth::user();
}
public function createGroup($name = 'Test Group', $website = 'https://therestartproject.org', $location = 'London', $text = 'Some text.', $assert = true, $approve = true, $email = null)
{
$idgroups = null;
// Get the dashboard. This will ensure that we have set the repair_network on the user.
$this->get('/');
// We create groups using the API.
$user = Auth::user();
$this->lastResponse = $this->post('/api/v2/groups?api_token=' . $user->api_token, [
'name' => $name.$this->groupCount++,
'website' => $website,
'location' => $location,
'description' => $text,
'timezone' => 'Europe/London',
'network_data' => [
'dummy' => 'dummy',
],
'email' => $email,
]);
if ($assert) {
$this->assertTrue($this->lastResponse->isSuccessful());
$json = json_decode($this->lastResponse->getContent(), true);
$this->assertTrue(array_key_exists('id', $json));
$idgroups = $json['id'];
if ($approve) {
$group = Group::find($idgroups);
$group->approved = true;
$group->save();
}
// Currently logged in user should be present, with status 1 = approved.
$member = UserGroups::where('group', $idgroups)->first();
$this->assertEquals(1, $member->status);
$this->assertEquals(Role::HOST, $member->role);
$this->assertEquals(Auth::user()->id, $member->user);
}
return $idgroups;
}
public function createEvent($idgroups, $date, $assert = true, $approve = false)
{
// Create a party for the specific group.
$eventAttributes = Party::factory()->raw();
$eventAttributes['group'] = $idgroups;
$event_start = Carbon::createFromTimestamp(strtotime($date))->setTimezone('UTC');
$event_end = Carbon::createFromTimestamp(strtotime($date))->setTimezone('UTC')->addHour(2);
// We create groups using the API.
$user = Auth::user();
$this->lastResponse = $this->post('/api/v2/events?api_token=' . $user->api_token, [
'groupid' => $idgroups,
'start' => $event_start->toIso8601String(),
'end' => $event_end->toIso8601String(),
'title' => $eventAttributes['venue'],
'location' => $eventAttributes['location'],
'description' => $eventAttributes['free_text'],
'timezone' => $eventAttributes['timezone']
]);
if ($assert) {
$this->assertTrue($this->lastResponse->isSuccessful());
$json = json_decode($this->lastResponse->getContent(), true);
$this->assertTrue(array_key_exists('id', $json));
$idevents = $json['id'];
if ($approve) {
$party = Party::findOrFail($idevents);
$party->approved = true;
$party->save();
}
// Currently logged in user should be present, with status 1 = approved.
$member = EventsUsers::where('event', $idevents)->first();
$this->assertEquals(1, $member->status);
$this->assertEquals(Role::HOST, $member->role);
$this->assertEquals($user->id, $member->user);
}
// Need to reformat start/end for row comparison.
$eventAttributes['event_start_utc'] = $event_start->toDateTimeString();
$eventAttributes['event_end_utc'] = $event_end->toDateTimeString();
$this->assertDatabaseHas('events', $eventAttributes);
return $idevents;
}
public function createDevice($idevents, $type)
{
$deviceAttributes = Device::factory()->{lcfirst($type)}()->raw();
$deviceAttributes['event_id'] = $idevents;
$deviceAttributes['quantity'] = 1;
$response = $this->post('/device/create', $deviceAttributes);
$iddevices = Device::latest()->first()->iddevices;
$this->assertNotNull($iddevices);
return $iddevices;
}
public function createJane()
{
$user = User::factory()->create([
'name' => 'Jane Bloggs',
'email' => 'jane@bloggs.net',
'password' => Hash::make('passw0rd'),
'role' => Role::ADMINISTRATOR,
'consent_gdpr' => true,
'consent_future_data' => true,
'repairdir_role' => Role::REPAIR_DIRECTORY_SUPERADMIN,
]);
$user->save();
}
public function getVueProperties($response)
{
$crawler = new Crawler($response->getContent());
$props = [];
$classname = 'vue';
$vues = $crawler->filterXPath("//*[contains(concat(' ', normalize-space(@class), ' '), ' $classname ')]")->each(function (Crawler $node, $i) {
return $node;
});
foreach ($vues as $vue) {
foreach ($vue->children() as $child) {
$dom = simplexml_import_dom($child);
$atts = current($dom->attributes());
$atts = $atts ? $atts : [];
$props[] = array_merge($atts, [
'VueComponent' => $vue->children()->first()->nodeName(),
]);
}
}
return $props;
}
private function canonicalise($val)
{
// Sinple code to filter out timestamps or other random values.
if ($val && is_string($val)) {
$val = preg_replace('/"created_at":".*?"/', '"created_at":"TIMESTAMP"', $val);
$val = preg_replace('/"updated_at":".*?"/', '"updated_at":"TIMESTAMP"', $val);
$val = preg_replace('/"shareable_code":".*?"/', '"shareable_code":"SHARECODE"', $val);
}
return $val;
}
private function isJson2($string)
{
// We have our own version because the PHPUnit one returns TRUE for a simple string.
json_decode($string);
return json_last_error() === JSON_ERROR_NONE;
}
private function canonicaliseAndAssertSame($val1, $val2, $name)
{
$val1 = $this->canonicalise($val1);
$val2 = $this->canonicalise($val2);
if ($this->isJson2($val1) && $this->isJson2($val2)) {
// We get nicer mismatch display if we compare the decoded JSON object rather than comparing the
// string encoding.
$dec1 = json_decode($val1, true);
$dec2 = json_decode($val2, true);
$this->assertSame($dec1, $dec2, $name);
} else {
$this->assertSame($val1, $val2, $name);
}
}
public function assertVueProperties($response, $expected)
{
// Assert that the returned response has some properties passed to our Vue components.
//
// phpunit has assertArraySubset, but this is controversially being removed in later versions so don't rely
// on it.
$props = $this->getVueProperties($response);
$foundSome = false;
for ($i = 0; $i < count($expected); $i++) {
foreach ($expected[$i] as $key => $value) {
$this->assertArrayHasKey($key, $props[$i]);
$this->canonicaliseAndAssertSame($value, $props[$i][$key], $key);
$foundSome = true;
}
}
$this->assertTrue($foundSome);
return $props;
}
public function processQueuedNotifications() {
// Process queued notifications.
while (Queue::size() > 0) {
Artisan::call('queue:work', ['--once' => true]);
}
}
// We override the methods to make HTTP requests so that we can automatically validate them against our OpenAPI
// definition where appropriate.
public function get($uri, array $headers = [])
{
$response = parent::get($uri, $headers);
if (strpos($uri, '/api/v2') === 0) {
// Validate response against OpenAPI schema.
$result = $this->OpenAPIValidator->validate($response->baseResponse, $uri, 'get');
$this->assertTrue($result);
}
return $response;
}
public function patch($uri, array $params = [], $headers = [])
{
$response = parent::patch($uri, $params, $headers);
if (strpos($uri, '/api/v2') === 0) {
// Validate response against OpenAPI schema.
$result = $this->OpenAPIValidator->validate($response->baseResponse, $uri, 'patch');
$this->assertTrue($result);
}
return $response;
}
public function post($uri, array $params = [], $headers = [])
{
$response = parent::post($uri, $params, $headers);
if (strpos($uri, '/api/v2') === 0) {
// Validate response against OpenAPI schema.
$result = $this->OpenAPIValidator->validate($response->baseResponse, $uri, 'post');
$this->assertTrue($result);
}
return $response;
}
/**
* Convert the internal attribute names to the names used in the v2 API. We have this because some of the tests
* use getAttributes() for convenience, which returns the internal attribute names, and then calls the API with
* them.
*
* @param $atts
* @return void
*/
public function eventAttributesToAPI($atts) {
$atts['title'] = $atts['venue'];
$atts['description'] = $atts['free_text'];
if (array_key_exists('event_start_utc', $atts)) {
$atts['start'] = Carbon::parse($atts['event_start_utc'])->setTimezone('UTC')->toIso8601String();
$atts['end'] = Carbon::parse($atts['event_end_utc'])->setTimezone('UTC')->toIso8601String();
} else {
// Fake an event that's two hours long. This is necessary because PartyFactory->raw() doesn't
// invoke afterMaking.
$faker = \Faker\Factory::create();
$start = Carbon::parse($faker->iso8601());
$end = $start;
$end->addHours(2);
$atts['start'] = $start->toIso8601String();
$atts['end'] = $end->toIso8601String();
}
$atts['groupid'] = $atts['group'];
return $atts;
}
}