Completed
Push — master ( c06d85...d20e4d )
by Joas
20:12 queued 13s
created
tests/lib/L10N/FactoryTest.php 2 patches
Indentation   +761 added lines, -761 removed lines patch added patch discarded remove patch
@@ -24,765 +24,765 @@
 block discarded – undo
24 24
 use Test\TestCase;
25 25
 
26 26
 class FactoryTest extends TestCase {
27
-	/** @var IConfig|MockObject */
28
-	protected $config;
29
-
30
-	/** @var IRequest|MockObject */
31
-	protected $request;
32
-
33
-	/** @var IUserSession|MockObject */
34
-	protected $userSession;
35
-
36
-	/** @var ICacheFactory|MockObject */
37
-	protected $cacheFactory;
38
-
39
-	/** @var string */
40
-	protected $serverRoot;
41
-
42
-	/** @var IAppManager|MockObject */
43
-	protected IAppManager $appManager;
44
-
45
-	protected function setUp(): void {
46
-		parent::setUp();
47
-
48
-		$this->config = $this->createMock(IConfig::class);
49
-		$this->request = $this->createMock(IRequest::class);
50
-		$this->userSession = $this->createMock(IUserSession::class);
51
-		$this->cacheFactory = $this->createMock(ICacheFactory::class);
52
-		$this->appManager = $this->createMock(IAppManager::class);
53
-
54
-		$this->serverRoot = \OC::$SERVERROOT;
55
-
56
-		$this->config
57
-			->method('getSystemValueBool')
58
-			->willReturnMap([
59
-				['installed', false, true],
60
-			]);
61
-	}
62
-
63
-	/**
64
-	 * @param string[] $methods
65
-	 * @param bool $mockRequestGetHeaderMethod
66
-	 *
67
-	 * @return Factory|MockObject
68
-	 */
69
-	protected function getFactory(array $methods = [], $mockRequestGetHeaderMethod = false) {
70
-		if ($mockRequestGetHeaderMethod) {
71
-			$this->request->expects(self::any())
72
-				->method('getHeader')
73
-				->willReturn('');
74
-		}
75
-
76
-		if (!empty($methods)) {
77
-			return $this->getMockBuilder(Factory::class)
78
-				->setConstructorArgs([
79
-					$this->config,
80
-					$this->request,
81
-					$this->userSession,
82
-					$this->cacheFactory,
83
-					$this->serverRoot,
84
-					$this->appManager,
85
-				])
86
-				->onlyMethods($methods)
87
-				->getMock();
88
-		}
89
-
90
-		return new Factory($this->config, $this->request, $this->userSession, $this->cacheFactory, $this->serverRoot, $this->appManager);
91
-	}
92
-
93
-	public static function dataFindAvailableLanguages(): array {
94
-		return [
95
-			[null],
96
-			['files'],
97
-		];
98
-	}
99
-
100
-	public function testFindLanguageWithExistingRequestLanguageAndNoApp(): void {
101
-		$factory = $this->getFactory(['languageExists']);
102
-		$this->invokePrivate($factory, 'requestLanguage', ['de']);
103
-		$factory->expects(self::once())
104
-			->method('languageExists')
105
-			->with(null, 'de')
106
-			->willReturn(true);
107
-
108
-		self::assertSame('de', $factory->findLanguage());
109
-	}
110
-
111
-	public function testFindLanguageWithExistingRequestLanguageAndApp(): void {
112
-		$factory = $this->getFactory(['languageExists']);
113
-		$this->invokePrivate($factory, 'requestLanguage', ['de']);
114
-		$factory->expects(self::once())
115
-			->method('languageExists')
116
-			->with('MyApp', 'de')
117
-			->willReturn(true);
118
-
119
-		self::assertSame('de', $factory->findLanguage('MyApp'));
120
-	}
121
-
122
-	public function testFindLanguageWithNotExistingRequestLanguageAndExistingStoredUserLanguage(): void {
123
-		$factory = $this->getFactory(['languageExists']);
124
-		$this->invokePrivate($factory, 'requestLanguage', ['de']);
125
-		$factory->expects($this->exactly(2))
126
-			->method('languageExists')
127
-			->willReturnMap([
128
-				['MyApp', 'de', false],
129
-				['MyApp', 'jp', true],
130
-			]);
131
-		$this->config
132
-			->expects($this->exactly(1))
133
-			->method('getSystemValue')
134
-			->willReturnMap([
135
-				['force_language', false, false],
136
-			]);
137
-		$user = $this->createMock(IUser::class);
138
-		$user->expects(self::once())
139
-			->method('getUID')
140
-			->willReturn('MyUserUid');
141
-		$this->userSession
142
-			->expects(self::exactly(2))
143
-			->method('getUser')
144
-			->willReturn($user);
145
-		$this->config
146
-			->expects(self::once())
147
-			->method('getUserValue')
148
-			->with('MyUserUid', 'core', 'lang', null)
149
-			->willReturn('jp');
150
-
151
-		self::assertSame('jp', $factory->findLanguage('MyApp'));
152
-	}
153
-
154
-	public function testFindLanguageWithNotExistingRequestLanguageAndNotExistingStoredUserLanguage(): void {
155
-		$factory = $this->getFactory(['languageExists'], true);
156
-		$this->invokePrivate($factory, 'requestLanguage', ['de']);
157
-		$factory->expects($this->exactly(3))
158
-			->method('languageExists')
159
-			->willReturnMap([
160
-				['MyApp', 'de', false],
161
-				['MyApp', 'jp', false],
162
-				['MyApp', 'es', true],
163
-			]);
164
-		$this->config
165
-			->expects($this->exactly(2))
166
-			->method('getSystemValue')
167
-			->willReturnMap([
168
-				['force_language', false, false],
169
-				['default_language', false, 'es']
170
-			]);
171
-		$user = $this->createMock(IUser::class);
172
-		$user->expects(self::once())
173
-			->method('getUID')
174
-			->willReturn('MyUserUid');
175
-		$this->userSession
176
-			->expects(self::exactly(2))
177
-			->method('getUser')
178
-			->willReturn($user);
179
-		$this->config
180
-			->expects(self::once())
181
-			->method('getUserValue')
182
-			->with('MyUserUid', 'core', 'lang', null)
183
-			->willReturn('jp');
184
-
185
-		self::assertSame('es', $factory->findLanguage('MyApp'));
186
-	}
187
-
188
-	public function testFindLanguageWithNotExistingRequestLanguageAndNotExistingStoredUserLanguageAndNotExistingDefault(): void {
189
-		$factory = $this->getFactory(['languageExists'], true);
190
-		$this->invokePrivate($factory, 'requestLanguage', ['de']);
191
-		$factory->expects($this->exactly(3))
192
-			->method('languageExists')
193
-			->willReturnMap([
194
-				['MyApp', 'de', false],
195
-				['MyApp', 'jp', false],
196
-				['MyApp', 'es', false],
197
-			]);
198
-		$this->config
199
-			->expects($this->exactly(2))
200
-			->method('getSystemValue')
201
-			->willReturnMap([
202
-				['force_language', false, false],
203
-				['default_language', false, 'es']
204
-			]);
205
-		$user = $this->createMock(IUser::class);
206
-		$user->expects(self::once())
207
-			->method('getUID')
208
-			->willReturn('MyUserUid');
209
-		$this->userSession
210
-			->expects(self::exactly(2))
211
-			->method('getUser')
212
-			->willReturn($user);
213
-		$this->config
214
-			->expects(self::once())
215
-			->method('getUserValue')
216
-			->with('MyUserUid', 'core', 'lang', null)
217
-			->willReturn('jp');
218
-		$this->config
219
-			->expects(self::never())
220
-			->method('setUserValue');
221
-
222
-		self::assertSame('en', $factory->findLanguage('MyApp'));
223
-	}
224
-
225
-	public function testFindLanguageWithNotExistingRequestLanguageAndNotExistingStoredUserLanguageAndNotExistingDefaultAndNoAppInScope(): void {
226
-		$factory = $this->getFactory(['languageExists'], true);
227
-		$this->invokePrivate($factory, 'requestLanguage', ['de']);
228
-		$factory->expects($this->exactly(3))
229
-			->method('languageExists')
230
-			->willReturnMap([
231
-				['MyApp', 'de', false],
232
-				['MyApp', 'jp', false],
233
-				['MyApp', 'es', false],
234
-			]);
235
-		$this->config
236
-			->expects($this->exactly(2))
237
-			->method('getSystemValue')
238
-			->willReturnMap([
239
-				['force_language', false, false],
240
-				['default_language', false, 'es']
241
-			]);
242
-		$user = $this->createMock(IUser::class);
243
-		$user->expects(self::once())
244
-			->method('getUID')
245
-			->willReturn('MyUserUid');
246
-		$this->userSession
247
-			->expects(self::exactly(2))
248
-			->method('getUser')
249
-			->willReturn($user);
250
-		$this->config
251
-			->expects(self::once())
252
-			->method('getUserValue')
253
-			->with('MyUserUid', 'core', 'lang', null)
254
-			->willReturn('jp');
255
-		$this->config
256
-			->expects(self::never())
257
-			->method('setUserValue')
258
-			->with('MyUserUid', 'core', 'lang', 'en');
259
-
260
-
261
-		self::assertSame('en', $factory->findLanguage('MyApp'));
262
-	}
263
-
264
-	public function testFindLanguageWithForcedLanguage(): void {
265
-		$factory = $this->getFactory(['languageExists']);
266
-		$this->config
267
-			->expects($this->once())
268
-			->method('getSystemValue')
269
-			->with('force_language', false)
270
-			->willReturn('de');
271
-
272
-		$factory->expects($this->once())
273
-			->method('languageExists')
274
-			->with('MyApp', 'de')
275
-			->willReturn(true);
276
-
277
-		self::assertSame('de', $factory->findLanguage('MyApp'));
278
-	}
279
-
280
-	/**
281
-	 * @dataProvider dataFindAvailableLanguages
282
-	 *
283
-	 * @param string|null $app
284
-	 */
285
-	public function testFindAvailableLanguages($app): void {
286
-		$factory = $this->getFactory(['findL10nDir']);
287
-		$factory->expects(self::once())
288
-			->method('findL10nDir')
289
-			->with($app)
290
-			->willReturn(\OC::$SERVERROOT . '/tests/data/l10n/');
291
-
292
-		self::assertEqualsCanonicalizing(['cs', 'de', 'en', 'ru'], $factory->findAvailableLanguages($app));
293
-	}
294
-
295
-	public static function dataLanguageExists(): array {
296
-		return [
297
-			[null, 'en', [], true],
298
-			[null, 'de', [], false],
299
-			[null, 'de', ['ru'], false],
300
-			[null, 'de', ['ru', 'de'], true],
301
-			['files', 'en', [], true],
302
-			['files', 'de', [], false],
303
-			['files', 'de', ['ru'], false],
304
-			['files', 'de', ['de', 'ru'], true],
305
-		];
306
-	}
307
-
308
-	public function testFindAvailableLanguagesWithThemes(): void {
309
-		$this->serverRoot .= '/tests/data';
310
-		$app = 'files';
311
-
312
-		$factory = $this->getFactory(['findL10nDir']);
313
-		$factory->expects(self::once())
314
-			->method('findL10nDir')
315
-			->with($app)
316
-			->willReturn($this->serverRoot . '/apps/files/l10n/');
317
-		$this->config
318
-			->expects(self::once())
319
-			->method('getSystemValueString')
320
-			->with('theme')
321
-			->willReturn('abc');
322
-
323
-		self::assertEqualsCanonicalizing(['en', 'zz'], $factory->findAvailableLanguages($app));
324
-	}
325
-
326
-	/**
327
-	 * @dataProvider dataLanguageExists
328
-	 *
329
-	 * @param string|null $app
330
-	 * @param string $lang
331
-	 * @param string[] $availableLanguages
332
-	 * @param string $expected
333
-	 */
334
-	public function testLanguageExists($app, $lang, array $availableLanguages, $expected): void {
335
-		$factory = $this->getFactory(['findAvailableLanguages']);
336
-		$factory->expects(($lang === 'en') ? self::never() : self::once())
337
-			->method('findAvailableLanguages')
338
-			->with($app)
339
-			->willReturn($availableLanguages);
340
-
341
-		self::assertSame($expected, $factory->languageExists($app, $lang));
342
-	}
343
-
344
-	public static function dataSetLanguageFromRequest(): array {
345
-		return [
346
-			// Language is available
347
-			[null, 'de', ['de'], 'de'],
348
-			[null, 'de,en', ['de'], 'de'],
349
-			[null, 'de-DE,en-US;q=0.8,en;q=0.6', ['de'], 'de'],
350
-			// Language is not available
351
-			[null, 'de', ['ru'], new LanguageNotFoundException()],
352
-			[null, 'de,en', ['ru', 'en'], 'en'],
353
-			[null, 'de-DE,en-US;q=0.8,en;q=0.6', ['ru', 'en'], 'en'],
354
-
355
-			// Language for app
356
-			['files_pdfviewer', 'de', ['de'], 'de'],
357
-			['files_pdfviewer', 'de,en', ['de'], 'de'],
358
-			['files_pdfviewer', 'de-DE,en-US;q=0.8,en;q=0.6', ['de'], 'de'],
359
-			// Language for app is not available
360
-			['files_pdfviewer', 'de', ['ru'], new LanguageNotFoundException()],
361
-			['files_pdfviewer', 'de,en', ['ru', 'en'], 'en'],
362
-			['files_pdfviewer', 'de-DE,en-US;q=0.8,en;q=0.6', ['ru', 'en'], 'en'],
363
-		];
364
-	}
365
-
366
-	/**
367
-	 * @dataProvider dataSetLanguageFromRequest
368
-	 *
369
-	 * @param string|null $app
370
-	 * @param string $header
371
-	 * @param string[] $availableLanguages
372
-	 * @param string $expected
373
-	 */
374
-	public function testGetLanguageFromRequest($app, $header, array $availableLanguages, $expected): void {
375
-		$factory = $this->getFactory(['findAvailableLanguages', 'respectDefaultLanguage']);
376
-		$factory->expects(self::once())
377
-			->method('findAvailableLanguages')
378
-			->with($app)
379
-			->willReturn($availableLanguages);
380
-
381
-		$factory->expects(self::any())
382
-			->method('respectDefaultLanguage')->willReturnCallback(function ($app, $lang) {
383
-				return $lang;
384
-			});
385
-
386
-		$this->request->expects(self::once())
387
-			->method('getHeader')
388
-			->with('ACCEPT_LANGUAGE')
389
-			->willReturn($header);
390
-
391
-		if ($expected instanceof LanguageNotFoundException) {
392
-			$this->expectException(LanguageNotFoundException::class);
393
-			self::invokePrivate($factory, 'getLanguageFromRequest', [$app]);
394
-		} else {
395
-			self::assertSame($expected, self::invokePrivate($factory, 'getLanguageFromRequest', [$app]), 'Asserting returned language');
396
-		}
397
-	}
398
-
399
-	public static function dataGetL10nFilesForApp(): array {
400
-		return [
401
-			['', 'de', [\OC::$SERVERROOT . '/core/l10n/de.json']],
402
-			['core', 'ru', [\OC::$SERVERROOT . '/core/l10n/ru.json']],
403
-			['lib', 'ru', [\OC::$SERVERROOT . '/lib/l10n/ru.json']],
404
-			['settings', 'de', [\OC::$SERVERROOT . '/apps/settings/l10n/de.json']],
405
-			['files', 'de', [\OC::$SERVERROOT . '/apps/files/l10n/de.json']],
406
-			['files', '_lang_never_exists_', []],
407
-			['_app_never_exists_', 'de', [\OC::$SERVERROOT . '/core/l10n/de.json']],
408
-		];
409
-	}
410
-
411
-	/**
412
-	 * @dataProvider dataGetL10nFilesForApp
413
-	 *
414
-	 * @param string $app
415
-	 * @param string $expected
416
-	 */
417
-	public function testGetL10nFilesForApp($app, $lang, $expected): void {
418
-		$factory = $this->getFactory();
419
-		if (in_array($app, ['settings','files'])) {
420
-			$this->appManager
421
-				->method('getAppPath')
422
-				->with($app)
423
-				->willReturn(\OC::$SERVERROOT . '/apps/' . $app);
424
-		} else {
425
-			$this->appManager
426
-				->method('getAppPath')
427
-				->with($app)
428
-				->willThrowException(new AppPathNotFoundException());
429
-		}
430
-		self::assertSame($expected, $this->invokePrivate($factory, 'getL10nFilesForApp', [$app, $lang]));
431
-	}
432
-
433
-	public static function dataFindL10NDir(): array {
434
-		return [
435
-			['', \OC::$SERVERROOT . '/core/l10n/'],
436
-			['core', \OC::$SERVERROOT . '/core/l10n/'],
437
-			['lib', \OC::$SERVERROOT . '/lib/l10n/'],
438
-			['settings', \OC::$SERVERROOT . '/apps/settings/l10n/'],
439
-			['files', \OC::$SERVERROOT . '/apps/files/l10n/'],
440
-			['_app_never_exists_', \OC::$SERVERROOT . '/core/l10n/'],
441
-		];
442
-	}
443
-
444
-	/**
445
-	 * @dataProvider dataFindL10NDir
446
-	 *
447
-	 * @param string $app
448
-	 * @param string $expected
449
-	 */
450
-	public function testFindL10NDir($app, $expected): void {
451
-		$factory = $this->getFactory();
452
-		if (in_array($app, ['settings','files'])) {
453
-			$this->appManager
454
-				->method('getAppPath')
455
-				->with($app)
456
-				->willReturn(\OC::$SERVERROOT . '/apps/' . $app);
457
-		} else {
458
-			$this->appManager
459
-				->method('getAppPath')
460
-				->with($app)
461
-				->willThrowException(new AppPathNotFoundException());
462
-		}
463
-		self::assertSame($expected, $this->invokePrivate($factory, 'findL10nDir', [$app]));
464
-	}
465
-
466
-	public static function dataFindLanguage(): array {
467
-		return [
468
-			// Not logged in
469
-			[false, [], 'en'],
470
-			[false, ['fr'], 'fr'],
471
-			[false, ['de', 'fr'], 'de'],
472
-			[false, ['nl', 'de', 'fr'], 'de'],
473
-
474
-			[true, [], 'en'],
475
-			[true, ['fr'], 'fr'],
476
-			[true, ['de', 'fr'], 'de'],
477
-			[true, ['nl', 'de', 'fr'], 'nl'],
478
-		];
479
-	}
480
-
481
-	/**
482
-	 * @dataProvider dataFindLanguage
483
-	 *
484
-	 * @param bool $loggedIn
485
-	 * @param array $availableLang
486
-	 * @param string $expected
487
-	 */
488
-	public function testFindLanguage($loggedIn, $availableLang, $expected): void {
489
-		$userLang = 'nl';
490
-		$browserLang = 'de';
491
-		$defaultLang = 'fr';
492
-
493
-		$this->config->expects(self::any())
494
-			->method('getSystemValue')
495
-			->willReturnCallback(function ($var, $default) use ($defaultLang) {
496
-				if ($var === 'default_language') {
497
-					return $defaultLang;
498
-				} else {
499
-					return $default;
500
-				}
501
-			});
502
-
503
-		if ($loggedIn) {
504
-			$user = $this->createMock(IUser::class);
505
-			$user->expects(self::any())
506
-				->method('getUID')
507
-				->willReturn('MyUserUid');
508
-			$this->userSession
509
-				->expects(self::any())
510
-				->method('getUser')
511
-				->willReturn($user);
512
-			$this->config->expects(self::any())
513
-				->method('getUserValue')
514
-				->with('MyUserUid', 'core', 'lang', null)
515
-				->willReturn($userLang);
516
-		} else {
517
-			$this->userSession
518
-				->expects(self::any())
519
-				->method('getUser')
520
-				->willReturn(null);
521
-		}
522
-
523
-		$this->request->expects(self::any())
524
-			->method('getHeader')
525
-			->with($this->equalTo('ACCEPT_LANGUAGE'))
526
-			->willReturn($browserLang);
527
-
528
-		$factory = $this->getFactory(['languageExists', 'findAvailableLanguages', 'respectDefaultLanguage']);
529
-		$factory->expects(self::any())
530
-			->method('languageExists')
531
-			->willReturnCallback(function ($app, $lang) use ($availableLang) {
532
-				return in_array($lang, $availableLang);
533
-			});
534
-		$factory->expects(self::any())
535
-			->method('findAvailableLanguages')
536
-			->willReturnCallback(function ($app) use ($availableLang) {
537
-				return $availableLang;
538
-			});
539
-		$factory->expects(self::any())
540
-			->method('respectDefaultLanguage')->willReturnCallback(function ($app, $lang) {
541
-				return $lang;
542
-			});
543
-
544
-		$lang = $factory->findLanguage();
545
-
546
-		self::assertSame($expected, $lang);
547
-	}
548
-
549
-	public function testFindGenericLanguageByEnforcedLanguage(): void {
550
-		$factory = $this->getFactory();
551
-		$this->config->expects(self::once())
552
-			->method('getSystemValue')
553
-			->with('force_language', false)
554
-			->willReturn('cz');
555
-
556
-		$lang = $factory->findGenericLanguage();
557
-
558
-		self::assertSame('cz', $lang);
559
-	}
560
-
561
-	public function testFindGenericLanguageByDefaultLanguage(): void {
562
-		$factory = $this->getFactory(['languageExists']);
563
-		$this->config->expects(self::exactly(2))
564
-			->method('getSystemValue')
565
-			->willReturnMap([
566
-				['force_language', false, false,],
567
-				['default_language', false, 'cz',],
568
-			]);
569
-		$factory->expects(self::once())
570
-			->method('languageExists')
571
-			->with(null, 'cz')
572
-			->willReturn(true);
573
-
574
-		$lang = $factory->findGenericLanguage();
575
-
576
-		self::assertSame('cz', $lang);
577
-	}
578
-
579
-	public function testFindGenericLanguageByUserLanguage(): void {
580
-		$factory = $this->getFactory();
581
-		$this->config->expects(self::exactly(2))
582
-			->method('getSystemValue')
583
-			->willReturnMap([
584
-				['force_language', false, false,],
585
-				['default_language', false, false,],
586
-			]);
587
-		$user = $this->createMock(IUser::class);
588
-		$this->userSession->expects(self::once())
589
-			->method('getUser')
590
-			->willReturn($user);
591
-		$user->method('getUID')->willReturn('user123');
592
-		$this->config->expects(self::once())
593
-			->method('getUserValue')
594
-			->with('user123', 'core', 'lang', null)
595
-			->willReturn('cz');
596
-
597
-		$lang = $factory->findGenericLanguage();
598
-
599
-		self::assertSame('cz', $lang);
600
-	}
601
-
602
-	public function testFindGenericLanguageByRequestLanguage(): void {
603
-		$factory = $this->getFactory(['findAvailableLanguages', 'languageExists']);
604
-		$this->config->method('getSystemValue')
605
-			->willReturnMap([
606
-				['force_language', false, false,],
607
-				['default_language', false, false,],
608
-			]);
609
-		$user = $this->createMock(IUser::class);
610
-		$this->userSession->expects(self::once())
611
-			->method('getUser')
612
-			->willReturn($user);
613
-		$user->method('getUID')->willReturn('user123');
614
-		$this->config->expects(self::once())
615
-			->method('getUserValue')
616
-			->with('user123', 'core', 'lang', null)
617
-			->willReturn(null);
618
-		$this->request->expects(self::once())
619
-			->method('getHeader')
620
-			->with('ACCEPT_LANGUAGE')
621
-			->willReturn('cz');
622
-		$factory->expects(self::once())
623
-			->method('findAvailableLanguages')
624
-			->with(null)
625
-			->willReturn(['cz']);
626
-
627
-		$lang = $factory->findGenericLanguage();
628
-
629
-		self::assertSame('cz', $lang);
630
-	}
631
-
632
-	public function testFindGenericLanguageFallback(): void {
633
-		$factory = $this->getFactory(['findAvailableLanguages', 'languageExists']);
634
-		$this->config->method('getSystemValue')
635
-			->willReturnMap([
636
-				['force_language', false, false,],
637
-				['default_language', false, false,],
638
-			]);
639
-		$user = $this->createMock(IUser::class);
640
-		$this->userSession->expects(self::once())
641
-			->method('getUser')
642
-			->willReturn($user);
643
-		$user->method('getUID')->willReturn('user123');
644
-		$this->config->expects(self::once())
645
-			->method('getUserValue')
646
-			->with('user123', 'core', 'lang', null)
647
-			->willReturn(null);
648
-		$this->request->expects(self::once())
649
-			->method('getHeader')
650
-			->with('ACCEPT_LANGUAGE')
651
-			->willReturn('');
652
-		$factory->expects(self::never())
653
-			->method('findAvailableLanguages');
654
-		$factory->expects(self::never())
655
-			->method('languageExists');
656
-
657
-		$lang = $factory->findGenericLanguage();
658
-
659
-		self::assertSame('en', $lang);
660
-	}
661
-
662
-	public static function dataTestRespectDefaultLanguage(): array {
663
-		return [
664
-			['de', 'de_DE', true, 'de_DE'],
665
-			['de', 'de', true, 'de'],
666
-			['de', false, true, 'de'],
667
-			['fr', 'de_DE', true, 'fr'],
668
-		];
669
-	}
670
-
671
-	/**
672
-	 * test if we respect default language if possible
673
-	 *
674
-	 * @dataProvider dataTestRespectDefaultLanguage
675
-	 *
676
-	 * @param string $lang
677
-	 * @param string $defaultLanguage
678
-	 * @param bool $langExists
679
-	 * @param string $expected
680
-	 */
681
-	public function testRespectDefaultLanguage($lang, $defaultLanguage, $langExists, $expected): void {
682
-		$factory = $this->getFactory(['languageExists']);
683
-		$factory->expects(self::any())
684
-			->method('languageExists')->willReturn($langExists);
685
-		$this->config->expects(self::any())
686
-			->method('getSystemValue')->with('default_language', false)->willReturn($defaultLanguage);
687
-
688
-		$result = $this->invokePrivate($factory, 'respectDefaultLanguage', ['app', $lang]);
689
-		self::assertSame($expected, $result);
690
-	}
691
-
692
-	public static function dataTestReduceToLanguages(): array {
693
-		return [
694
-			['en', ['en', 'de', 'fr', 'it', 'es'], ['en', 'fr', 'de'], ['en', 'fr', 'de']],
695
-			['en', ['en', 'de', 'fr', 'it', 'es'], ['en', 'de'], ['en', 'de']],
696
-			['en', ['en', 'de', 'fr', 'it', 'es'], [], ['de', 'en', 'es', 'fr', 'it']],
697
-		];
698
-	}
699
-
700
-	/**
701
-	 * test
702
-	 * - if available languages set can be reduced by configuration
703
-	 * - if available languages set is not reduced to an empty set if
704
-	 *   the reduce config is an empty set
705
-	 *
706
-	 * @dataProvider dataTestReduceToLanguages
707
-	 *
708
-	 * @param string $lang
709
-	 * @param array $availableLanguages
710
-	 * @param array $reducedLanguageSet
711
-	 * @param array $expected
712
-	 */
713
-	public function testReduceLanguagesByConfiguration(string $lang, array $availableLanguages, array $reducedLanguageSet, array $expected): void {
714
-		$factory = $this->getFactory(['findAvailableLanguages', 'languageExists']);
715
-		$factory->expects(self::any())
716
-			->method('languageExists')->willReturn(true);
717
-		$factory->expects(self::any())
718
-			->method('findAvailableLanguages')
719
-			->willReturnCallback(function ($app) use ($availableLanguages) {
720
-				return $availableLanguages;
721
-			});
722
-
723
-		$this->config
724
-			->method('getSystemValue')
725
-			->willReturnMap([
726
-				['force_language', false, false],
727
-				['default_language', false, $lang],
728
-				['reduce_to_languages', [], $reducedLanguageSet]
729
-			]);
730
-
731
-		$result = $this->invokePrivate($factory, 'getLanguages');
732
-		$commonLanguagesCodes = array_map(function ($lang) {
733
-			return $lang['code'];
734
-		}, $result['commonLanguages']);
735
-
736
-		self::assertEqualsCanonicalizing($expected, $commonLanguagesCodes);
737
-	}
738
-
739
-	public static function languageIteratorRequestProvider(): array {
740
-		return [
741
-			[ true, true],
742
-			[ false, true],
743
-			[ false, false],
744
-		];
745
-	}
746
-
747
-	/**
748
-	 * @dataProvider languageIteratorRequestProvider
749
-	 */
750
-	public function testGetLanguageIterator(bool $hasSession, bool $mockUser): void {
751
-		$factory = $this->getFactory();
752
-		$user = null;
753
-
754
-		if (!$mockUser) {
755
-			$matcher = $this->userSession->expects(self::once())
756
-				->method('getUser');
757
-
758
-			if ($hasSession) {
759
-				$matcher->willReturn($this->createMock(IUser::class));
760
-			} else {
761
-				$this->expectException(\RuntimeException::class);
762
-			}
763
-		} else {
764
-			$user = $this->createMock(IUser::class);
765
-		}
766
-
767
-		$iterator = $factory->getLanguageIterator($user);
768
-		self::assertInstanceOf(ILanguageIterator::class, $iterator);
769
-	}
770
-
771
-	public static function dataGetLanguageDirection(): array {
772
-		return [
773
-			['en', 'ltr'],
774
-			['de', 'ltr'],
775
-			['fa', 'rtl'],
776
-			['ar', 'rtl']
777
-		];
778
-	}
779
-
780
-	/**
781
-	 * @dataProvider dataGetLanguageDirection
782
-	 */
783
-	public function testGetLanguageDirection(string $language, string $expectedDirection) {
784
-		$factory = $this->getFactory();
785
-
786
-		self::assertEquals($expectedDirection, $factory->getLanguageDirection($language));
787
-	}
27
+    /** @var IConfig|MockObject */
28
+    protected $config;
29
+
30
+    /** @var IRequest|MockObject */
31
+    protected $request;
32
+
33
+    /** @var IUserSession|MockObject */
34
+    protected $userSession;
35
+
36
+    /** @var ICacheFactory|MockObject */
37
+    protected $cacheFactory;
38
+
39
+    /** @var string */
40
+    protected $serverRoot;
41
+
42
+    /** @var IAppManager|MockObject */
43
+    protected IAppManager $appManager;
44
+
45
+    protected function setUp(): void {
46
+        parent::setUp();
47
+
48
+        $this->config = $this->createMock(IConfig::class);
49
+        $this->request = $this->createMock(IRequest::class);
50
+        $this->userSession = $this->createMock(IUserSession::class);
51
+        $this->cacheFactory = $this->createMock(ICacheFactory::class);
52
+        $this->appManager = $this->createMock(IAppManager::class);
53
+
54
+        $this->serverRoot = \OC::$SERVERROOT;
55
+
56
+        $this->config
57
+            ->method('getSystemValueBool')
58
+            ->willReturnMap([
59
+                ['installed', false, true],
60
+            ]);
61
+    }
62
+
63
+    /**
64
+     * @param string[] $methods
65
+     * @param bool $mockRequestGetHeaderMethod
66
+     *
67
+     * @return Factory|MockObject
68
+     */
69
+    protected function getFactory(array $methods = [], $mockRequestGetHeaderMethod = false) {
70
+        if ($mockRequestGetHeaderMethod) {
71
+            $this->request->expects(self::any())
72
+                ->method('getHeader')
73
+                ->willReturn('');
74
+        }
75
+
76
+        if (!empty($methods)) {
77
+            return $this->getMockBuilder(Factory::class)
78
+                ->setConstructorArgs([
79
+                    $this->config,
80
+                    $this->request,
81
+                    $this->userSession,
82
+                    $this->cacheFactory,
83
+                    $this->serverRoot,
84
+                    $this->appManager,
85
+                ])
86
+                ->onlyMethods($methods)
87
+                ->getMock();
88
+        }
89
+
90
+        return new Factory($this->config, $this->request, $this->userSession, $this->cacheFactory, $this->serverRoot, $this->appManager);
91
+    }
92
+
93
+    public static function dataFindAvailableLanguages(): array {
94
+        return [
95
+            [null],
96
+            ['files'],
97
+        ];
98
+    }
99
+
100
+    public function testFindLanguageWithExistingRequestLanguageAndNoApp(): void {
101
+        $factory = $this->getFactory(['languageExists']);
102
+        $this->invokePrivate($factory, 'requestLanguage', ['de']);
103
+        $factory->expects(self::once())
104
+            ->method('languageExists')
105
+            ->with(null, 'de')
106
+            ->willReturn(true);
107
+
108
+        self::assertSame('de', $factory->findLanguage());
109
+    }
110
+
111
+    public function testFindLanguageWithExistingRequestLanguageAndApp(): void {
112
+        $factory = $this->getFactory(['languageExists']);
113
+        $this->invokePrivate($factory, 'requestLanguage', ['de']);
114
+        $factory->expects(self::once())
115
+            ->method('languageExists')
116
+            ->with('MyApp', 'de')
117
+            ->willReturn(true);
118
+
119
+        self::assertSame('de', $factory->findLanguage('MyApp'));
120
+    }
121
+
122
+    public function testFindLanguageWithNotExistingRequestLanguageAndExistingStoredUserLanguage(): void {
123
+        $factory = $this->getFactory(['languageExists']);
124
+        $this->invokePrivate($factory, 'requestLanguage', ['de']);
125
+        $factory->expects($this->exactly(2))
126
+            ->method('languageExists')
127
+            ->willReturnMap([
128
+                ['MyApp', 'de', false],
129
+                ['MyApp', 'jp', true],
130
+            ]);
131
+        $this->config
132
+            ->expects($this->exactly(1))
133
+            ->method('getSystemValue')
134
+            ->willReturnMap([
135
+                ['force_language', false, false],
136
+            ]);
137
+        $user = $this->createMock(IUser::class);
138
+        $user->expects(self::once())
139
+            ->method('getUID')
140
+            ->willReturn('MyUserUid');
141
+        $this->userSession
142
+            ->expects(self::exactly(2))
143
+            ->method('getUser')
144
+            ->willReturn($user);
145
+        $this->config
146
+            ->expects(self::once())
147
+            ->method('getUserValue')
148
+            ->with('MyUserUid', 'core', 'lang', null)
149
+            ->willReturn('jp');
150
+
151
+        self::assertSame('jp', $factory->findLanguage('MyApp'));
152
+    }
153
+
154
+    public function testFindLanguageWithNotExistingRequestLanguageAndNotExistingStoredUserLanguage(): void {
155
+        $factory = $this->getFactory(['languageExists'], true);
156
+        $this->invokePrivate($factory, 'requestLanguage', ['de']);
157
+        $factory->expects($this->exactly(3))
158
+            ->method('languageExists')
159
+            ->willReturnMap([
160
+                ['MyApp', 'de', false],
161
+                ['MyApp', 'jp', false],
162
+                ['MyApp', 'es', true],
163
+            ]);
164
+        $this->config
165
+            ->expects($this->exactly(2))
166
+            ->method('getSystemValue')
167
+            ->willReturnMap([
168
+                ['force_language', false, false],
169
+                ['default_language', false, 'es']
170
+            ]);
171
+        $user = $this->createMock(IUser::class);
172
+        $user->expects(self::once())
173
+            ->method('getUID')
174
+            ->willReturn('MyUserUid');
175
+        $this->userSession
176
+            ->expects(self::exactly(2))
177
+            ->method('getUser')
178
+            ->willReturn($user);
179
+        $this->config
180
+            ->expects(self::once())
181
+            ->method('getUserValue')
182
+            ->with('MyUserUid', 'core', 'lang', null)
183
+            ->willReturn('jp');
184
+
185
+        self::assertSame('es', $factory->findLanguage('MyApp'));
186
+    }
187
+
188
+    public function testFindLanguageWithNotExistingRequestLanguageAndNotExistingStoredUserLanguageAndNotExistingDefault(): void {
189
+        $factory = $this->getFactory(['languageExists'], true);
190
+        $this->invokePrivate($factory, 'requestLanguage', ['de']);
191
+        $factory->expects($this->exactly(3))
192
+            ->method('languageExists')
193
+            ->willReturnMap([
194
+                ['MyApp', 'de', false],
195
+                ['MyApp', 'jp', false],
196
+                ['MyApp', 'es', false],
197
+            ]);
198
+        $this->config
199
+            ->expects($this->exactly(2))
200
+            ->method('getSystemValue')
201
+            ->willReturnMap([
202
+                ['force_language', false, false],
203
+                ['default_language', false, 'es']
204
+            ]);
205
+        $user = $this->createMock(IUser::class);
206
+        $user->expects(self::once())
207
+            ->method('getUID')
208
+            ->willReturn('MyUserUid');
209
+        $this->userSession
210
+            ->expects(self::exactly(2))
211
+            ->method('getUser')
212
+            ->willReturn($user);
213
+        $this->config
214
+            ->expects(self::once())
215
+            ->method('getUserValue')
216
+            ->with('MyUserUid', 'core', 'lang', null)
217
+            ->willReturn('jp');
218
+        $this->config
219
+            ->expects(self::never())
220
+            ->method('setUserValue');
221
+
222
+        self::assertSame('en', $factory->findLanguage('MyApp'));
223
+    }
224
+
225
+    public function testFindLanguageWithNotExistingRequestLanguageAndNotExistingStoredUserLanguageAndNotExistingDefaultAndNoAppInScope(): void {
226
+        $factory = $this->getFactory(['languageExists'], true);
227
+        $this->invokePrivate($factory, 'requestLanguage', ['de']);
228
+        $factory->expects($this->exactly(3))
229
+            ->method('languageExists')
230
+            ->willReturnMap([
231
+                ['MyApp', 'de', false],
232
+                ['MyApp', 'jp', false],
233
+                ['MyApp', 'es', false],
234
+            ]);
235
+        $this->config
236
+            ->expects($this->exactly(2))
237
+            ->method('getSystemValue')
238
+            ->willReturnMap([
239
+                ['force_language', false, false],
240
+                ['default_language', false, 'es']
241
+            ]);
242
+        $user = $this->createMock(IUser::class);
243
+        $user->expects(self::once())
244
+            ->method('getUID')
245
+            ->willReturn('MyUserUid');
246
+        $this->userSession
247
+            ->expects(self::exactly(2))
248
+            ->method('getUser')
249
+            ->willReturn($user);
250
+        $this->config
251
+            ->expects(self::once())
252
+            ->method('getUserValue')
253
+            ->with('MyUserUid', 'core', 'lang', null)
254
+            ->willReturn('jp');
255
+        $this->config
256
+            ->expects(self::never())
257
+            ->method('setUserValue')
258
+            ->with('MyUserUid', 'core', 'lang', 'en');
259
+
260
+
261
+        self::assertSame('en', $factory->findLanguage('MyApp'));
262
+    }
263
+
264
+    public function testFindLanguageWithForcedLanguage(): void {
265
+        $factory = $this->getFactory(['languageExists']);
266
+        $this->config
267
+            ->expects($this->once())
268
+            ->method('getSystemValue')
269
+            ->with('force_language', false)
270
+            ->willReturn('de');
271
+
272
+        $factory->expects($this->once())
273
+            ->method('languageExists')
274
+            ->with('MyApp', 'de')
275
+            ->willReturn(true);
276
+
277
+        self::assertSame('de', $factory->findLanguage('MyApp'));
278
+    }
279
+
280
+    /**
281
+     * @dataProvider dataFindAvailableLanguages
282
+     *
283
+     * @param string|null $app
284
+     */
285
+    public function testFindAvailableLanguages($app): void {
286
+        $factory = $this->getFactory(['findL10nDir']);
287
+        $factory->expects(self::once())
288
+            ->method('findL10nDir')
289
+            ->with($app)
290
+            ->willReturn(\OC::$SERVERROOT . '/tests/data/l10n/');
291
+
292
+        self::assertEqualsCanonicalizing(['cs', 'de', 'en', 'ru'], $factory->findAvailableLanguages($app));
293
+    }
294
+
295
+    public static function dataLanguageExists(): array {
296
+        return [
297
+            [null, 'en', [], true],
298
+            [null, 'de', [], false],
299
+            [null, 'de', ['ru'], false],
300
+            [null, 'de', ['ru', 'de'], true],
301
+            ['files', 'en', [], true],
302
+            ['files', 'de', [], false],
303
+            ['files', 'de', ['ru'], false],
304
+            ['files', 'de', ['de', 'ru'], true],
305
+        ];
306
+    }
307
+
308
+    public function testFindAvailableLanguagesWithThemes(): void {
309
+        $this->serverRoot .= '/tests/data';
310
+        $app = 'files';
311
+
312
+        $factory = $this->getFactory(['findL10nDir']);
313
+        $factory->expects(self::once())
314
+            ->method('findL10nDir')
315
+            ->with($app)
316
+            ->willReturn($this->serverRoot . '/apps/files/l10n/');
317
+        $this->config
318
+            ->expects(self::once())
319
+            ->method('getSystemValueString')
320
+            ->with('theme')
321
+            ->willReturn('abc');
322
+
323
+        self::assertEqualsCanonicalizing(['en', 'zz'], $factory->findAvailableLanguages($app));
324
+    }
325
+
326
+    /**
327
+     * @dataProvider dataLanguageExists
328
+     *
329
+     * @param string|null $app
330
+     * @param string $lang
331
+     * @param string[] $availableLanguages
332
+     * @param string $expected
333
+     */
334
+    public function testLanguageExists($app, $lang, array $availableLanguages, $expected): void {
335
+        $factory = $this->getFactory(['findAvailableLanguages']);
336
+        $factory->expects(($lang === 'en') ? self::never() : self::once())
337
+            ->method('findAvailableLanguages')
338
+            ->with($app)
339
+            ->willReturn($availableLanguages);
340
+
341
+        self::assertSame($expected, $factory->languageExists($app, $lang));
342
+    }
343
+
344
+    public static function dataSetLanguageFromRequest(): array {
345
+        return [
346
+            // Language is available
347
+            [null, 'de', ['de'], 'de'],
348
+            [null, 'de,en', ['de'], 'de'],
349
+            [null, 'de-DE,en-US;q=0.8,en;q=0.6', ['de'], 'de'],
350
+            // Language is not available
351
+            [null, 'de', ['ru'], new LanguageNotFoundException()],
352
+            [null, 'de,en', ['ru', 'en'], 'en'],
353
+            [null, 'de-DE,en-US;q=0.8,en;q=0.6', ['ru', 'en'], 'en'],
354
+
355
+            // Language for app
356
+            ['files_pdfviewer', 'de', ['de'], 'de'],
357
+            ['files_pdfviewer', 'de,en', ['de'], 'de'],
358
+            ['files_pdfviewer', 'de-DE,en-US;q=0.8,en;q=0.6', ['de'], 'de'],
359
+            // Language for app is not available
360
+            ['files_pdfviewer', 'de', ['ru'], new LanguageNotFoundException()],
361
+            ['files_pdfviewer', 'de,en', ['ru', 'en'], 'en'],
362
+            ['files_pdfviewer', 'de-DE,en-US;q=0.8,en;q=0.6', ['ru', 'en'], 'en'],
363
+        ];
364
+    }
365
+
366
+    /**
367
+     * @dataProvider dataSetLanguageFromRequest
368
+     *
369
+     * @param string|null $app
370
+     * @param string $header
371
+     * @param string[] $availableLanguages
372
+     * @param string $expected
373
+     */
374
+    public function testGetLanguageFromRequest($app, $header, array $availableLanguages, $expected): void {
375
+        $factory = $this->getFactory(['findAvailableLanguages', 'respectDefaultLanguage']);
376
+        $factory->expects(self::once())
377
+            ->method('findAvailableLanguages')
378
+            ->with($app)
379
+            ->willReturn($availableLanguages);
380
+
381
+        $factory->expects(self::any())
382
+            ->method('respectDefaultLanguage')->willReturnCallback(function ($app, $lang) {
383
+                return $lang;
384
+            });
385
+
386
+        $this->request->expects(self::once())
387
+            ->method('getHeader')
388
+            ->with('ACCEPT_LANGUAGE')
389
+            ->willReturn($header);
390
+
391
+        if ($expected instanceof LanguageNotFoundException) {
392
+            $this->expectException(LanguageNotFoundException::class);
393
+            self::invokePrivate($factory, 'getLanguageFromRequest', [$app]);
394
+        } else {
395
+            self::assertSame($expected, self::invokePrivate($factory, 'getLanguageFromRequest', [$app]), 'Asserting returned language');
396
+        }
397
+    }
398
+
399
+    public static function dataGetL10nFilesForApp(): array {
400
+        return [
401
+            ['', 'de', [\OC::$SERVERROOT . '/core/l10n/de.json']],
402
+            ['core', 'ru', [\OC::$SERVERROOT . '/core/l10n/ru.json']],
403
+            ['lib', 'ru', [\OC::$SERVERROOT . '/lib/l10n/ru.json']],
404
+            ['settings', 'de', [\OC::$SERVERROOT . '/apps/settings/l10n/de.json']],
405
+            ['files', 'de', [\OC::$SERVERROOT . '/apps/files/l10n/de.json']],
406
+            ['files', '_lang_never_exists_', []],
407
+            ['_app_never_exists_', 'de', [\OC::$SERVERROOT . '/core/l10n/de.json']],
408
+        ];
409
+    }
410
+
411
+    /**
412
+     * @dataProvider dataGetL10nFilesForApp
413
+     *
414
+     * @param string $app
415
+     * @param string $expected
416
+     */
417
+    public function testGetL10nFilesForApp($app, $lang, $expected): void {
418
+        $factory = $this->getFactory();
419
+        if (in_array($app, ['settings','files'])) {
420
+            $this->appManager
421
+                ->method('getAppPath')
422
+                ->with($app)
423
+                ->willReturn(\OC::$SERVERROOT . '/apps/' . $app);
424
+        } else {
425
+            $this->appManager
426
+                ->method('getAppPath')
427
+                ->with($app)
428
+                ->willThrowException(new AppPathNotFoundException());
429
+        }
430
+        self::assertSame($expected, $this->invokePrivate($factory, 'getL10nFilesForApp', [$app, $lang]));
431
+    }
432
+
433
+    public static function dataFindL10NDir(): array {
434
+        return [
435
+            ['', \OC::$SERVERROOT . '/core/l10n/'],
436
+            ['core', \OC::$SERVERROOT . '/core/l10n/'],
437
+            ['lib', \OC::$SERVERROOT . '/lib/l10n/'],
438
+            ['settings', \OC::$SERVERROOT . '/apps/settings/l10n/'],
439
+            ['files', \OC::$SERVERROOT . '/apps/files/l10n/'],
440
+            ['_app_never_exists_', \OC::$SERVERROOT . '/core/l10n/'],
441
+        ];
442
+    }
443
+
444
+    /**
445
+     * @dataProvider dataFindL10NDir
446
+     *
447
+     * @param string $app
448
+     * @param string $expected
449
+     */
450
+    public function testFindL10NDir($app, $expected): void {
451
+        $factory = $this->getFactory();
452
+        if (in_array($app, ['settings','files'])) {
453
+            $this->appManager
454
+                ->method('getAppPath')
455
+                ->with($app)
456
+                ->willReturn(\OC::$SERVERROOT . '/apps/' . $app);
457
+        } else {
458
+            $this->appManager
459
+                ->method('getAppPath')
460
+                ->with($app)
461
+                ->willThrowException(new AppPathNotFoundException());
462
+        }
463
+        self::assertSame($expected, $this->invokePrivate($factory, 'findL10nDir', [$app]));
464
+    }
465
+
466
+    public static function dataFindLanguage(): array {
467
+        return [
468
+            // Not logged in
469
+            [false, [], 'en'],
470
+            [false, ['fr'], 'fr'],
471
+            [false, ['de', 'fr'], 'de'],
472
+            [false, ['nl', 'de', 'fr'], 'de'],
473
+
474
+            [true, [], 'en'],
475
+            [true, ['fr'], 'fr'],
476
+            [true, ['de', 'fr'], 'de'],
477
+            [true, ['nl', 'de', 'fr'], 'nl'],
478
+        ];
479
+    }
480
+
481
+    /**
482
+     * @dataProvider dataFindLanguage
483
+     *
484
+     * @param bool $loggedIn
485
+     * @param array $availableLang
486
+     * @param string $expected
487
+     */
488
+    public function testFindLanguage($loggedIn, $availableLang, $expected): void {
489
+        $userLang = 'nl';
490
+        $browserLang = 'de';
491
+        $defaultLang = 'fr';
492
+
493
+        $this->config->expects(self::any())
494
+            ->method('getSystemValue')
495
+            ->willReturnCallback(function ($var, $default) use ($defaultLang) {
496
+                if ($var === 'default_language') {
497
+                    return $defaultLang;
498
+                } else {
499
+                    return $default;
500
+                }
501
+            });
502
+
503
+        if ($loggedIn) {
504
+            $user = $this->createMock(IUser::class);
505
+            $user->expects(self::any())
506
+                ->method('getUID')
507
+                ->willReturn('MyUserUid');
508
+            $this->userSession
509
+                ->expects(self::any())
510
+                ->method('getUser')
511
+                ->willReturn($user);
512
+            $this->config->expects(self::any())
513
+                ->method('getUserValue')
514
+                ->with('MyUserUid', 'core', 'lang', null)
515
+                ->willReturn($userLang);
516
+        } else {
517
+            $this->userSession
518
+                ->expects(self::any())
519
+                ->method('getUser')
520
+                ->willReturn(null);
521
+        }
522
+
523
+        $this->request->expects(self::any())
524
+            ->method('getHeader')
525
+            ->with($this->equalTo('ACCEPT_LANGUAGE'))
526
+            ->willReturn($browserLang);
527
+
528
+        $factory = $this->getFactory(['languageExists', 'findAvailableLanguages', 'respectDefaultLanguage']);
529
+        $factory->expects(self::any())
530
+            ->method('languageExists')
531
+            ->willReturnCallback(function ($app, $lang) use ($availableLang) {
532
+                return in_array($lang, $availableLang);
533
+            });
534
+        $factory->expects(self::any())
535
+            ->method('findAvailableLanguages')
536
+            ->willReturnCallback(function ($app) use ($availableLang) {
537
+                return $availableLang;
538
+            });
539
+        $factory->expects(self::any())
540
+            ->method('respectDefaultLanguage')->willReturnCallback(function ($app, $lang) {
541
+                return $lang;
542
+            });
543
+
544
+        $lang = $factory->findLanguage();
545
+
546
+        self::assertSame($expected, $lang);
547
+    }
548
+
549
+    public function testFindGenericLanguageByEnforcedLanguage(): void {
550
+        $factory = $this->getFactory();
551
+        $this->config->expects(self::once())
552
+            ->method('getSystemValue')
553
+            ->with('force_language', false)
554
+            ->willReturn('cz');
555
+
556
+        $lang = $factory->findGenericLanguage();
557
+
558
+        self::assertSame('cz', $lang);
559
+    }
560
+
561
+    public function testFindGenericLanguageByDefaultLanguage(): void {
562
+        $factory = $this->getFactory(['languageExists']);
563
+        $this->config->expects(self::exactly(2))
564
+            ->method('getSystemValue')
565
+            ->willReturnMap([
566
+                ['force_language', false, false,],
567
+                ['default_language', false, 'cz',],
568
+            ]);
569
+        $factory->expects(self::once())
570
+            ->method('languageExists')
571
+            ->with(null, 'cz')
572
+            ->willReturn(true);
573
+
574
+        $lang = $factory->findGenericLanguage();
575
+
576
+        self::assertSame('cz', $lang);
577
+    }
578
+
579
+    public function testFindGenericLanguageByUserLanguage(): void {
580
+        $factory = $this->getFactory();
581
+        $this->config->expects(self::exactly(2))
582
+            ->method('getSystemValue')
583
+            ->willReturnMap([
584
+                ['force_language', false, false,],
585
+                ['default_language', false, false,],
586
+            ]);
587
+        $user = $this->createMock(IUser::class);
588
+        $this->userSession->expects(self::once())
589
+            ->method('getUser')
590
+            ->willReturn($user);
591
+        $user->method('getUID')->willReturn('user123');
592
+        $this->config->expects(self::once())
593
+            ->method('getUserValue')
594
+            ->with('user123', 'core', 'lang', null)
595
+            ->willReturn('cz');
596
+
597
+        $lang = $factory->findGenericLanguage();
598
+
599
+        self::assertSame('cz', $lang);
600
+    }
601
+
602
+    public function testFindGenericLanguageByRequestLanguage(): void {
603
+        $factory = $this->getFactory(['findAvailableLanguages', 'languageExists']);
604
+        $this->config->method('getSystemValue')
605
+            ->willReturnMap([
606
+                ['force_language', false, false,],
607
+                ['default_language', false, false,],
608
+            ]);
609
+        $user = $this->createMock(IUser::class);
610
+        $this->userSession->expects(self::once())
611
+            ->method('getUser')
612
+            ->willReturn($user);
613
+        $user->method('getUID')->willReturn('user123');
614
+        $this->config->expects(self::once())
615
+            ->method('getUserValue')
616
+            ->with('user123', 'core', 'lang', null)
617
+            ->willReturn(null);
618
+        $this->request->expects(self::once())
619
+            ->method('getHeader')
620
+            ->with('ACCEPT_LANGUAGE')
621
+            ->willReturn('cz');
622
+        $factory->expects(self::once())
623
+            ->method('findAvailableLanguages')
624
+            ->with(null)
625
+            ->willReturn(['cz']);
626
+
627
+        $lang = $factory->findGenericLanguage();
628
+
629
+        self::assertSame('cz', $lang);
630
+    }
631
+
632
+    public function testFindGenericLanguageFallback(): void {
633
+        $factory = $this->getFactory(['findAvailableLanguages', 'languageExists']);
634
+        $this->config->method('getSystemValue')
635
+            ->willReturnMap([
636
+                ['force_language', false, false,],
637
+                ['default_language', false, false,],
638
+            ]);
639
+        $user = $this->createMock(IUser::class);
640
+        $this->userSession->expects(self::once())
641
+            ->method('getUser')
642
+            ->willReturn($user);
643
+        $user->method('getUID')->willReturn('user123');
644
+        $this->config->expects(self::once())
645
+            ->method('getUserValue')
646
+            ->with('user123', 'core', 'lang', null)
647
+            ->willReturn(null);
648
+        $this->request->expects(self::once())
649
+            ->method('getHeader')
650
+            ->with('ACCEPT_LANGUAGE')
651
+            ->willReturn('');
652
+        $factory->expects(self::never())
653
+            ->method('findAvailableLanguages');
654
+        $factory->expects(self::never())
655
+            ->method('languageExists');
656
+
657
+        $lang = $factory->findGenericLanguage();
658
+
659
+        self::assertSame('en', $lang);
660
+    }
661
+
662
+    public static function dataTestRespectDefaultLanguage(): array {
663
+        return [
664
+            ['de', 'de_DE', true, 'de_DE'],
665
+            ['de', 'de', true, 'de'],
666
+            ['de', false, true, 'de'],
667
+            ['fr', 'de_DE', true, 'fr'],
668
+        ];
669
+    }
670
+
671
+    /**
672
+     * test if we respect default language if possible
673
+     *
674
+     * @dataProvider dataTestRespectDefaultLanguage
675
+     *
676
+     * @param string $lang
677
+     * @param string $defaultLanguage
678
+     * @param bool $langExists
679
+     * @param string $expected
680
+     */
681
+    public function testRespectDefaultLanguage($lang, $defaultLanguage, $langExists, $expected): void {
682
+        $factory = $this->getFactory(['languageExists']);
683
+        $factory->expects(self::any())
684
+            ->method('languageExists')->willReturn($langExists);
685
+        $this->config->expects(self::any())
686
+            ->method('getSystemValue')->with('default_language', false)->willReturn($defaultLanguage);
687
+
688
+        $result = $this->invokePrivate($factory, 'respectDefaultLanguage', ['app', $lang]);
689
+        self::assertSame($expected, $result);
690
+    }
691
+
692
+    public static function dataTestReduceToLanguages(): array {
693
+        return [
694
+            ['en', ['en', 'de', 'fr', 'it', 'es'], ['en', 'fr', 'de'], ['en', 'fr', 'de']],
695
+            ['en', ['en', 'de', 'fr', 'it', 'es'], ['en', 'de'], ['en', 'de']],
696
+            ['en', ['en', 'de', 'fr', 'it', 'es'], [], ['de', 'en', 'es', 'fr', 'it']],
697
+        ];
698
+    }
699
+
700
+    /**
701
+     * test
702
+     * - if available languages set can be reduced by configuration
703
+     * - if available languages set is not reduced to an empty set if
704
+     *   the reduce config is an empty set
705
+     *
706
+     * @dataProvider dataTestReduceToLanguages
707
+     *
708
+     * @param string $lang
709
+     * @param array $availableLanguages
710
+     * @param array $reducedLanguageSet
711
+     * @param array $expected
712
+     */
713
+    public function testReduceLanguagesByConfiguration(string $lang, array $availableLanguages, array $reducedLanguageSet, array $expected): void {
714
+        $factory = $this->getFactory(['findAvailableLanguages', 'languageExists']);
715
+        $factory->expects(self::any())
716
+            ->method('languageExists')->willReturn(true);
717
+        $factory->expects(self::any())
718
+            ->method('findAvailableLanguages')
719
+            ->willReturnCallback(function ($app) use ($availableLanguages) {
720
+                return $availableLanguages;
721
+            });
722
+
723
+        $this->config
724
+            ->method('getSystemValue')
725
+            ->willReturnMap([
726
+                ['force_language', false, false],
727
+                ['default_language', false, $lang],
728
+                ['reduce_to_languages', [], $reducedLanguageSet]
729
+            ]);
730
+
731
+        $result = $this->invokePrivate($factory, 'getLanguages');
732
+        $commonLanguagesCodes = array_map(function ($lang) {
733
+            return $lang['code'];
734
+        }, $result['commonLanguages']);
735
+
736
+        self::assertEqualsCanonicalizing($expected, $commonLanguagesCodes);
737
+    }
738
+
739
+    public static function languageIteratorRequestProvider(): array {
740
+        return [
741
+            [ true, true],
742
+            [ false, true],
743
+            [ false, false],
744
+        ];
745
+    }
746
+
747
+    /**
748
+     * @dataProvider languageIteratorRequestProvider
749
+     */
750
+    public function testGetLanguageIterator(bool $hasSession, bool $mockUser): void {
751
+        $factory = $this->getFactory();
752
+        $user = null;
753
+
754
+        if (!$mockUser) {
755
+            $matcher = $this->userSession->expects(self::once())
756
+                ->method('getUser');
757
+
758
+            if ($hasSession) {
759
+                $matcher->willReturn($this->createMock(IUser::class));
760
+            } else {
761
+                $this->expectException(\RuntimeException::class);
762
+            }
763
+        } else {
764
+            $user = $this->createMock(IUser::class);
765
+        }
766
+
767
+        $iterator = $factory->getLanguageIterator($user);
768
+        self::assertInstanceOf(ILanguageIterator::class, $iterator);
769
+    }
770
+
771
+    public static function dataGetLanguageDirection(): array {
772
+        return [
773
+            ['en', 'ltr'],
774
+            ['de', 'ltr'],
775
+            ['fa', 'rtl'],
776
+            ['ar', 'rtl']
777
+        ];
778
+    }
779
+
780
+    /**
781
+     * @dataProvider dataGetLanguageDirection
782
+     */
783
+    public function testGetLanguageDirection(string $language, string $expectedDirection) {
784
+        $factory = $this->getFactory();
785
+
786
+        self::assertEquals($expectedDirection, $factory->getLanguageDirection($language));
787
+    }
788 788
 }
Please login to merge, or discard this patch.
Spacing   +36 added lines, -36 removed lines patch added patch discarded remove patch
@@ -287,7 +287,7 @@  discard block
 block discarded – undo
287 287
 		$factory->expects(self::once())
288 288
 			->method('findL10nDir')
289 289
 			->with($app)
290
-			->willReturn(\OC::$SERVERROOT . '/tests/data/l10n/');
290
+			->willReturn(\OC::$SERVERROOT.'/tests/data/l10n/');
291 291
 
292 292
 		self::assertEqualsCanonicalizing(['cs', 'de', 'en', 'ru'], $factory->findAvailableLanguages($app));
293 293
 	}
@@ -313,7 +313,7 @@  discard block
 block discarded – undo
313 313
 		$factory->expects(self::once())
314 314
 			->method('findL10nDir')
315 315
 			->with($app)
316
-			->willReturn($this->serverRoot . '/apps/files/l10n/');
316
+			->willReturn($this->serverRoot.'/apps/files/l10n/');
317 317
 		$this->config
318 318
 			->expects(self::once())
319 319
 			->method('getSystemValueString')
@@ -379,7 +379,7 @@  discard block
 block discarded – undo
379 379
 			->willReturn($availableLanguages);
380 380
 
381 381
 		$factory->expects(self::any())
382
-			->method('respectDefaultLanguage')->willReturnCallback(function ($app, $lang) {
382
+			->method('respectDefaultLanguage')->willReturnCallback(function($app, $lang) {
383 383
 				return $lang;
384 384
 			});
385 385
 
@@ -398,13 +398,13 @@  discard block
 block discarded – undo
398 398
 
399 399
 	public static function dataGetL10nFilesForApp(): array {
400 400
 		return [
401
-			['', 'de', [\OC::$SERVERROOT . '/core/l10n/de.json']],
402
-			['core', 'ru', [\OC::$SERVERROOT . '/core/l10n/ru.json']],
403
-			['lib', 'ru', [\OC::$SERVERROOT . '/lib/l10n/ru.json']],
404
-			['settings', 'de', [\OC::$SERVERROOT . '/apps/settings/l10n/de.json']],
405
-			['files', 'de', [\OC::$SERVERROOT . '/apps/files/l10n/de.json']],
401
+			['', 'de', [\OC::$SERVERROOT.'/core/l10n/de.json']],
402
+			['core', 'ru', [\OC::$SERVERROOT.'/core/l10n/ru.json']],
403
+			['lib', 'ru', [\OC::$SERVERROOT.'/lib/l10n/ru.json']],
404
+			['settings', 'de', [\OC::$SERVERROOT.'/apps/settings/l10n/de.json']],
405
+			['files', 'de', [\OC::$SERVERROOT.'/apps/files/l10n/de.json']],
406 406
 			['files', '_lang_never_exists_', []],
407
-			['_app_never_exists_', 'de', [\OC::$SERVERROOT . '/core/l10n/de.json']],
407
+			['_app_never_exists_', 'de', [\OC::$SERVERROOT.'/core/l10n/de.json']],
408 408
 		];
409 409
 	}
410 410
 
@@ -416,11 +416,11 @@  discard block
 block discarded – undo
416 416
 	 */
417 417
 	public function testGetL10nFilesForApp($app, $lang, $expected): void {
418 418
 		$factory = $this->getFactory();
419
-		if (in_array($app, ['settings','files'])) {
419
+		if (in_array($app, ['settings', 'files'])) {
420 420
 			$this->appManager
421 421
 				->method('getAppPath')
422 422
 				->with($app)
423
-				->willReturn(\OC::$SERVERROOT . '/apps/' . $app);
423
+				->willReturn(\OC::$SERVERROOT.'/apps/'.$app);
424 424
 		} else {
425 425
 			$this->appManager
426 426
 				->method('getAppPath')
@@ -432,12 +432,12 @@  discard block
 block discarded – undo
432 432
 
433 433
 	public static function dataFindL10NDir(): array {
434 434
 		return [
435
-			['', \OC::$SERVERROOT . '/core/l10n/'],
436
-			['core', \OC::$SERVERROOT . '/core/l10n/'],
437
-			['lib', \OC::$SERVERROOT . '/lib/l10n/'],
438
-			['settings', \OC::$SERVERROOT . '/apps/settings/l10n/'],
439
-			['files', \OC::$SERVERROOT . '/apps/files/l10n/'],
440
-			['_app_never_exists_', \OC::$SERVERROOT . '/core/l10n/'],
435
+			['', \OC::$SERVERROOT.'/core/l10n/'],
436
+			['core', \OC::$SERVERROOT.'/core/l10n/'],
437
+			['lib', \OC::$SERVERROOT.'/lib/l10n/'],
438
+			['settings', \OC::$SERVERROOT.'/apps/settings/l10n/'],
439
+			['files', \OC::$SERVERROOT.'/apps/files/l10n/'],
440
+			['_app_never_exists_', \OC::$SERVERROOT.'/core/l10n/'],
441 441
 		];
442 442
 	}
443 443
 
@@ -449,11 +449,11 @@  discard block
 block discarded – undo
449 449
 	 */
450 450
 	public function testFindL10NDir($app, $expected): void {
451 451
 		$factory = $this->getFactory();
452
-		if (in_array($app, ['settings','files'])) {
452
+		if (in_array($app, ['settings', 'files'])) {
453 453
 			$this->appManager
454 454
 				->method('getAppPath')
455 455
 				->with($app)
456
-				->willReturn(\OC::$SERVERROOT . '/apps/' . $app);
456
+				->willReturn(\OC::$SERVERROOT.'/apps/'.$app);
457 457
 		} else {
458 458
 			$this->appManager
459 459
 				->method('getAppPath')
@@ -492,7 +492,7 @@  discard block
 block discarded – undo
492 492
 
493 493
 		$this->config->expects(self::any())
494 494
 			->method('getSystemValue')
495
-			->willReturnCallback(function ($var, $default) use ($defaultLang) {
495
+			->willReturnCallback(function($var, $default) use ($defaultLang) {
496 496
 				if ($var === 'default_language') {
497 497
 					return $defaultLang;
498 498
 				} else {
@@ -528,16 +528,16 @@  discard block
 block discarded – undo
528 528
 		$factory = $this->getFactory(['languageExists', 'findAvailableLanguages', 'respectDefaultLanguage']);
529 529
 		$factory->expects(self::any())
530 530
 			->method('languageExists')
531
-			->willReturnCallback(function ($app, $lang) use ($availableLang) {
531
+			->willReturnCallback(function($app, $lang) use ($availableLang) {
532 532
 				return in_array($lang, $availableLang);
533 533
 			});
534 534
 		$factory->expects(self::any())
535 535
 			->method('findAvailableLanguages')
536
-			->willReturnCallback(function ($app) use ($availableLang) {
536
+			->willReturnCallback(function($app) use ($availableLang) {
537 537
 				return $availableLang;
538 538
 			});
539 539
 		$factory->expects(self::any())
540
-			->method('respectDefaultLanguage')->willReturnCallback(function ($app, $lang) {
540
+			->method('respectDefaultLanguage')->willReturnCallback(function($app, $lang) {
541 541
 				return $lang;
542 542
 			});
543 543
 
@@ -563,8 +563,8 @@  discard block
 block discarded – undo
563 563
 		$this->config->expects(self::exactly(2))
564 564
 			->method('getSystemValue')
565 565
 			->willReturnMap([
566
-				['force_language', false, false,],
567
-				['default_language', false, 'cz',],
566
+				['force_language', false, false, ],
567
+				['default_language', false, 'cz', ],
568 568
 			]);
569 569
 		$factory->expects(self::once())
570 570
 			->method('languageExists')
@@ -581,8 +581,8 @@  discard block
 block discarded – undo
581 581
 		$this->config->expects(self::exactly(2))
582 582
 			->method('getSystemValue')
583 583
 			->willReturnMap([
584
-				['force_language', false, false,],
585
-				['default_language', false, false,],
584
+				['force_language', false, false, ],
585
+				['default_language', false, false, ],
586 586
 			]);
587 587
 		$user = $this->createMock(IUser::class);
588 588
 		$this->userSession->expects(self::once())
@@ -603,8 +603,8 @@  discard block
 block discarded – undo
603 603
 		$factory = $this->getFactory(['findAvailableLanguages', 'languageExists']);
604 604
 		$this->config->method('getSystemValue')
605 605
 			->willReturnMap([
606
-				['force_language', false, false,],
607
-				['default_language', false, false,],
606
+				['force_language', false, false, ],
607
+				['default_language', false, false, ],
608 608
 			]);
609 609
 		$user = $this->createMock(IUser::class);
610 610
 		$this->userSession->expects(self::once())
@@ -633,8 +633,8 @@  discard block
 block discarded – undo
633 633
 		$factory = $this->getFactory(['findAvailableLanguages', 'languageExists']);
634 634
 		$this->config->method('getSystemValue')
635 635
 			->willReturnMap([
636
-				['force_language', false, false,],
637
-				['default_language', false, false,],
636
+				['force_language', false, false, ],
637
+				['default_language', false, false, ],
638 638
 			]);
639 639
 		$user = $this->createMock(IUser::class);
640 640
 		$this->userSession->expects(self::once())
@@ -716,7 +716,7 @@  discard block
 block discarded – undo
716 716
 			->method('languageExists')->willReturn(true);
717 717
 		$factory->expects(self::any())
718 718
 			->method('findAvailableLanguages')
719
-			->willReturnCallback(function ($app) use ($availableLanguages) {
719
+			->willReturnCallback(function($app) use ($availableLanguages) {
720 720
 				return $availableLanguages;
721 721
 			});
722 722
 
@@ -729,7 +729,7 @@  discard block
 block discarded – undo
729 729
 			]);
730 730
 
731 731
 		$result = $this->invokePrivate($factory, 'getLanguages');
732
-		$commonLanguagesCodes = array_map(function ($lang) {
732
+		$commonLanguagesCodes = array_map(function($lang) {
733 733
 			return $lang['code'];
734 734
 		}, $result['commonLanguages']);
735 735
 
@@ -738,9 +738,9 @@  discard block
 block discarded – undo
738 738
 
739 739
 	public static function languageIteratorRequestProvider(): array {
740 740
 		return [
741
-			[ true, true],
742
-			[ false, true],
743
-			[ false, false],
741
+			[true, true],
742
+			[false, true],
743
+			[false, false],
744 744
 		];
745 745
 	}
746 746
 
Please login to merge, or discard this patch.
tests/lib/Security/IdentityProof/ManagerTest.php 1 patch
Indentation   +189 added lines, -189 removed lines patch added patch discarded remove patch
@@ -24,193 +24,193 @@
 block discarded – undo
24 24
 use Test\TestCase;
25 25
 
26 26
 class ManagerTest extends TestCase {
27
-	/** @var Factory|MockObject */
28
-	private $factory;
29
-	/** @var IAppData|MockObject */
30
-	private $appData;
31
-	/** @var ICrypto|MockObject */
32
-	private $crypto;
33
-	/** @var Manager|MockObject */
34
-	private $manager;
35
-	/** @var IConfig|MockObject */
36
-	private $config;
37
-	/** @var LoggerInterface|MockObject */
38
-	private $logger;
39
-
40
-	protected function setUp(): void {
41
-		parent::setUp();
42
-
43
-		/** @var Factory|\PHPUnit\Framework\MockObject\MockObject $factory */
44
-		$this->factory = $this->createMock(Factory::class);
45
-		$this->appData = $this->createMock(AppData::class);
46
-		$this->config = $this->createMock(IConfig::class);
47
-		$this->factory->expects($this->any())
48
-			->method('get')
49
-			->with('identityproof')
50
-			->willReturn($this->appData);
51
-		$this->logger = $this->createMock(LoggerInterface::class);
52
-
53
-		$this->crypto = $this->createMock(ICrypto::class);
54
-		$this->manager = $this->getManager(['generateKeyPair']);
55
-	}
56
-
57
-	/**
58
-	 * create manager object
59
-	 *
60
-	 * @param array $setMethods
61
-	 * @return Manager|\PHPUnit\Framework\MockObject\MockObject
62
-	 */
63
-	protected function getManager($setMethods = []) {
64
-		if (empty($setMethods)) {
65
-			return new Manager(
66
-				$this->factory,
67
-				$this->crypto,
68
-				$this->config,
69
-				$this->logger
70
-			);
71
-		} else {
72
-			return $this->getMockBuilder(Manager::class)
73
-				->setConstructorArgs([
74
-					$this->factory,
75
-					$this->crypto,
76
-					$this->config,
77
-					$this->logger
78
-				])
79
-				->onlyMethods($setMethods)
80
-				->getMock();
81
-		}
82
-	}
83
-
84
-	public function testGetKeyWithExistingKey(): void {
85
-		$user = $this->createMock(IUser::class);
86
-		$user
87
-			->expects($this->once())
88
-			->method('getUID')
89
-			->willReturn('MyUid');
90
-		$folder = $this->createMock(ISimpleFolder::class);
91
-		$privateFile = $this->createMock(ISimpleFile::class);
92
-		$privateFile
93
-			->expects($this->once())
94
-			->method('getContent')
95
-			->willReturn('EncryptedPrivateKey');
96
-		$publicFile = $this->createMock(ISimpleFile::class);
97
-		$publicFile
98
-			->expects($this->once())
99
-			->method('getContent')
100
-			->willReturn('MyPublicKey');
101
-		$this->crypto
102
-			->expects($this->once())
103
-			->method('decrypt')
104
-			->with('EncryptedPrivateKey')
105
-			->willReturn('MyPrivateKey');
106
-		$folder
107
-			->expects($this->exactly(2))
108
-			->method('getFile')
109
-			->willReturnMap([
110
-				['private', $privateFile],
111
-				['public', $publicFile],
112
-			]);
113
-		$this->appData
114
-			->expects($this->once())
115
-			->method('getFolder')
116
-			->with('user-MyUid')
117
-			->willReturn($folder);
118
-
119
-		$expected = new Key('MyPublicKey', 'MyPrivateKey');
120
-		$this->assertEquals($expected, $this->manager->getKey($user));
121
-	}
122
-
123
-	public function testGetKeyWithNotExistingKey(): void {
124
-		$user = $this->createMock(IUser::class);
125
-		$user
126
-			->expects($this->once())
127
-			->method('getUID')
128
-			->willReturn('MyUid');
129
-		$this->manager
130
-			->expects($this->once())
131
-			->method('generateKeyPair')
132
-			->willReturn(['MyNewPublicKey', 'MyNewPrivateKey']);
133
-		$this->appData
134
-			->expects($this->once())
135
-			->method('newFolder')
136
-			->with('user-MyUid');
137
-		$folder = $this->createMock(ISimpleFolder::class);
138
-		$this->crypto
139
-			->expects($this->once())
140
-			->method('encrypt')
141
-			->with('MyNewPrivateKey')
142
-			->willReturn('MyNewEncryptedPrivateKey');
143
-		$privateFile = $this->createMock(ISimpleFile::class);
144
-		$privateFile
145
-			->expects($this->once())
146
-			->method('putContent')
147
-			->with('MyNewEncryptedPrivateKey');
148
-		$publicFile = $this->createMock(ISimpleFile::class);
149
-		$publicFile
150
-			->expects($this->once())
151
-			->method('putContent')
152
-			->with('MyNewPublicKey');
153
-		$folder
154
-			->expects($this->exactly(2))
155
-			->method('newFile')
156
-			->willReturnMap([
157
-				['private', null, $privateFile],
158
-				['public', null, $publicFile],
159
-			]);
160
-		$this->appData
161
-			->expects($this->exactly(2))
162
-			->method('getFolder')
163
-			->with('user-MyUid')
164
-			->willReturnOnConsecutiveCalls(
165
-				$this->throwException(new \Exception()),
166
-				$folder
167
-			);
168
-
169
-
170
-		$expected = new Key('MyNewPublicKey', 'MyNewPrivateKey');
171
-		$this->assertEquals($expected, $this->manager->getKey($user));
172
-	}
173
-
174
-	public function testGenerateKeyPair(): void {
175
-		$manager = $this->getManager();
176
-		$data = 'MyTestData';
177
-
178
-		[$resultPublicKey, $resultPrivateKey] = self::invokePrivate($manager, 'generateKeyPair');
179
-		openssl_sign($data, $signature, $resultPrivateKey);
180
-		$details = openssl_pkey_get_details(openssl_pkey_get_public($resultPublicKey));
181
-
182
-		$this->assertSame(1, openssl_verify($data, $signature, $resultPublicKey));
183
-		$this->assertSame(2048, $details['bits']);
184
-	}
185
-
186
-	public function testGetSystemKey(): void {
187
-		$manager = $this->getManager(['retrieveKey']);
188
-
189
-		/** @var Key|\PHPUnit\Framework\MockObject\MockObject $key */
190
-		$key = $this->createMock(Key::class);
191
-
192
-		$this->config->expects($this->once())->method('getSystemValue')
193
-			->with('instanceid', null)->willReturn('instanceId');
194
-
195
-		$manager->expects($this->once())->method('retrieveKey')->with('system-instanceId')
196
-			->willReturn($key);
197
-
198
-		$this->assertSame($key, $manager->getSystemKey());
199
-	}
200
-
201
-
202
-
203
-	public function testGetSystemKeyFailure(): void {
204
-		$this->expectException(\RuntimeException::class);
205
-
206
-		$manager = $this->getManager(['retrieveKey']);
207
-
208
-		/** @var Key|\PHPUnit\Framework\MockObject\MockObject $key */
209
-		$key = $this->createMock(Key::class);
210
-
211
-		$this->config->expects($this->once())->method('getSystemValue')
212
-			->with('instanceid', null)->willReturn(null);
213
-
214
-		$manager->getSystemKey();
215
-	}
27
+    /** @var Factory|MockObject */
28
+    private $factory;
29
+    /** @var IAppData|MockObject */
30
+    private $appData;
31
+    /** @var ICrypto|MockObject */
32
+    private $crypto;
33
+    /** @var Manager|MockObject */
34
+    private $manager;
35
+    /** @var IConfig|MockObject */
36
+    private $config;
37
+    /** @var LoggerInterface|MockObject */
38
+    private $logger;
39
+
40
+    protected function setUp(): void {
41
+        parent::setUp();
42
+
43
+        /** @var Factory|\PHPUnit\Framework\MockObject\MockObject $factory */
44
+        $this->factory = $this->createMock(Factory::class);
45
+        $this->appData = $this->createMock(AppData::class);
46
+        $this->config = $this->createMock(IConfig::class);
47
+        $this->factory->expects($this->any())
48
+            ->method('get')
49
+            ->with('identityproof')
50
+            ->willReturn($this->appData);
51
+        $this->logger = $this->createMock(LoggerInterface::class);
52
+
53
+        $this->crypto = $this->createMock(ICrypto::class);
54
+        $this->manager = $this->getManager(['generateKeyPair']);
55
+    }
56
+
57
+    /**
58
+     * create manager object
59
+     *
60
+     * @param array $setMethods
61
+     * @return Manager|\PHPUnit\Framework\MockObject\MockObject
62
+     */
63
+    protected function getManager($setMethods = []) {
64
+        if (empty($setMethods)) {
65
+            return new Manager(
66
+                $this->factory,
67
+                $this->crypto,
68
+                $this->config,
69
+                $this->logger
70
+            );
71
+        } else {
72
+            return $this->getMockBuilder(Manager::class)
73
+                ->setConstructorArgs([
74
+                    $this->factory,
75
+                    $this->crypto,
76
+                    $this->config,
77
+                    $this->logger
78
+                ])
79
+                ->onlyMethods($setMethods)
80
+                ->getMock();
81
+        }
82
+    }
83
+
84
+    public function testGetKeyWithExistingKey(): void {
85
+        $user = $this->createMock(IUser::class);
86
+        $user
87
+            ->expects($this->once())
88
+            ->method('getUID')
89
+            ->willReturn('MyUid');
90
+        $folder = $this->createMock(ISimpleFolder::class);
91
+        $privateFile = $this->createMock(ISimpleFile::class);
92
+        $privateFile
93
+            ->expects($this->once())
94
+            ->method('getContent')
95
+            ->willReturn('EncryptedPrivateKey');
96
+        $publicFile = $this->createMock(ISimpleFile::class);
97
+        $publicFile
98
+            ->expects($this->once())
99
+            ->method('getContent')
100
+            ->willReturn('MyPublicKey');
101
+        $this->crypto
102
+            ->expects($this->once())
103
+            ->method('decrypt')
104
+            ->with('EncryptedPrivateKey')
105
+            ->willReturn('MyPrivateKey');
106
+        $folder
107
+            ->expects($this->exactly(2))
108
+            ->method('getFile')
109
+            ->willReturnMap([
110
+                ['private', $privateFile],
111
+                ['public', $publicFile],
112
+            ]);
113
+        $this->appData
114
+            ->expects($this->once())
115
+            ->method('getFolder')
116
+            ->with('user-MyUid')
117
+            ->willReturn($folder);
118
+
119
+        $expected = new Key('MyPublicKey', 'MyPrivateKey');
120
+        $this->assertEquals($expected, $this->manager->getKey($user));
121
+    }
122
+
123
+    public function testGetKeyWithNotExistingKey(): void {
124
+        $user = $this->createMock(IUser::class);
125
+        $user
126
+            ->expects($this->once())
127
+            ->method('getUID')
128
+            ->willReturn('MyUid');
129
+        $this->manager
130
+            ->expects($this->once())
131
+            ->method('generateKeyPair')
132
+            ->willReturn(['MyNewPublicKey', 'MyNewPrivateKey']);
133
+        $this->appData
134
+            ->expects($this->once())
135
+            ->method('newFolder')
136
+            ->with('user-MyUid');
137
+        $folder = $this->createMock(ISimpleFolder::class);
138
+        $this->crypto
139
+            ->expects($this->once())
140
+            ->method('encrypt')
141
+            ->with('MyNewPrivateKey')
142
+            ->willReturn('MyNewEncryptedPrivateKey');
143
+        $privateFile = $this->createMock(ISimpleFile::class);
144
+        $privateFile
145
+            ->expects($this->once())
146
+            ->method('putContent')
147
+            ->with('MyNewEncryptedPrivateKey');
148
+        $publicFile = $this->createMock(ISimpleFile::class);
149
+        $publicFile
150
+            ->expects($this->once())
151
+            ->method('putContent')
152
+            ->with('MyNewPublicKey');
153
+        $folder
154
+            ->expects($this->exactly(2))
155
+            ->method('newFile')
156
+            ->willReturnMap([
157
+                ['private', null, $privateFile],
158
+                ['public', null, $publicFile],
159
+            ]);
160
+        $this->appData
161
+            ->expects($this->exactly(2))
162
+            ->method('getFolder')
163
+            ->with('user-MyUid')
164
+            ->willReturnOnConsecutiveCalls(
165
+                $this->throwException(new \Exception()),
166
+                $folder
167
+            );
168
+
169
+
170
+        $expected = new Key('MyNewPublicKey', 'MyNewPrivateKey');
171
+        $this->assertEquals($expected, $this->manager->getKey($user));
172
+    }
173
+
174
+    public function testGenerateKeyPair(): void {
175
+        $manager = $this->getManager();
176
+        $data = 'MyTestData';
177
+
178
+        [$resultPublicKey, $resultPrivateKey] = self::invokePrivate($manager, 'generateKeyPair');
179
+        openssl_sign($data, $signature, $resultPrivateKey);
180
+        $details = openssl_pkey_get_details(openssl_pkey_get_public($resultPublicKey));
181
+
182
+        $this->assertSame(1, openssl_verify($data, $signature, $resultPublicKey));
183
+        $this->assertSame(2048, $details['bits']);
184
+    }
185
+
186
+    public function testGetSystemKey(): void {
187
+        $manager = $this->getManager(['retrieveKey']);
188
+
189
+        /** @var Key|\PHPUnit\Framework\MockObject\MockObject $key */
190
+        $key = $this->createMock(Key::class);
191
+
192
+        $this->config->expects($this->once())->method('getSystemValue')
193
+            ->with('instanceid', null)->willReturn('instanceId');
194
+
195
+        $manager->expects($this->once())->method('retrieveKey')->with('system-instanceId')
196
+            ->willReturn($key);
197
+
198
+        $this->assertSame($key, $manager->getSystemKey());
199
+    }
200
+
201
+
202
+
203
+    public function testGetSystemKeyFailure(): void {
204
+        $this->expectException(\RuntimeException::class);
205
+
206
+        $manager = $this->getManager(['retrieveKey']);
207
+
208
+        /** @var Key|\PHPUnit\Framework\MockObject\MockObject $key */
209
+        $key = $this->createMock(Key::class);
210
+
211
+        $this->config->expects($this->once())->method('getSystemValue')
212
+            ->with('instanceid', null)->willReturn(null);
213
+
214
+        $manager->getSystemKey();
215
+    }
216 216
 }
Please login to merge, or discard this patch.
tests/lib/Settings/ManagerTest.php 1 patch
Indentation   +197 added lines, -197 removed lines patch added patch discarded remove patch
@@ -22,201 +22,201 @@
 block discarded – undo
22 22
 use Test\TestCase;
23 23
 
24 24
 class ManagerTest extends TestCase {
25
-	/** @var Manager|MockObject */
26
-	private $manager;
27
-	/** @var LoggerInterface|MockObject */
28
-	private $logger;
29
-	/** @var IDBConnection|MockObject */
30
-	private $l10n;
31
-	/** @var IFactory|MockObject */
32
-	private $l10nFactory;
33
-	/** @var IURLGenerator|MockObject */
34
-	private $url;
35
-	/** @var IServerContainer|MockObject */
36
-	private $container;
37
-	/** @var AuthorizedGroupMapper|MockObject */
38
-	private $mapper;
39
-	/** @var IGroupManager|MockObject */
40
-	private $groupManager;
41
-	/** @var ISubAdmin|MockObject */
42
-	private $subAdmin;
43
-
44
-	protected function setUp(): void {
45
-		parent::setUp();
46
-
47
-		$this->logger = $this->createMock(LoggerInterface::class);
48
-		$this->l10n = $this->createMock(IL10N::class);
49
-		$this->l10nFactory = $this->createMock(IFactory::class);
50
-		$this->url = $this->createMock(IURLGenerator::class);
51
-		$this->container = $this->createMock(IServerContainer::class);
52
-		$this->mapper = $this->createMock(AuthorizedGroupMapper::class);
53
-		$this->groupManager = $this->createMock(IGroupManager::class);
54
-		$this->subAdmin = $this->createMock(ISubAdmin::class);
55
-
56
-		$this->manager = new Manager(
57
-			$this->logger,
58
-			$this->l10nFactory,
59
-			$this->url,
60
-			$this->container,
61
-			$this->mapper,
62
-			$this->groupManager,
63
-			$this->subAdmin,
64
-		);
65
-	}
66
-
67
-	public function testGetAdminSections(): void {
68
-		$this->manager->registerSection('admin', \OCA\WorkflowEngine\Settings\Section::class);
69
-
70
-		$section = \OC::$server->query(\OCA\WorkflowEngine\Settings\Section::class);
71
-		$this->container->method('get')
72
-			->with(\OCA\WorkflowEngine\Settings\Section::class)
73
-			->willReturn($section);
74
-
75
-		$this->assertEquals([
76
-			55 => [$section],
77
-		], $this->manager->getAdminSections());
78
-	}
79
-
80
-	public function testGetPersonalSections(): void {
81
-		$this->manager->registerSection('personal', \OCA\WorkflowEngine\Settings\Section::class);
82
-
83
-		$section = \OC::$server->query(\OCA\WorkflowEngine\Settings\Section::class);
84
-		$this->container->method('get')
85
-			->with(\OCA\WorkflowEngine\Settings\Section::class)
86
-			->willReturn($section);
87
-
88
-		$this->assertEquals([
89
-			55 => [$section],
90
-		], $this->manager->getPersonalSections());
91
-	}
92
-
93
-	public function testGetAdminSectionsEmptySection(): void {
94
-		$this->assertEquals([], $this->manager->getAdminSections());
95
-	}
96
-
97
-	public function testGetPersonalSectionsEmptySection(): void {
98
-		$this->l10nFactory
99
-			->expects($this->once())
100
-			->method('get')
101
-			->with('lib')
102
-			->willReturn($this->l10n);
103
-		$this->l10n
104
-			->expects($this->any())
105
-			->method('t')
106
-			->willReturnArgument(0);
107
-
108
-		$this->assertEquals([], $this->manager->getPersonalSections());
109
-	}
110
-
111
-	public function testGetAdminSettings(): void {
112
-		$section = $this->createMock(ISettings::class);
113
-		$section->method('getPriority')
114
-			->willReturn(13);
115
-		$section->method('getSection')
116
-			->willReturn('sharing');
117
-		$this->container->method('get')
118
-			->with('myAdminClass')
119
-			->willReturn($section);
120
-
121
-		$this->manager->registerSetting('admin', 'myAdminClass');
122
-		$settings = $this->manager->getAdminSettings('sharing');
123
-
124
-		$this->assertEquals([
125
-			13 => [$section]
126
-		], $settings);
127
-	}
128
-
129
-	public function testGetAdminSettingsAsSubAdmin(): void {
130
-		$section = $this->createMock(ISettings::class);
131
-		$section->method('getPriority')
132
-			->willReturn(13);
133
-		$section->method('getSection')
134
-			->willReturn('sharing');
135
-		$this->container->method('get')
136
-			->with('myAdminClass')
137
-			->willReturn($section);
138
-
139
-		$this->manager->registerSetting('admin', 'myAdminClass');
140
-		$settings = $this->manager->getAdminSettings('sharing', true);
141
-
142
-		$this->assertEquals([], $settings);
143
-	}
144
-
145
-	public function testGetSubAdminSettingsAsSubAdmin(): void {
146
-		$section = $this->createMock(ISubAdminSettings::class);
147
-		$section->method('getPriority')
148
-			->willReturn(13);
149
-		$section->method('getSection')
150
-			->willReturn('sharing');
151
-		$this->container->expects($this->once())
152
-			->method('get')
153
-			->with('mySubAdminClass')
154
-			->willReturn($section);
155
-
156
-		$this->manager->registerSetting('admin', 'mySubAdminClass');
157
-		$settings = $this->manager->getAdminSettings('sharing', true);
158
-
159
-		$this->assertEquals([
160
-			13 => [$section]
161
-		], $settings);
162
-	}
163
-
164
-	public function testGetPersonalSettings(): void {
165
-		$section = $this->createMock(ISettings::class);
166
-		$section->method('getPriority')
167
-			->willReturn(16);
168
-		$section->method('getSection')
169
-			->willReturn('security');
170
-		$section2 = $this->createMock(ISettings::class);
171
-		$section2->method('getPriority')
172
-			->willReturn(100);
173
-		$section2->method('getSection')
174
-			->willReturn('security');
175
-
176
-		$this->manager->registerSetting('personal', 'section1');
177
-		$this->manager->registerSetting('personal', 'section2');
178
-
179
-		$this->container->expects($this->exactly(2))
180
-			->method('get')
181
-			->willReturnMap([
182
-				['section1', $section],
183
-				['section2', $section2],
184
-			]);
185
-
186
-		$settings = $this->manager->getPersonalSettings('security');
187
-
188
-		$this->assertEquals([
189
-			16 => [$section],
190
-			100 => [$section2],
191
-		], $settings);
192
-	}
193
-
194
-	public function testSameSectionAsPersonalAndAdmin(): void {
195
-		$this->l10nFactory
196
-			->expects($this->once())
197
-			->method('get')
198
-			->with('lib')
199
-			->willReturn($this->l10n);
200
-		$this->l10n
201
-			->expects($this->any())
202
-			->method('t')
203
-			->willReturnArgument(0);
204
-
205
-		$this->manager->registerSection('personal', \OCA\WorkflowEngine\Settings\Section::class);
206
-		$this->manager->registerSection('admin', \OCA\WorkflowEngine\Settings\Section::class);
207
-
208
-
209
-		$section = \OC::$server->query(\OCA\WorkflowEngine\Settings\Section::class);
210
-		$this->container->method('get')
211
-			->with(\OCA\WorkflowEngine\Settings\Section::class)
212
-			->willReturn($section);
213
-
214
-		$this->assertEquals([
215
-			55 => [$section],
216
-		], $this->manager->getPersonalSections());
217
-
218
-		$this->assertEquals([
219
-			55 => [$section],
220
-		], $this->manager->getAdminSections());
221
-	}
25
+    /** @var Manager|MockObject */
26
+    private $manager;
27
+    /** @var LoggerInterface|MockObject */
28
+    private $logger;
29
+    /** @var IDBConnection|MockObject */
30
+    private $l10n;
31
+    /** @var IFactory|MockObject */
32
+    private $l10nFactory;
33
+    /** @var IURLGenerator|MockObject */
34
+    private $url;
35
+    /** @var IServerContainer|MockObject */
36
+    private $container;
37
+    /** @var AuthorizedGroupMapper|MockObject */
38
+    private $mapper;
39
+    /** @var IGroupManager|MockObject */
40
+    private $groupManager;
41
+    /** @var ISubAdmin|MockObject */
42
+    private $subAdmin;
43
+
44
+    protected function setUp(): void {
45
+        parent::setUp();
46
+
47
+        $this->logger = $this->createMock(LoggerInterface::class);
48
+        $this->l10n = $this->createMock(IL10N::class);
49
+        $this->l10nFactory = $this->createMock(IFactory::class);
50
+        $this->url = $this->createMock(IURLGenerator::class);
51
+        $this->container = $this->createMock(IServerContainer::class);
52
+        $this->mapper = $this->createMock(AuthorizedGroupMapper::class);
53
+        $this->groupManager = $this->createMock(IGroupManager::class);
54
+        $this->subAdmin = $this->createMock(ISubAdmin::class);
55
+
56
+        $this->manager = new Manager(
57
+            $this->logger,
58
+            $this->l10nFactory,
59
+            $this->url,
60
+            $this->container,
61
+            $this->mapper,
62
+            $this->groupManager,
63
+            $this->subAdmin,
64
+        );
65
+    }
66
+
67
+    public function testGetAdminSections(): void {
68
+        $this->manager->registerSection('admin', \OCA\WorkflowEngine\Settings\Section::class);
69
+
70
+        $section = \OC::$server->query(\OCA\WorkflowEngine\Settings\Section::class);
71
+        $this->container->method('get')
72
+            ->with(\OCA\WorkflowEngine\Settings\Section::class)
73
+            ->willReturn($section);
74
+
75
+        $this->assertEquals([
76
+            55 => [$section],
77
+        ], $this->manager->getAdminSections());
78
+    }
79
+
80
+    public function testGetPersonalSections(): void {
81
+        $this->manager->registerSection('personal', \OCA\WorkflowEngine\Settings\Section::class);
82
+
83
+        $section = \OC::$server->query(\OCA\WorkflowEngine\Settings\Section::class);
84
+        $this->container->method('get')
85
+            ->with(\OCA\WorkflowEngine\Settings\Section::class)
86
+            ->willReturn($section);
87
+
88
+        $this->assertEquals([
89
+            55 => [$section],
90
+        ], $this->manager->getPersonalSections());
91
+    }
92
+
93
+    public function testGetAdminSectionsEmptySection(): void {
94
+        $this->assertEquals([], $this->manager->getAdminSections());
95
+    }
96
+
97
+    public function testGetPersonalSectionsEmptySection(): void {
98
+        $this->l10nFactory
99
+            ->expects($this->once())
100
+            ->method('get')
101
+            ->with('lib')
102
+            ->willReturn($this->l10n);
103
+        $this->l10n
104
+            ->expects($this->any())
105
+            ->method('t')
106
+            ->willReturnArgument(0);
107
+
108
+        $this->assertEquals([], $this->manager->getPersonalSections());
109
+    }
110
+
111
+    public function testGetAdminSettings(): void {
112
+        $section = $this->createMock(ISettings::class);
113
+        $section->method('getPriority')
114
+            ->willReturn(13);
115
+        $section->method('getSection')
116
+            ->willReturn('sharing');
117
+        $this->container->method('get')
118
+            ->with('myAdminClass')
119
+            ->willReturn($section);
120
+
121
+        $this->manager->registerSetting('admin', 'myAdminClass');
122
+        $settings = $this->manager->getAdminSettings('sharing');
123
+
124
+        $this->assertEquals([
125
+            13 => [$section]
126
+        ], $settings);
127
+    }
128
+
129
+    public function testGetAdminSettingsAsSubAdmin(): void {
130
+        $section = $this->createMock(ISettings::class);
131
+        $section->method('getPriority')
132
+            ->willReturn(13);
133
+        $section->method('getSection')
134
+            ->willReturn('sharing');
135
+        $this->container->method('get')
136
+            ->with('myAdminClass')
137
+            ->willReturn($section);
138
+
139
+        $this->manager->registerSetting('admin', 'myAdminClass');
140
+        $settings = $this->manager->getAdminSettings('sharing', true);
141
+
142
+        $this->assertEquals([], $settings);
143
+    }
144
+
145
+    public function testGetSubAdminSettingsAsSubAdmin(): void {
146
+        $section = $this->createMock(ISubAdminSettings::class);
147
+        $section->method('getPriority')
148
+            ->willReturn(13);
149
+        $section->method('getSection')
150
+            ->willReturn('sharing');
151
+        $this->container->expects($this->once())
152
+            ->method('get')
153
+            ->with('mySubAdminClass')
154
+            ->willReturn($section);
155
+
156
+        $this->manager->registerSetting('admin', 'mySubAdminClass');
157
+        $settings = $this->manager->getAdminSettings('sharing', true);
158
+
159
+        $this->assertEquals([
160
+            13 => [$section]
161
+        ], $settings);
162
+    }
163
+
164
+    public function testGetPersonalSettings(): void {
165
+        $section = $this->createMock(ISettings::class);
166
+        $section->method('getPriority')
167
+            ->willReturn(16);
168
+        $section->method('getSection')
169
+            ->willReturn('security');
170
+        $section2 = $this->createMock(ISettings::class);
171
+        $section2->method('getPriority')
172
+            ->willReturn(100);
173
+        $section2->method('getSection')
174
+            ->willReturn('security');
175
+
176
+        $this->manager->registerSetting('personal', 'section1');
177
+        $this->manager->registerSetting('personal', 'section2');
178
+
179
+        $this->container->expects($this->exactly(2))
180
+            ->method('get')
181
+            ->willReturnMap([
182
+                ['section1', $section],
183
+                ['section2', $section2],
184
+            ]);
185
+
186
+        $settings = $this->manager->getPersonalSettings('security');
187
+
188
+        $this->assertEquals([
189
+            16 => [$section],
190
+            100 => [$section2],
191
+        ], $settings);
192
+    }
193
+
194
+    public function testSameSectionAsPersonalAndAdmin(): void {
195
+        $this->l10nFactory
196
+            ->expects($this->once())
197
+            ->method('get')
198
+            ->with('lib')
199
+            ->willReturn($this->l10n);
200
+        $this->l10n
201
+            ->expects($this->any())
202
+            ->method('t')
203
+            ->willReturnArgument(0);
204
+
205
+        $this->manager->registerSection('personal', \OCA\WorkflowEngine\Settings\Section::class);
206
+        $this->manager->registerSection('admin', \OCA\WorkflowEngine\Settings\Section::class);
207
+
208
+
209
+        $section = \OC::$server->query(\OCA\WorkflowEngine\Settings\Section::class);
210
+        $this->container->method('get')
211
+            ->with(\OCA\WorkflowEngine\Settings\Section::class)
212
+            ->willReturn($section);
213
+
214
+        $this->assertEquals([
215
+            55 => [$section],
216
+        ], $this->manager->getPersonalSections());
217
+
218
+        $this->assertEquals([
219
+            55 => [$section],
220
+        ], $this->manager->getAdminSections());
221
+    }
222 222
 }
Please login to merge, or discard this patch.
tests/lib/OCS/ProviderTest.php 1 patch
Indentation   +180 added lines, -180 removed lines patch added patch discarded remove patch
@@ -10,184 +10,184 @@
 block discarded – undo
10 10
 use OC\OCS\Provider;
11 11
 
12 12
 class ProviderTest extends \Test\TestCase {
13
-	/** @var \OCP\IRequest */
14
-	private $request;
15
-	/** @var \OCP\App\IAppManager */
16
-	private $appManager;
17
-	/** @var Provider */
18
-	private $ocsProvider;
19
-
20
-	protected function setUp(): void {
21
-		parent::setUp();
22
-
23
-		$this->request = $this->getMockBuilder('\\OCP\\IRequest')->getMock();
24
-		$this->appManager = $this->getMockBuilder('\\OCP\\App\\IAppManager')->getMock();
25
-		$this->ocsProvider = new Provider('ocs_provider', $this->request, $this->appManager);
26
-	}
27
-
28
-	public function testBuildProviderListWithoutAnythingEnabled(): void {
29
-		$this->appManager
30
-			->expects($this->exactly(4))
31
-			->method('isEnabledForUser')
32
-			->willReturnMap([
33
-				['files_sharing', null, false],
34
-				['federation', null, false],
35
-				['activity', null, false],
36
-				['provisioning_api', null, false],
37
-			]);
38
-
39
-		$expected = new \OCP\AppFramework\Http\JSONResponse(
40
-			[
41
-				'version' => 2,
42
-				'services' => [
43
-					'PRIVATE_DATA' => [
44
-						'version' => 1,
45
-						'endpoints' => [
46
-							'store' => '/ocs/v2.php/privatedata/setattribute',
47
-							'read' => '/ocs/v2.php/privatedata/getattribute',
48
-							'delete' => '/ocs/v2.php/privatedata/deleteattribute',
49
-						],
50
-					],
51
-				],
52
-			]
53
-		);
54
-
55
-		$this->assertEquals($expected, $this->ocsProvider->buildProviderList());
56
-	}
57
-
58
-	public function testBuildProviderListWithSharingEnabled(): void {
59
-		$this->appManager
60
-			->expects($this->exactly(4))
61
-			->method('isEnabledForUser')
62
-			->willReturnMap([
63
-				['files_sharing', null, true],
64
-				['federation', null, false],
65
-				['activity', null, false],
66
-				['provisioning_api', null, false],
67
-			]);
68
-
69
-		$expected = new \OCP\AppFramework\Http\JSONResponse(
70
-			[
71
-				'version' => 2,
72
-				'services' => [
73
-					'PRIVATE_DATA' => [
74
-						'version' => 1,
75
-						'endpoints' => [
76
-							'store' => '/ocs/v2.php/privatedata/setattribute',
77
-							'read' => '/ocs/v2.php/privatedata/getattribute',
78
-							'delete' => '/ocs/v2.php/privatedata/deleteattribute',
79
-						],
80
-					],
81
-					'FEDERATED_SHARING' => [
82
-						'version' => 1,
83
-						'endpoints' => [
84
-							'share' => '/ocs/v2.php/cloud/shares',
85
-							'webdav' => '/public.php/webdav/',
86
-						],
87
-					],
88
-					'SHARING' => [
89
-						'version' => 1,
90
-						'endpoints' => [
91
-							'share' => '/ocs/v2.php/apps/files_sharing/api/v1/shares',
92
-						],
93
-					],
94
-				],
95
-			]
96
-		);
97
-
98
-		$this->assertEquals($expected, $this->ocsProvider->buildProviderList());
99
-	}
100
-
101
-	public function testBuildProviderListWithFederationEnabled(): void {
102
-		$this->appManager
103
-			->expects($this->exactly(4))
104
-			->method('isEnabledForUser')
105
-			->willReturnMap([
106
-				['files_sharing', null, false],
107
-				['federation', null, true],
108
-				['activity', null, false],
109
-				['provisioning_api', null, false],
110
-			]);
111
-
112
-		$expected = new \OCP\AppFramework\Http\JSONResponse(
113
-			[
114
-				'version' => 2,
115
-				'services' => [
116
-					'PRIVATE_DATA' => [
117
-						'version' => 1,
118
-						'endpoints' => [
119
-							'store' => '/ocs/v2.php/privatedata/setattribute',
120
-							'read' => '/ocs/v2.php/privatedata/getattribute',
121
-							'delete' => '/ocs/v2.php/privatedata/deleteattribute',
122
-						],
123
-					],
124
-					'FEDERATED_SHARING' => [
125
-						'version' => 1,
126
-						'endpoints' => [
127
-							'shared-secret' => '/ocs/v2.php/cloud/shared-secret',
128
-							'system-address-book' => '/remote.php/dav/addressbooks/system/system/system',
129
-							'carddav-user' => 'system'
130
-						],
131
-					],
132
-				],
133
-			]
134
-		);
135
-
136
-		$this->assertEquals($expected, $this->ocsProvider->buildProviderList());
137
-	}
138
-
139
-	public function testBuildProviderListWithEverythingEnabled(): void {
140
-		$this->appManager
141
-			->expects($this->any())
142
-			->method('isEnabledForUser')
143
-			->willReturn(true);
144
-
145
-		$expected = new \OCP\AppFramework\Http\JSONResponse(
146
-			[
147
-				'version' => 2,
148
-				'services' => [
149
-					'PRIVATE_DATA' => [
150
-						'version' => 1,
151
-						'endpoints' => [
152
-							'store' => '/ocs/v2.php/privatedata/setattribute',
153
-							'read' => '/ocs/v2.php/privatedata/getattribute',
154
-							'delete' => '/ocs/v2.php/privatedata/deleteattribute',
155
-						],
156
-					],
157
-					'FEDERATED_SHARING' => [
158
-						'version' => 1,
159
-						'endpoints' => [
160
-							'share' => '/ocs/v2.php/cloud/shares',
161
-							'webdav' => '/public.php/webdav/',
162
-							'shared-secret' => '/ocs/v2.php/cloud/shared-secret',
163
-							'system-address-book' => '/remote.php/dav/addressbooks/system/system/system',
164
-							'carddav-user' => 'system'
165
-						],
166
-					],
167
-					'SHARING' => [
168
-						'version' => 1,
169
-						'endpoints' => [
170
-							'share' => '/ocs/v2.php/apps/files_sharing/api/v1/shares',
171
-						],
172
-					],
173
-					'ACTIVITY' => [
174
-						'version' => 1,
175
-						'endpoints' => [
176
-							'list' => '/ocs/v2.php/cloud/activity',
177
-						],
178
-					],
179
-					'PROVISIONING' => [
180
-						'version' => 1,
181
-						'endpoints' => [
182
-							'user' => '/ocs/v2.php/cloud/users',
183
-							'groups' => '/ocs/v2.php/cloud/groups',
184
-							'apps' => '/ocs/v2.php/cloud/apps',
185
-						],
186
-					],
187
-				],
188
-			]
189
-		);
190
-
191
-		$this->assertEquals($expected, $this->ocsProvider->buildProviderList());
192
-	}
13
+    /** @var \OCP\IRequest */
14
+    private $request;
15
+    /** @var \OCP\App\IAppManager */
16
+    private $appManager;
17
+    /** @var Provider */
18
+    private $ocsProvider;
19
+
20
+    protected function setUp(): void {
21
+        parent::setUp();
22
+
23
+        $this->request = $this->getMockBuilder('\\OCP\\IRequest')->getMock();
24
+        $this->appManager = $this->getMockBuilder('\\OCP\\App\\IAppManager')->getMock();
25
+        $this->ocsProvider = new Provider('ocs_provider', $this->request, $this->appManager);
26
+    }
27
+
28
+    public function testBuildProviderListWithoutAnythingEnabled(): void {
29
+        $this->appManager
30
+            ->expects($this->exactly(4))
31
+            ->method('isEnabledForUser')
32
+            ->willReturnMap([
33
+                ['files_sharing', null, false],
34
+                ['federation', null, false],
35
+                ['activity', null, false],
36
+                ['provisioning_api', null, false],
37
+            ]);
38
+
39
+        $expected = new \OCP\AppFramework\Http\JSONResponse(
40
+            [
41
+                'version' => 2,
42
+                'services' => [
43
+                    'PRIVATE_DATA' => [
44
+                        'version' => 1,
45
+                        'endpoints' => [
46
+                            'store' => '/ocs/v2.php/privatedata/setattribute',
47
+                            'read' => '/ocs/v2.php/privatedata/getattribute',
48
+                            'delete' => '/ocs/v2.php/privatedata/deleteattribute',
49
+                        ],
50
+                    ],
51
+                ],
52
+            ]
53
+        );
54
+
55
+        $this->assertEquals($expected, $this->ocsProvider->buildProviderList());
56
+    }
57
+
58
+    public function testBuildProviderListWithSharingEnabled(): void {
59
+        $this->appManager
60
+            ->expects($this->exactly(4))
61
+            ->method('isEnabledForUser')
62
+            ->willReturnMap([
63
+                ['files_sharing', null, true],
64
+                ['federation', null, false],
65
+                ['activity', null, false],
66
+                ['provisioning_api', null, false],
67
+            ]);
68
+
69
+        $expected = new \OCP\AppFramework\Http\JSONResponse(
70
+            [
71
+                'version' => 2,
72
+                'services' => [
73
+                    'PRIVATE_DATA' => [
74
+                        'version' => 1,
75
+                        'endpoints' => [
76
+                            'store' => '/ocs/v2.php/privatedata/setattribute',
77
+                            'read' => '/ocs/v2.php/privatedata/getattribute',
78
+                            'delete' => '/ocs/v2.php/privatedata/deleteattribute',
79
+                        ],
80
+                    ],
81
+                    'FEDERATED_SHARING' => [
82
+                        'version' => 1,
83
+                        'endpoints' => [
84
+                            'share' => '/ocs/v2.php/cloud/shares',
85
+                            'webdav' => '/public.php/webdav/',
86
+                        ],
87
+                    ],
88
+                    'SHARING' => [
89
+                        'version' => 1,
90
+                        'endpoints' => [
91
+                            'share' => '/ocs/v2.php/apps/files_sharing/api/v1/shares',
92
+                        ],
93
+                    ],
94
+                ],
95
+            ]
96
+        );
97
+
98
+        $this->assertEquals($expected, $this->ocsProvider->buildProviderList());
99
+    }
100
+
101
+    public function testBuildProviderListWithFederationEnabled(): void {
102
+        $this->appManager
103
+            ->expects($this->exactly(4))
104
+            ->method('isEnabledForUser')
105
+            ->willReturnMap([
106
+                ['files_sharing', null, false],
107
+                ['federation', null, true],
108
+                ['activity', null, false],
109
+                ['provisioning_api', null, false],
110
+            ]);
111
+
112
+        $expected = new \OCP\AppFramework\Http\JSONResponse(
113
+            [
114
+                'version' => 2,
115
+                'services' => [
116
+                    'PRIVATE_DATA' => [
117
+                        'version' => 1,
118
+                        'endpoints' => [
119
+                            'store' => '/ocs/v2.php/privatedata/setattribute',
120
+                            'read' => '/ocs/v2.php/privatedata/getattribute',
121
+                            'delete' => '/ocs/v2.php/privatedata/deleteattribute',
122
+                        ],
123
+                    ],
124
+                    'FEDERATED_SHARING' => [
125
+                        'version' => 1,
126
+                        'endpoints' => [
127
+                            'shared-secret' => '/ocs/v2.php/cloud/shared-secret',
128
+                            'system-address-book' => '/remote.php/dav/addressbooks/system/system/system',
129
+                            'carddav-user' => 'system'
130
+                        ],
131
+                    ],
132
+                ],
133
+            ]
134
+        );
135
+
136
+        $this->assertEquals($expected, $this->ocsProvider->buildProviderList());
137
+    }
138
+
139
+    public function testBuildProviderListWithEverythingEnabled(): void {
140
+        $this->appManager
141
+            ->expects($this->any())
142
+            ->method('isEnabledForUser')
143
+            ->willReturn(true);
144
+
145
+        $expected = new \OCP\AppFramework\Http\JSONResponse(
146
+            [
147
+                'version' => 2,
148
+                'services' => [
149
+                    'PRIVATE_DATA' => [
150
+                        'version' => 1,
151
+                        'endpoints' => [
152
+                            'store' => '/ocs/v2.php/privatedata/setattribute',
153
+                            'read' => '/ocs/v2.php/privatedata/getattribute',
154
+                            'delete' => '/ocs/v2.php/privatedata/deleteattribute',
155
+                        ],
156
+                    ],
157
+                    'FEDERATED_SHARING' => [
158
+                        'version' => 1,
159
+                        'endpoints' => [
160
+                            'share' => '/ocs/v2.php/cloud/shares',
161
+                            'webdav' => '/public.php/webdav/',
162
+                            'shared-secret' => '/ocs/v2.php/cloud/shared-secret',
163
+                            'system-address-book' => '/remote.php/dav/addressbooks/system/system/system',
164
+                            'carddav-user' => 'system'
165
+                        ],
166
+                    ],
167
+                    'SHARING' => [
168
+                        'version' => 1,
169
+                        'endpoints' => [
170
+                            'share' => '/ocs/v2.php/apps/files_sharing/api/v1/shares',
171
+                        ],
172
+                    ],
173
+                    'ACTIVITY' => [
174
+                        'version' => 1,
175
+                        'endpoints' => [
176
+                            'list' => '/ocs/v2.php/cloud/activity',
177
+                        ],
178
+                    ],
179
+                    'PROVISIONING' => [
180
+                        'version' => 1,
181
+                        'endpoints' => [
182
+                            'user' => '/ocs/v2.php/cloud/users',
183
+                            'groups' => '/ocs/v2.php/cloud/groups',
184
+                            'apps' => '/ocs/v2.php/cloud/apps',
185
+                        ],
186
+                    ],
187
+                ],
188
+            ]
189
+        );
190
+
191
+        $this->assertEquals($expected, $this->ocsProvider->buildProviderList());
192
+    }
193 193
 }
Please login to merge, or discard this patch.
tests/lib/Updater/ChangesCheckTest.php 2 patches
Indentation   +294 added lines, -294 removed lines patch added patch discarded remove patch
@@ -20,92 +20,92 @@  discard block
 block discarded – undo
20 20
 use Test\TestCase;
21 21
 
22 22
 class ChangesCheckTest extends TestCase {
23
-	/** @var IClientService|\PHPUnit\Framework\MockObject\MockObject */
24
-	protected $clientService;
25
-
26
-	/** @var ChangesCheck */
27
-	protected $checker;
28
-
29
-	/** @var ChangesMapper|\PHPUnit\Framework\MockObject\MockObject */
30
-	protected $mapper;
31
-
32
-	/** @var LoggerInterface|\PHPUnit\Framework\MockObject\MockObject */
33
-	protected $logger;
34
-
35
-	protected function setUp(): void {
36
-		parent::setUp();
37
-
38
-		$this->clientService = $this->createMock(IClientService::class);
39
-		$this->mapper = $this->createMock(ChangesMapper::class);
40
-		$this->logger = $this->createMock(LoggerInterface::class);
41
-
42
-		$this->checker = new ChangesCheck($this->clientService, $this->mapper, $this->logger);
43
-	}
44
-
45
-	public static function statusCodeProvider(): array {
46
-		return [
47
-			[200, ChangesCheck::RESPONSE_HAS_CONTENT],
48
-			[304, ChangesCheck::RESPONSE_USE_CACHE],
49
-			[404, ChangesCheck::RESPONSE_NO_CONTENT],
50
-			[418, ChangesCheck::RESPONSE_NO_CONTENT],
51
-		];
52
-	}
53
-
54
-	/**
55
-	 * @dataProvider statusCodeProvider
56
-	 */
57
-	public function testEvaluateResponse(int $statusCode, int $expected): void {
58
-		$response = $this->createMock(IResponse::class);
59
-		$response->expects($this->atLeastOnce())
60
-			->method('getStatusCode')
61
-			->willReturn($statusCode);
62
-
63
-		if (!in_array($statusCode, [200, 304, 404])) {
64
-			$this->logger->expects($this->once())
65
-				->method('debug');
66
-		}
67
-
68
-		$evaluation = $this->invokePrivate($this->checker, 'evaluateResponse', [$response]);
69
-		$this->assertSame($expected, $evaluation);
70
-	}
71
-
72
-	public function testCacheResultInsert(): void {
73
-		$version = '13.0.4';
74
-		$entry = $this->createMock(Changes::class);
75
-		$entry->expects($this->exactly(2))
76
-			->method('__call')
77
-			->willReturnMap([
78
-				['getVersion', [], ''],
79
-				['setVersion', [$version], null],
80
-			]);
81
-
82
-		$this->mapper->expects($this->once())
83
-			->method('insert');
84
-		$this->mapper->expects($this->never())
85
-			->method('update');
86
-
87
-		$this->invokePrivate($this->checker, 'cacheResult', [$entry, $version]);
88
-	}
89
-
90
-	public function testCacheResultUpdate(): void {
91
-		$version = '13.0.4';
92
-		$entry = $this->createMock(Changes::class);
93
-		$entry->expects($this->once())
94
-			->method('__call')
95
-			->willReturn($version);
96
-
97
-		$this->mapper->expects($this->never())
98
-			->method('insert');
99
-		$this->mapper->expects($this->once())
100
-			->method('update');
101
-
102
-		$this->invokePrivate($this->checker, 'cacheResult', [$entry, $version]);
103
-	}
104
-
105
-	public static function changesXMLProvider(): array {
106
-		return [
107
-			[ # 0 - full example
108
-				'<?xml version="1.0" encoding="utf-8" ?>
23
+    /** @var IClientService|\PHPUnit\Framework\MockObject\MockObject */
24
+    protected $clientService;
25
+
26
+    /** @var ChangesCheck */
27
+    protected $checker;
28
+
29
+    /** @var ChangesMapper|\PHPUnit\Framework\MockObject\MockObject */
30
+    protected $mapper;
31
+
32
+    /** @var LoggerInterface|\PHPUnit\Framework\MockObject\MockObject */
33
+    protected $logger;
34
+
35
+    protected function setUp(): void {
36
+        parent::setUp();
37
+
38
+        $this->clientService = $this->createMock(IClientService::class);
39
+        $this->mapper = $this->createMock(ChangesMapper::class);
40
+        $this->logger = $this->createMock(LoggerInterface::class);
41
+
42
+        $this->checker = new ChangesCheck($this->clientService, $this->mapper, $this->logger);
43
+    }
44
+
45
+    public static function statusCodeProvider(): array {
46
+        return [
47
+            [200, ChangesCheck::RESPONSE_HAS_CONTENT],
48
+            [304, ChangesCheck::RESPONSE_USE_CACHE],
49
+            [404, ChangesCheck::RESPONSE_NO_CONTENT],
50
+            [418, ChangesCheck::RESPONSE_NO_CONTENT],
51
+        ];
52
+    }
53
+
54
+    /**
55
+     * @dataProvider statusCodeProvider
56
+     */
57
+    public function testEvaluateResponse(int $statusCode, int $expected): void {
58
+        $response = $this->createMock(IResponse::class);
59
+        $response->expects($this->atLeastOnce())
60
+            ->method('getStatusCode')
61
+            ->willReturn($statusCode);
62
+
63
+        if (!in_array($statusCode, [200, 304, 404])) {
64
+            $this->logger->expects($this->once())
65
+                ->method('debug');
66
+        }
67
+
68
+        $evaluation = $this->invokePrivate($this->checker, 'evaluateResponse', [$response]);
69
+        $this->assertSame($expected, $evaluation);
70
+    }
71
+
72
+    public function testCacheResultInsert(): void {
73
+        $version = '13.0.4';
74
+        $entry = $this->createMock(Changes::class);
75
+        $entry->expects($this->exactly(2))
76
+            ->method('__call')
77
+            ->willReturnMap([
78
+                ['getVersion', [], ''],
79
+                ['setVersion', [$version], null],
80
+            ]);
81
+
82
+        $this->mapper->expects($this->once())
83
+            ->method('insert');
84
+        $this->mapper->expects($this->never())
85
+            ->method('update');
86
+
87
+        $this->invokePrivate($this->checker, 'cacheResult', [$entry, $version]);
88
+    }
89
+
90
+    public function testCacheResultUpdate(): void {
91
+        $version = '13.0.4';
92
+        $entry = $this->createMock(Changes::class);
93
+        $entry->expects($this->once())
94
+            ->method('__call')
95
+            ->willReturn($version);
96
+
97
+        $this->mapper->expects($this->never())
98
+            ->method('insert');
99
+        $this->mapper->expects($this->once())
100
+            ->method('update');
101
+
102
+        $this->invokePrivate($this->checker, 'cacheResult', [$entry, $version]);
103
+    }
104
+
105
+    public static function changesXMLProvider(): array {
106
+        return [
107
+            [ # 0 - full example
108
+                '<?xml version="1.0" encoding="utf-8" ?>
109 109
 <release xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance"
110 110
          xsi:noNamespaceSchemaLocation="https://updates.nextcloud.com/changelog_server/schema.xsd"
111 111
          version="13.0.0">
@@ -133,36 +133,36 @@  discard block
 block discarded – undo
133 133
         </admin>
134 134
     </whatsNew>
135 135
 </release>',
136
-				[
137
-					'changelogURL' => 'https://nextcloud.com/changelog/#13-0-0',
138
-					'whatsNew' => [
139
-						'en' => [
140
-							'regular' => [
141
-								'Refined user interface',
142
-								'End-to-end Encryption',
143
-								'Video and Text Chat'
144
-							],
145
-							'admin' => [
146
-								'Changes to the Nginx configuration',
147
-								'Theming: CSS files were consolidated'
148
-							],
149
-						],
150
-						'de' => [
151
-							'regular' => [
152
-								'Überarbeitete Benutzerschnittstelle',
153
-								'Ende-zu-Ende Verschlüsselung',
154
-								'Video- und Text-Chat'
155
-							],
156
-							'admin' => [
157
-								'Änderungen an der Nginx Konfiguration',
158
-								'Theming: CSS Dateien wurden konsolidiert'
159
-							],
160
-						],
161
-					],
162
-				]
163
-			],
164
-			[ # 1- admin part not translated
165
-				'<?xml version="1.0" encoding="utf-8" ?>
136
+                [
137
+                    'changelogURL' => 'https://nextcloud.com/changelog/#13-0-0',
138
+                    'whatsNew' => [
139
+                        'en' => [
140
+                            'regular' => [
141
+                                'Refined user interface',
142
+                                'End-to-end Encryption',
143
+                                'Video and Text Chat'
144
+                            ],
145
+                            'admin' => [
146
+                                'Changes to the Nginx configuration',
147
+                                'Theming: CSS files were consolidated'
148
+                            ],
149
+                        ],
150
+                        'de' => [
151
+                            'regular' => [
152
+                                'Überarbeitete Benutzerschnittstelle',
153
+                                'Ende-zu-Ende Verschlüsselung',
154
+                                'Video- und Text-Chat'
155
+                            ],
156
+                            'admin' => [
157
+                                'Änderungen an der Nginx Konfiguration',
158
+                                'Theming: CSS Dateien wurden konsolidiert'
159
+                            ],
160
+                        ],
161
+                    ],
162
+                ]
163
+            ],
164
+            [ # 1- admin part not translated
165
+                '<?xml version="1.0" encoding="utf-8" ?>
166 166
 <release xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance"
167 167
          xsi:noNamespaceSchemaLocation="https://updates.nextcloud.com/changelog_server/schema.xsd"
168 168
          version="13.0.0">
@@ -186,34 +186,34 @@  discard block
 block discarded – undo
186 186
         </regular>
187 187
     </whatsNew>
188 188
 </release>',
189
-				[
190
-					'changelogURL' => 'https://nextcloud.com/changelog/#13-0-0',
191
-					'whatsNew' => [
192
-						'en' => [
193
-							'regular' => [
194
-								'Refined user interface',
195
-								'End-to-end Encryption',
196
-								'Video and Text Chat'
197
-							],
198
-							'admin' => [
199
-								'Changes to the Nginx configuration',
200
-								'Theming: CSS files were consolidated'
201
-							],
202
-						],
203
-						'de' => [
204
-							'regular' => [
205
-								'Überarbeitete Benutzerschnittstelle',
206
-								'Ende-zu-Ende Verschlüsselung',
207
-								'Video- und Text-Chat'
208
-							],
209
-							'admin' => [
210
-							],
211
-						],
212
-					],
213
-				]
214
-			],
215
-			[ # 2 - minimal set
216
-				'<?xml version="1.0" encoding="utf-8" ?>
189
+                [
190
+                    'changelogURL' => 'https://nextcloud.com/changelog/#13-0-0',
191
+                    'whatsNew' => [
192
+                        'en' => [
193
+                            'regular' => [
194
+                                'Refined user interface',
195
+                                'End-to-end Encryption',
196
+                                'Video and Text Chat'
197
+                            ],
198
+                            'admin' => [
199
+                                'Changes to the Nginx configuration',
200
+                                'Theming: CSS files were consolidated'
201
+                            ],
202
+                        ],
203
+                        'de' => [
204
+                            'regular' => [
205
+                                'Überarbeitete Benutzerschnittstelle',
206
+                                'Ende-zu-Ende Verschlüsselung',
207
+                                'Video- und Text-Chat'
208
+                            ],
209
+                            'admin' => [
210
+                            ],
211
+                        ],
212
+                    ],
213
+                ]
214
+            ],
215
+            [ # 2 - minimal set
216
+                '<?xml version="1.0" encoding="utf-8" ?>
217 217
 <release xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance"
218 218
          xsi:noNamespaceSchemaLocation="https://updates.nextcloud.com/changelog_server/schema.xsd"
219 219
          version="13.0.0">
@@ -226,22 +226,22 @@  discard block
 block discarded – undo
226 226
         </regular>
227 227
     </whatsNew>
228 228
 </release>',
229
-				[
230
-					'changelogURL' => 'https://nextcloud.com/changelog/#13-0-0',
231
-					'whatsNew' => [
232
-						'en' => [
233
-							'regular' => [
234
-								'Refined user interface',
235
-								'End-to-end Encryption',
236
-								'Video and Text Chat'
237
-							],
238
-							'admin' => [],
239
-						],
240
-					],
241
-				]
242
-			],
243
-			[ # 3 - minimal set (procrastinator edition)
244
-				'<?xml version="1.0" encoding="utf-8" ?>
229
+                [
230
+                    'changelogURL' => 'https://nextcloud.com/changelog/#13-0-0',
231
+                    'whatsNew' => [
232
+                        'en' => [
233
+                            'regular' => [
234
+                                'Refined user interface',
235
+                                'End-to-end Encryption',
236
+                                'Video and Text Chat'
237
+                            ],
238
+                            'admin' => [],
239
+                        ],
240
+                    ],
241
+                ]
242
+            ],
243
+            [ # 3 - minimal set (procrastinator edition)
244
+                '<?xml version="1.0" encoding="utf-8" ?>
245 245
 <release xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance"
246 246
          xsi:noNamespaceSchemaLocation="https://updates.nextcloud.com/changelog_server/schema.xsd"
247 247
          version="13.0.0">
@@ -252,138 +252,138 @@  discard block
 block discarded – undo
252 252
         </regular>
253 253
     </whatsNew>
254 254
 </release>',
255
-				[
256
-					'changelogURL' => 'https://nextcloud.com/changelog/#13-0-0',
257
-					'whatsNew' => [
258
-						'en' => [
259
-							'regular' => [
260
-								'Write this tomorrow',
261
-							],
262
-							'admin' => [],
263
-						],
264
-					],
265
-				]
266
-			],
267
-			[ # 4 - empty
268
-				'',
269
-				[]
270
-			],
271
-		];
272
-	}
273
-
274
-	/**
275
-	 * @dataProvider changesXMLProvider
276
-	 */
277
-	public function testExtractData(string $body, array $expected): void {
278
-		$actual = $this->invokePrivate($this->checker, 'extractData', [$body]);
279
-		$this->assertSame($expected, $actual);
280
-	}
281
-
282
-	public static function etagProvider() {
283
-		return [
284
-			[''],
285
-			['a27aab83d8205d73978435076e53d143']
286
-		];
287
-	}
288
-
289
-	/**
290
-	 * @dataProvider etagProvider
291
-	 */
292
-	public function testQueryChangesServer(string $etag): void {
293
-		$uri = 'https://changes.nextcloud.server/?13.0.5';
294
-		$entry = $this->createMock(Changes::class);
295
-		$entry->expects($this->any())
296
-			->method('__call')
297
-			->willReturn($etag);
298
-
299
-		$expectedHeaders = $etag === '' ? [] : ['If-None-Match' => [$etag]];
300
-
301
-		$client = $this->createMock(IClient::class);
302
-		$client->expects($this->once())
303
-			->method('get')
304
-			->with($uri, ['headers' => $expectedHeaders])
305
-			->willReturn($this->createMock(IResponse::class));
306
-
307
-		$this->clientService->expects($this->once())
308
-			->method('newClient')
309
-			->willReturn($client);
310
-
311
-		$response = $this->invokePrivate($this->checker, 'queryChangesServer', [$uri, $entry]);
312
-		$this->assertInstanceOf(IResponse::class, $response);
313
-	}
314
-
315
-	public static function versionProvider(): array {
316
-		return [
317
-			['13.0.7', '13.0.7'],
318
-			['13.0.7.3', '13.0.7'],
319
-			['13.0.7.3.42', '13.0.7'],
320
-			['13.0', '13.0.0'],
321
-			['13', '13.0.0'],
322
-			['', '0.0.0'],
323
-		];
324
-	}
325
-
326
-	/**
327
-	 * @dataProvider versionProvider
328
-	 */
329
-	public function testNormalizeVersion(string $input, string $expected): void {
330
-		$normalized = $this->checker->normalizeVersion($input);
331
-		$this->assertSame($expected, $normalized);
332
-	}
333
-
334
-	public static function changeDataProvider():array {
335
-		$testDataFound = $testDataNotFound = self::versionProvider();
336
-		array_walk($testDataFound, static function (&$params) {
337
-			$params[] = true;
338
-		});
339
-		array_walk($testDataNotFound, static function (&$params) {
340
-			$params[] = false;
341
-		});
342
-		return array_merge($testDataFound, $testDataNotFound);
343
-	}
344
-
345
-	/**
346
-	 * @dataProvider changeDataProvider
347
-	 *
348
-	 */
349
-	public function testGetChangesForVersion(string $inputVersion, string $normalizedVersion, bool $isFound): void {
350
-		$mocker = $this->mapper->expects($this->once())
351
-			->method('getChanges')
352
-			->with($normalizedVersion);
353
-
354
-		if (!$isFound) {
355
-			$this->expectException(DoesNotExistException::class);
356
-			$mocker->willThrowException(new DoesNotExistException('Changes info is not present'));
357
-		} else {
358
-			$entry = $this->createMock(Changes::class);
359
-			$entry->expects($this->once())
360
-				->method('__call')
361
-				->with('getData')
362
-				->willReturn('{"changelogURL":"https:\/\/nextcloud.com\/changelog\/#13-0-0","whatsNew":{"en":{"regular":["Refined user interface","End-to-end Encryption","Video and Text Chat"],"admin":["Changes to the Nginx configuration","Theming: CSS files were consolidated"]},"de":{"regular":["\u00dcberarbeitete Benutzerschnittstelle","Ende-zu-Ende Verschl\u00fcsselung","Video- und Text-Chat"],"admin":["\u00c4nderungen an der Nginx Konfiguration","Theming: CSS Dateien wurden konsolidiert"]}}}');
363
-
364
-			$mocker->willReturn($entry);
365
-		}
366
-
367
-		/** @noinspection PhpUnhandledExceptionInspection */
368
-		$data = $this->checker->getChangesForVersion($inputVersion);
369
-		$this->assertTrue(isset($data['whatsNew']['en']['regular']));
370
-		$this->assertTrue(isset($data['changelogURL']));
371
-	}
372
-
373
-	public function testGetChangesForVersionEmptyData(): void {
374
-		$entry = $this->createMock(Changes::class);
375
-		$entry->expects($this->once())
376
-			->method('__call')
377
-			->with('getData')
378
-			->willReturn('');
379
-
380
-		$this->mapper->expects($this->once())
381
-			->method('getChanges')
382
-			->with('13.0.7')
383
-			->willReturn($entry);
384
-
385
-		$this->expectException(DoesNotExistException::class);
386
-		/** @noinspection PhpUnhandledExceptionInspection */
387
-		$this->checker->getChangesForVersion('13.0.7');
388
-	}
255
+                [
256
+                    'changelogURL' => 'https://nextcloud.com/changelog/#13-0-0',
257
+                    'whatsNew' => [
258
+                        'en' => [
259
+                            'regular' => [
260
+                                'Write this tomorrow',
261
+                            ],
262
+                            'admin' => [],
263
+                        ],
264
+                    ],
265
+                ]
266
+            ],
267
+            [ # 4 - empty
268
+                '',
269
+                []
270
+            ],
271
+        ];
272
+    }
273
+
274
+    /**
275
+     * @dataProvider changesXMLProvider
276
+     */
277
+    public function testExtractData(string $body, array $expected): void {
278
+        $actual = $this->invokePrivate($this->checker, 'extractData', [$body]);
279
+        $this->assertSame($expected, $actual);
280
+    }
281
+
282
+    public static function etagProvider() {
283
+        return [
284
+            [''],
285
+            ['a27aab83d8205d73978435076e53d143']
286
+        ];
287
+    }
288
+
289
+    /**
290
+     * @dataProvider etagProvider
291
+     */
292
+    public function testQueryChangesServer(string $etag): void {
293
+        $uri = 'https://changes.nextcloud.server/?13.0.5';
294
+        $entry = $this->createMock(Changes::class);
295
+        $entry->expects($this->any())
296
+            ->method('__call')
297
+            ->willReturn($etag);
298
+
299
+        $expectedHeaders = $etag === '' ? [] : ['If-None-Match' => [$etag]];
300
+
301
+        $client = $this->createMock(IClient::class);
302
+        $client->expects($this->once())
303
+            ->method('get')
304
+            ->with($uri, ['headers' => $expectedHeaders])
305
+            ->willReturn($this->createMock(IResponse::class));
306
+
307
+        $this->clientService->expects($this->once())
308
+            ->method('newClient')
309
+            ->willReturn($client);
310
+
311
+        $response = $this->invokePrivate($this->checker, 'queryChangesServer', [$uri, $entry]);
312
+        $this->assertInstanceOf(IResponse::class, $response);
313
+    }
314
+
315
+    public static function versionProvider(): array {
316
+        return [
317
+            ['13.0.7', '13.0.7'],
318
+            ['13.0.7.3', '13.0.7'],
319
+            ['13.0.7.3.42', '13.0.7'],
320
+            ['13.0', '13.0.0'],
321
+            ['13', '13.0.0'],
322
+            ['', '0.0.0'],
323
+        ];
324
+    }
325
+
326
+    /**
327
+     * @dataProvider versionProvider
328
+     */
329
+    public function testNormalizeVersion(string $input, string $expected): void {
330
+        $normalized = $this->checker->normalizeVersion($input);
331
+        $this->assertSame($expected, $normalized);
332
+    }
333
+
334
+    public static function changeDataProvider():array {
335
+        $testDataFound = $testDataNotFound = self::versionProvider();
336
+        array_walk($testDataFound, static function (&$params) {
337
+            $params[] = true;
338
+        });
339
+        array_walk($testDataNotFound, static function (&$params) {
340
+            $params[] = false;
341
+        });
342
+        return array_merge($testDataFound, $testDataNotFound);
343
+    }
344
+
345
+    /**
346
+     * @dataProvider changeDataProvider
347
+     *
348
+     */
349
+    public function testGetChangesForVersion(string $inputVersion, string $normalizedVersion, bool $isFound): void {
350
+        $mocker = $this->mapper->expects($this->once())
351
+            ->method('getChanges')
352
+            ->with($normalizedVersion);
353
+
354
+        if (!$isFound) {
355
+            $this->expectException(DoesNotExistException::class);
356
+            $mocker->willThrowException(new DoesNotExistException('Changes info is not present'));
357
+        } else {
358
+            $entry = $this->createMock(Changes::class);
359
+            $entry->expects($this->once())
360
+                ->method('__call')
361
+                ->with('getData')
362
+                ->willReturn('{"changelogURL":"https:\/\/nextcloud.com\/changelog\/#13-0-0","whatsNew":{"en":{"regular":["Refined user interface","End-to-end Encryption","Video and Text Chat"],"admin":["Changes to the Nginx configuration","Theming: CSS files were consolidated"]},"de":{"regular":["\u00dcberarbeitete Benutzerschnittstelle","Ende-zu-Ende Verschl\u00fcsselung","Video- und Text-Chat"],"admin":["\u00c4nderungen an der Nginx Konfiguration","Theming: CSS Dateien wurden konsolidiert"]}}}');
363
+
364
+            $mocker->willReturn($entry);
365
+        }
366
+
367
+        /** @noinspection PhpUnhandledExceptionInspection */
368
+        $data = $this->checker->getChangesForVersion($inputVersion);
369
+        $this->assertTrue(isset($data['whatsNew']['en']['regular']));
370
+        $this->assertTrue(isset($data['changelogURL']));
371
+    }
372
+
373
+    public function testGetChangesForVersionEmptyData(): void {
374
+        $entry = $this->createMock(Changes::class);
375
+        $entry->expects($this->once())
376
+            ->method('__call')
377
+            ->with('getData')
378
+            ->willReturn('');
379
+
380
+        $this->mapper->expects($this->once())
381
+            ->method('getChanges')
382
+            ->with('13.0.7')
383
+            ->willReturn($entry);
384
+
385
+        $this->expectException(DoesNotExistException::class);
386
+        /** @noinspection PhpUnhandledExceptionInspection */
387
+        $this->checker->getChangesForVersion('13.0.7');
388
+    }
389 389
 }
Please login to merge, or discard this patch.
Spacing   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -104,7 +104,7 @@  discard block
 block discarded – undo
104 104
 
105 105
 	public static function changesXMLProvider(): array {
106 106
 		return [
107
-			[ # 0 - full example
107
+			[# 0 - full example
108 108
 				'<?xml version="1.0" encoding="utf-8" ?>
109 109
 <release xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance"
110 110
          xsi:noNamespaceSchemaLocation="https://updates.nextcloud.com/changelog_server/schema.xsd"
@@ -161,7 +161,7 @@  discard block
 block discarded – undo
161 161
 					],
162 162
 				]
163 163
 			],
164
-			[ # 1- admin part not translated
164
+			[# 1- admin part not translated
165 165
 				'<?xml version="1.0" encoding="utf-8" ?>
166 166
 <release xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance"
167 167
          xsi:noNamespaceSchemaLocation="https://updates.nextcloud.com/changelog_server/schema.xsd"
@@ -212,7 +212,7 @@  discard block
 block discarded – undo
212 212
 					],
213 213
 				]
214 214
 			],
215
-			[ # 2 - minimal set
215
+			[# 2 - minimal set
216 216
 				'<?xml version="1.0" encoding="utf-8" ?>
217 217
 <release xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance"
218 218
          xsi:noNamespaceSchemaLocation="https://updates.nextcloud.com/changelog_server/schema.xsd"
@@ -240,7 +240,7 @@  discard block
 block discarded – undo
240 240
 					],
241 241
 				]
242 242
 			],
243
-			[ # 3 - minimal set (procrastinator edition)
243
+			[# 3 - minimal set (procrastinator edition)
244 244
 				'<?xml version="1.0" encoding="utf-8" ?>
245 245
 <release xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance"
246 246
          xsi:noNamespaceSchemaLocation="https://updates.nextcloud.com/changelog_server/schema.xsd"
@@ -264,7 +264,7 @@  discard block
 block discarded – undo
264 264
 					],
265 265
 				]
266 266
 			],
267
-			[ # 4 - empty
267
+			[# 4 - empty
268 268
 				'',
269 269
 				[]
270 270
 			],
@@ -333,10 +333,10 @@  discard block
 block discarded – undo
333 333
 
334 334
 	public static function changeDataProvider():array {
335 335
 		$testDataFound = $testDataNotFound = self::versionProvider();
336
-		array_walk($testDataFound, static function (&$params) {
336
+		array_walk($testDataFound, static function(&$params) {
337 337
 			$params[] = true;
338 338
 		});
339
-		array_walk($testDataNotFound, static function (&$params) {
339
+		array_walk($testDataNotFound, static function(&$params) {
340 340
 			$params[] = false;
341 341
 		});
342 342
 		return array_merge($testDataFound, $testDataNotFound);
Please login to merge, or discard this patch.
tests/lib/DB/MigrationsTest.php 2 patches
Indentation   +898 added lines, -898 removed lines patch added patch discarded remove patch
@@ -41,902 +41,902 @@
 block discarded – undo
41 41
  * @package Test\DB
42 42
  */
43 43
 class MigrationsTest extends \Test\TestCase {
44
-	private MigrationService|MockObject $migrationService;
45
-	private MockObject|IDBConnection $db;
46
-	private IAppManager $appManager;
47
-
48
-	protected function setUp(): void {
49
-		parent::setUp();
50
-
51
-		$this->db = $this->createMock(Connection::class);
52
-		$this->db->expects($this->any())->method('getPrefix')->willReturn('test_oc_');
53
-		$this->migrationService = new MigrationService('testing', $this->db);
54
-
55
-		$this->appManager = Server::get(IAppManager::class);
56
-	}
57
-
58
-	public function testGetters(): void {
59
-		$this->assertEquals('testing', $this->migrationService->getApp());
60
-		$this->assertEquals(\OC::$SERVERROOT . '/apps/testing/lib/Migration', $this->migrationService->getMigrationsDirectory());
61
-		$this->assertEquals('OCA\Testing\Migration', $this->migrationService->getMigrationsNamespace());
62
-		$this->assertEquals('test_oc_migrations', $this->migrationService->getMigrationsTableName());
63
-	}
64
-
65
-	public function testCore(): void {
66
-		$this->migrationService = new MigrationService('core', $this->db);
67
-
68
-		$this->assertEquals('core', $this->migrationService->getApp());
69
-		$this->assertEquals(\OC::$SERVERROOT . '/core/Migrations', $this->migrationService->getMigrationsDirectory());
70
-		$this->assertEquals('OC\Core\Migrations', $this->migrationService->getMigrationsNamespace());
71
-		$this->assertEquals('test_oc_migrations', $this->migrationService->getMigrationsTableName());
72
-	}
73
-
74
-
75
-	public function testExecuteUnknownStep(): void {
76
-		$this->expectException(\InvalidArgumentException::class);
77
-		$this->expectExceptionMessage('Version 20170130180000 is unknown.');
78
-
79
-		$this->migrationService->executeStep('20170130180000');
80
-	}
81
-
82
-
83
-	public function testUnknownApp(): void {
84
-		$this->expectException(\Exception::class);
85
-		$this->expectExceptionMessage('App not found');
86
-
87
-		$migrationService = new MigrationService('unknown-bloody-app', $this->db);
88
-	}
89
-
90
-
91
-	public function testExecuteStepWithUnknownClass(): void {
92
-		$this->expectException(\Exception::class);
93
-		$this->expectExceptionMessage('Migration step \'X\' is unknown');
94
-
95
-		$this->migrationService = $this->getMockBuilder(MigrationService::class)
96
-			->onlyMethods(['findMigrations'])
97
-			->setConstructorArgs(['testing', $this->db])
98
-			->getMock();
99
-		$this->migrationService->expects($this->any())->method('findMigrations')->willReturn(
100
-			['20170130180000' => 'X', '20170130180001' => 'Y', '20170130180002' => 'Z', '20170130180003' => 'A']
101
-		);
102
-		$this->migrationService->executeStep('20170130180000');
103
-	}
104
-
105
-	public function testExecuteStepWithSchemaChange(): void {
106
-		$schema = $this->createMock(Schema::class);
107
-		$this->db->expects($this->any())
108
-			->method('createSchema')
109
-			->willReturn($schema);
110
-
111
-		$this->db->expects($this->once())
112
-			->method('migrateToSchema');
113
-
114
-		$wrappedSchema = $this->createMock(Schema::class);
115
-		$wrappedSchema->expects($this->exactly(2))
116
-			->method('getTables')
117
-			->willReturn([]);
118
-		$wrappedSchema->expects($this->exactly(2))
119
-			->method('getSequences')
120
-			->willReturn([]);
121
-
122
-		$schemaResult = $this->createMock(SchemaWrapper::class);
123
-		$schemaResult->expects($this->once())
124
-			->method('getWrappedSchema')
125
-			->willReturn($wrappedSchema);
126
-
127
-		$step = $this->createMock(IMigrationStep::class);
128
-		$step->expects($this->once())
129
-			->method('preSchemaChange');
130
-		$step->expects($this->once())
131
-			->method('changeSchema')
132
-			->willReturn($schemaResult);
133
-		$step->expects($this->once())
134
-			->method('postSchemaChange');
135
-
136
-		$this->migrationService = $this->getMockBuilder(MigrationService::class)
137
-			->onlyMethods(['createInstance'])
138
-			->setConstructorArgs(['testing', $this->db])
139
-			->getMock();
140
-
141
-		$this->migrationService->expects($this->any())
142
-			->method('createInstance')
143
-			->with('20170130180000')
144
-			->willReturn($step);
145
-		$this->migrationService->executeStep('20170130180000');
146
-	}
147
-
148
-	public function testExecuteStepWithoutSchemaChange(): void {
149
-		$schema = $this->createMock(Schema::class);
150
-		$this->db->expects($this->any())
151
-			->method('createSchema')
152
-			->willReturn($schema);
153
-
154
-		$this->db->expects($this->never())
155
-			->method('migrateToSchema');
156
-
157
-		$step = $this->createMock(IMigrationStep::class);
158
-		$step->expects($this->once())
159
-			->method('preSchemaChange');
160
-		$step->expects($this->once())
161
-			->method('changeSchema')
162
-			->willReturn(null);
163
-		$step->expects($this->once())
164
-			->method('postSchemaChange');
165
-
166
-		$this->migrationService = $this->getMockBuilder(MigrationService::class)
167
-			->onlyMethods(['createInstance'])
168
-			->setConstructorArgs(['testing', $this->db])
169
-			->getMock();
170
-
171
-		$this->migrationService->expects($this->any())
172
-			->method('createInstance')
173
-			->with('20170130180000')
174
-			->willReturn($step);
175
-		$this->migrationService->executeStep('20170130180000');
176
-	}
177
-
178
-	public function dataGetMigration() {
179
-		return [
180
-			['current', '20170130180001'],
181
-			['prev', '20170130180000'],
182
-			['next', '20170130180002'],
183
-			['latest', '20170130180003'],
184
-		];
185
-	}
186
-
187
-	/**
188
-	 * @dataProvider dataGetMigration
189
-	 * @param string $alias
190
-	 * @param string $expected
191
-	 */
192
-	public function testGetMigration($alias, $expected): void {
193
-		$this->migrationService = $this->getMockBuilder(MigrationService::class)
194
-			->onlyMethods(['getMigratedVersions', 'findMigrations'])
195
-			->setConstructorArgs(['testing', $this->db])
196
-			->getMock();
197
-		$this->migrationService->expects($this->any())->method('getMigratedVersions')->willReturn(
198
-			['20170130180000', '20170130180001']
199
-		);
200
-		$this->migrationService->expects($this->any())->method('findMigrations')->willReturn(
201
-			['20170130180000' => 'X', '20170130180001' => 'Y', '20170130180002' => 'Z', '20170130180003' => 'A']
202
-		);
203
-
204
-		$this->assertEquals(
205
-			['20170130180000', '20170130180001', '20170130180002', '20170130180003'],
206
-			$this->migrationService->getAvailableVersions());
207
-
208
-		$migration = $this->migrationService->getMigration($alias);
209
-		$this->assertEquals($expected, $migration);
210
-	}
211
-
212
-	public function testMigrate(): void {
213
-		$this->migrationService = $this->getMockBuilder(MigrationService::class)
214
-			->onlyMethods(['getMigratedVersions', 'findMigrations', 'executeStep'])
215
-			->setConstructorArgs(['testing', $this->db])
216
-			->getMock();
217
-		$this->migrationService->method('getMigratedVersions')
218
-			->willReturn(
219
-				['20170130180000', '20170130180001']
220
-			);
221
-		$this->migrationService->method('findMigrations')
222
-			->willReturn(
223
-				['20170130180000' => 'X', '20170130180001' => 'Y', '20170130180002' => 'Z', '20170130180003' => 'A']
224
-			);
225
-
226
-		$this->assertEquals(
227
-			['20170130180000', '20170130180001', '20170130180002', '20170130180003'],
228
-			$this->migrationService->getAvailableVersions()
229
-		);
230
-
231
-		$calls = [
232
-			['20170130180002', false],
233
-			['20170130180003', false],
234
-		];
235
-		$this->migrationService->expects($this->exactly(2))
236
-			->method('executeStep')
237
-			->willReturnCallback(function () use (&$calls) {
238
-				$expected = array_shift($calls);
239
-				$this->assertEquals($expected, func_get_args());
240
-			});
241
-		$this->migrationService->migrate();
242
-	}
243
-
244
-	public function testEnsureOracleConstraintsValid(): void {
245
-		$column = $this->createMock(Column::class);
246
-		$column->expects($this->once())
247
-			->method('getName')
248
-			->willReturn(\str_repeat('a', 30));
249
-
250
-		$index = $this->createMock(Index::class);
251
-		$index->expects($this->once())
252
-			->method('getName')
253
-			->willReturn(\str_repeat('a', 30));
254
-
255
-		$foreignKey = $this->createMock(ForeignKeyConstraint::class);
256
-		$foreignKey->expects($this->once())
257
-			->method('getName')
258
-			->willReturn(\str_repeat('a', 30));
259
-
260
-		$table = $this->createMock(Table::class);
261
-		$table->expects($this->atLeastOnce())
262
-			->method('getName')
263
-			->willReturn(\str_repeat('a', 30));
264
-
265
-		$sequence = $this->createMock(Sequence::class);
266
-		$sequence->expects($this->atLeastOnce())
267
-			->method('getName')
268
-			->willReturn(\str_repeat('a', 30));
269
-
270
-		$primaryKey = $this->createMock(Index::class);
271
-		$primaryKey->expects($this->once())
272
-			->method('getName')
273
-			->willReturn(\str_repeat('a', 30));
274
-
275
-		$table->expects($this->once())
276
-			->method('getColumns')
277
-			->willReturn([$column]);
278
-		$table->expects($this->once())
279
-			->method('getIndexes')
280
-			->willReturn([$index]);
281
-		$table->expects($this->once())
282
-			->method('getForeignKeys')
283
-			->willReturn([$foreignKey]);
284
-		$table->expects($this->once())
285
-			->method('getPrimaryKey')
286
-			->willReturn($primaryKey);
287
-
288
-		$schema = $this->createMock(Schema::class);
289
-		$schema->expects($this->once())
290
-			->method('getTables')
291
-			->willReturn([$table]);
292
-		$schema->expects($this->once())
293
-			->method('getSequences')
294
-			->willReturn([$sequence]);
295
-
296
-		$sourceSchema = $this->createMock(Schema::class);
297
-		$sourceSchema->expects($this->any())
298
-			->method('getTable')
299
-			->willThrowException(new SchemaException());
300
-		$sourceSchema->expects($this->any())
301
-			->method('hasSequence')
302
-			->willReturn(false);
303
-
304
-		self::invokePrivate($this->migrationService, 'ensureOracleConstraints', [$sourceSchema, $schema, 3]);
305
-	}
306
-
307
-	public function testEnsureOracleConstraintsValidWithPrimaryKey(): void {
308
-		$index = $this->createMock(Index::class);
309
-		$index->expects($this->any())
310
-			->method('getName')
311
-			->willReturn(\str_repeat('a', 30));
312
-
313
-		$table = $this->createMock(Table::class);
314
-		$table->expects($this->any())
315
-			->method('getName')
316
-			->willReturn(\str_repeat('a', 26));
317
-
318
-		$table->expects($this->once())
319
-			->method('getColumns')
320
-			->willReturn([]);
321
-		$table->expects($this->once())
322
-			->method('getIndexes')
323
-			->willReturn([]);
324
-		$table->expects($this->once())
325
-			->method('getForeignKeys')
326
-			->willReturn([]);
327
-		$table->expects($this->once())
328
-			->method('getPrimaryKey')
329
-			->willReturn($index);
330
-
331
-		$schema = $this->createMock(Schema::class);
332
-		$schema->expects($this->once())
333
-			->method('getTables')
334
-			->willReturn([$table]);
335
-		$schema->expects($this->once())
336
-			->method('getSequences')
337
-			->willReturn([]);
338
-
339
-		$sourceSchema = $this->createMock(Schema::class);
340
-		$sourceSchema->expects($this->any())
341
-			->method('getTable')
342
-			->willThrowException(new SchemaException());
343
-		$sourceSchema->expects($this->any())
344
-			->method('hasSequence')
345
-			->willReturn(false);
346
-
347
-		self::invokePrivate($this->migrationService, 'ensureOracleConstraints', [$sourceSchema, $schema, 3]);
348
-	}
349
-
350
-	public function testEnsureOracleConstraintsValidWithPrimaryKeyDefault(): void {
351
-		$defaultName = 'PRIMARY';
352
-		if ($this->db->getDatabaseProvider() === IDBConnection::PLATFORM_POSTGRES) {
353
-			$defaultName = \str_repeat('a', 26) . '_' . \str_repeat('b', 30) . '_seq';
354
-		} elseif ($this->db->getDatabaseProvider() === IDBConnection::PLATFORM_ORACLE) {
355
-			$defaultName = \str_repeat('a', 26) . '_seq';
356
-		}
357
-
358
-		$index = $this->createMock(Index::class);
359
-		$index->expects($this->any())
360
-			->method('getName')
361
-			->willReturn($defaultName);
362
-		$index->expects($this->any())
363
-			->method('getColumns')
364
-			->willReturn([\str_repeat('b', 30)]);
365
-
366
-		$table = $this->createMock(Table::class);
367
-		$table->expects($this->any())
368
-			->method('getName')
369
-			->willReturn(\str_repeat('a', 25));
370
-
371
-		$table->expects($this->once())
372
-			->method('getColumns')
373
-			->willReturn([]);
374
-		$table->expects($this->once())
375
-			->method('getIndexes')
376
-			->willReturn([]);
377
-		$table->expects($this->once())
378
-			->method('getForeignKeys')
379
-			->willReturn([]);
380
-		$table->expects($this->once())
381
-			->method('getPrimaryKey')
382
-			->willReturn($index);
383
-
384
-		$schema = $this->createMock(Schema::class);
385
-		$schema->expects($this->once())
386
-			->method('getTables')
387
-			->willReturn([$table]);
388
-		$schema->expects($this->once())
389
-			->method('getSequences')
390
-			->willReturn([]);
391
-
392
-		$sourceSchema = $this->createMock(Schema::class);
393
-		$sourceSchema->expects($this->any())
394
-			->method('getTable')
395
-			->willThrowException(new SchemaException());
396
-		$sourceSchema->expects($this->any())
397
-			->method('hasSequence')
398
-			->willReturn(false);
399
-
400
-		self::invokePrivate($this->migrationService, 'ensureOracleConstraints', [$sourceSchema, $schema, 3]);
401
-	}
402
-
403
-
404
-	public function testEnsureOracleConstraintsTooLongTableName(): void {
405
-		$this->expectException(\InvalidArgumentException::class);
406
-
407
-		$table = $this->createMock(Table::class);
408
-		$table->expects($this->any())
409
-			->method('getName')
410
-			->willReturn(\str_repeat('a', 31));
411
-
412
-		$schema = $this->createMock(Schema::class);
413
-		$schema->expects($this->once())
414
-			->method('getTables')
415
-			->willReturn([$table]);
416
-
417
-		$sourceSchema = $this->createMock(Schema::class);
418
-		$sourceSchema->expects($this->any())
419
-			->method('getTable')
420
-			->willThrowException(new SchemaException());
421
-		$sourceSchema->expects($this->any())
422
-			->method('hasSequence')
423
-			->willReturn(false);
424
-
425
-		self::invokePrivate($this->migrationService, 'ensureOracleConstraints', [$sourceSchema, $schema, 3]);
426
-	}
427
-
428
-
429
-	public function testEnsureOracleConstraintsTooLongPrimaryWithDefault(): void {
430
-		$this->expectException(\InvalidArgumentException::class);
431
-
432
-		$defaultName = 'PRIMARY';
433
-		if ($this->db->getDatabaseProvider() === IDBConnection::PLATFORM_POSTGRES) {
434
-			$defaultName = \str_repeat('a', 27) . '_' . \str_repeat('b', 30) . '_seq';
435
-		} elseif ($this->db->getDatabaseProvider() === IDBConnection::PLATFORM_ORACLE) {
436
-			$defaultName = \str_repeat('a', 27) . '_seq';
437
-		}
438
-
439
-		$index = $this->createMock(Index::class);
440
-		$index->expects($this->any())
441
-			->method('getName')
442
-			->willReturn($defaultName);
443
-		$index->expects($this->any())
444
-			->method('getColumns')
445
-			->willReturn([\str_repeat('b', 30)]);
446
-
447
-		$table = $this->createMock(Table::class);
448
-		$table->expects($this->any())
449
-			->method('getName')
450
-			->willReturn(\str_repeat('a', 27));
451
-
452
-		$table->expects($this->once())
453
-			->method('getColumns')
454
-			->willReturn([]);
455
-		$table->expects($this->once())
456
-			->method('getIndexes')
457
-			->willReturn([]);
458
-		$table->expects($this->once())
459
-			->method('getForeignKeys')
460
-			->willReturn([]);
461
-		$table->expects($this->once())
462
-			->method('getPrimaryKey')
463
-			->willReturn($index);
464
-
465
-		$schema = $this->createMock(Schema::class);
466
-		$schema->expects($this->once())
467
-			->method('getTables')
468
-			->willReturn([$table]);
469
-
470
-		$sourceSchema = $this->createMock(Schema::class);
471
-		$sourceSchema->expects($this->any())
472
-			->method('getTable')
473
-			->willThrowException(new SchemaException());
474
-		$sourceSchema->expects($this->any())
475
-			->method('hasSequence')
476
-			->willReturn(false);
477
-
478
-		self::invokePrivate($this->migrationService, 'ensureOracleConstraints', [$sourceSchema, $schema, 3]);
479
-	}
480
-
481
-
482
-	public function testEnsureOracleConstraintsTooLongPrimaryWithName(): void {
483
-		$this->expectException(\InvalidArgumentException::class);
484
-
485
-		$index = $this->createMock(Index::class);
486
-		$index->expects($this->any())
487
-			->method('getName')
488
-			->willReturn(\str_repeat('a', 31));
489
-
490
-		$table = $this->createMock(Table::class);
491
-		$table->expects($this->any())
492
-			->method('getName')
493
-			->willReturn(\str_repeat('a', 26));
494
-
495
-		$table->expects($this->once())
496
-			->method('getColumns')
497
-			->willReturn([]);
498
-		$table->expects($this->once())
499
-			->method('getIndexes')
500
-			->willReturn([]);
501
-		$table->expects($this->once())
502
-			->method('getForeignKeys')
503
-			->willReturn([]);
504
-		$table->expects($this->once())
505
-			->method('getPrimaryKey')
506
-			->willReturn($index);
507
-
508
-		$schema = $this->createMock(Schema::class);
509
-		$schema->expects($this->once())
510
-			->method('getTables')
511
-			->willReturn([$table]);
512
-
513
-		$sourceSchema = $this->createMock(Schema::class);
514
-		$sourceSchema->expects($this->any())
515
-			->method('getTable')
516
-			->willThrowException(new SchemaException());
517
-		$sourceSchema->expects($this->any())
518
-			->method('hasSequence')
519
-			->willReturn(false);
520
-
521
-		self::invokePrivate($this->migrationService, 'ensureOracleConstraints', [$sourceSchema, $schema, 3]);
522
-	}
523
-
524
-
525
-	public function testEnsureOracleConstraintsTooLongColumnName(): void {
526
-		$this->expectException(\InvalidArgumentException::class);
527
-
528
-		$column = $this->createMock(Column::class);
529
-		$column->expects($this->any())
530
-			->method('getName')
531
-			->willReturn(\str_repeat('a', 31));
532
-
533
-		$table = $this->createMock(Table::class);
534
-		$table->expects($this->any())
535
-			->method('getName')
536
-			->willReturn(\str_repeat('a', 30));
537
-
538
-		$table->expects($this->once())
539
-			->method('getColumns')
540
-			->willReturn([$column]);
541
-
542
-		$schema = $this->createMock(Schema::class);
543
-		$schema->expects($this->once())
544
-			->method('getTables')
545
-			->willReturn([$table]);
546
-
547
-		$sourceSchema = $this->createMock(Schema::class);
548
-		$sourceSchema->expects($this->any())
549
-			->method('getTable')
550
-			->willThrowException(new SchemaException());
551
-		$sourceSchema->expects($this->any())
552
-			->method('hasSequence')
553
-			->willReturn(false);
554
-
555
-		self::invokePrivate($this->migrationService, 'ensureOracleConstraints', [$sourceSchema, $schema, 3]);
556
-	}
557
-
558
-
559
-	public function testEnsureOracleConstraintsTooLongIndexName(): void {
560
-		$this->expectException(\InvalidArgumentException::class);
561
-
562
-		$index = $this->createMock(Index::class);
563
-		$index->expects($this->any())
564
-			->method('getName')
565
-			->willReturn(\str_repeat('a', 31));
566
-
567
-		$table = $this->createMock(Table::class);
568
-		$table->expects($this->any())
569
-			->method('getName')
570
-			->willReturn(\str_repeat('a', 30));
571
-
572
-		$table->expects($this->once())
573
-			->method('getColumns')
574
-			->willReturn([]);
575
-		$table->expects($this->once())
576
-			->method('getIndexes')
577
-			->willReturn([$index]);
578
-
579
-		$schema = $this->createMock(Schema::class);
580
-		$schema->expects($this->once())
581
-			->method('getTables')
582
-			->willReturn([$table]);
583
-
584
-		$sourceSchema = $this->createMock(Schema::class);
585
-		$sourceSchema->expects($this->any())
586
-			->method('getTable')
587
-			->willThrowException(new SchemaException());
588
-		$sourceSchema->expects($this->any())
589
-			->method('hasSequence')
590
-			->willReturn(false);
591
-
592
-		self::invokePrivate($this->migrationService, 'ensureOracleConstraints', [$sourceSchema, $schema, 3]);
593
-	}
594
-
595
-
596
-	public function testEnsureOracleConstraintsTooLongForeignKeyName(): void {
597
-		$this->expectException(\InvalidArgumentException::class);
598
-
599
-		$foreignKey = $this->createMock(ForeignKeyConstraint::class);
600
-		$foreignKey->expects($this->any())
601
-			->method('getName')
602
-			->willReturn(\str_repeat('a', 31));
603
-
604
-		$table = $this->createMock(Table::class);
605
-		$table->expects($this->any())
606
-			->method('getName')
607
-			->willReturn(\str_repeat('a', 30));
608
-
609
-		$table->expects($this->once())
610
-			->method('getColumns')
611
-			->willReturn([]);
612
-		$table->expects($this->once())
613
-			->method('getIndexes')
614
-			->willReturn([]);
615
-		$table->expects($this->once())
616
-			->method('getForeignKeys')
617
-			->willReturn([$foreignKey]);
618
-
619
-		$schema = $this->createMock(Schema::class);
620
-		$schema->expects($this->once())
621
-			->method('getTables')
622
-			->willReturn([$table]);
623
-
624
-		$sourceSchema = $this->createMock(Schema::class);
625
-		$sourceSchema->expects($this->any())
626
-			->method('getTable')
627
-			->willThrowException(new SchemaException());
628
-		$sourceSchema->expects($this->any())
629
-			->method('hasSequence')
630
-			->willReturn(false);
631
-
632
-		self::invokePrivate($this->migrationService, 'ensureOracleConstraints', [$sourceSchema, $schema, 3]);
633
-	}
634
-
635
-
636
-	public function testEnsureOracleConstraintsNoPrimaryKey(): void {
637
-		$this->markTestSkipped('Test disabled for now due to multiple reasons, see https://github.com/nextcloud/server/pull/31580#issuecomment-1069182234 for details.');
638
-		$this->expectException(\InvalidArgumentException::class);
639
-
640
-		$table = $this->createMock(Table::class);
641
-		$table->expects($this->atLeastOnce())
642
-			->method('getName')
643
-			->willReturn(\str_repeat('a', 30));
644
-		$table->expects($this->once())
645
-			->method('getColumns')
646
-			->willReturn([]);
647
-		$table->expects($this->once())
648
-			->method('getIndexes')
649
-			->willReturn([]);
650
-		$table->expects($this->once())
651
-			->method('getForeignKeys')
652
-			->willReturn([]);
653
-		$table->expects($this->once())
654
-			->method('getPrimaryKey')
655
-			->willReturn(null);
656
-
657
-		$schema = $this->createMock(Schema::class);
658
-		$schema->expects($this->once())
659
-			->method('getTables')
660
-			->willReturn([$table]);
661
-		$schema->expects($this->once())
662
-			->method('getSequences')
663
-			->willReturn([]);
664
-
665
-		$sourceSchema = $this->createMock(Schema::class);
666
-		$sourceSchema->expects($this->any())
667
-			->method('getTable')
668
-			->willThrowException(new SchemaException());
669
-		$sourceSchema->expects($this->any())
670
-			->method('hasSequence')
671
-			->willReturn(false);
672
-
673
-		self::invokePrivate($this->migrationService, 'ensureOracleConstraints', [$sourceSchema, $schema, 3]);
674
-	}
675
-
676
-
677
-	public function testEnsureOracleConstraintsTooLongSequenceName(): void {
678
-		$this->expectException(\InvalidArgumentException::class);
679
-
680
-		$sequence = $this->createMock(Sequence::class);
681
-		$sequence->expects($this->any())
682
-			->method('getName')
683
-			->willReturn(\str_repeat('a', 31));
684
-
685
-		$schema = $this->createMock(Schema::class);
686
-		$schema->expects($this->once())
687
-			->method('getTables')
688
-			->willReturn([]);
689
-		$schema->expects($this->once())
690
-			->method('getSequences')
691
-			->willReturn([$sequence]);
692
-
693
-		$sourceSchema = $this->createMock(Schema::class);
694
-		$sourceSchema->expects($this->any())
695
-			->method('getTable')
696
-			->willThrowException(new SchemaException());
697
-		$sourceSchema->expects($this->any())
698
-			->method('hasSequence')
699
-			->willReturn(false);
700
-
701
-		self::invokePrivate($this->migrationService, 'ensureOracleConstraints', [$sourceSchema, $schema, 3]);
702
-	}
703
-
704
-
705
-	public function testEnsureOracleConstraintsBooleanNotNull(): void {
706
-		$this->expectException(\InvalidArgumentException::class);
707
-
708
-		$column = $this->createMock(Column::class);
709
-		$column->expects($this->any())
710
-			->method('getName')
711
-			->willReturn('aaaa');
712
-		$column->expects($this->any())
713
-			->method('getType')
714
-			->willReturn(Type::getType('boolean'));
715
-		$column->expects($this->any())
716
-			->method('getNotnull')
717
-			->willReturn(true);
718
-
719
-		$table = $this->createMock(Table::class);
720
-		$table->expects($this->any())
721
-			->method('getName')
722
-			->willReturn(\str_repeat('a', 30));
723
-
724
-		$table->expects($this->once())
725
-			->method('getColumns')
726
-			->willReturn([$column]);
727
-
728
-		$schema = $this->createMock(Schema::class);
729
-		$schema->expects($this->once())
730
-			->method('getTables')
731
-			->willReturn([$table]);
732
-
733
-		$sourceSchema = $this->createMock(Schema::class);
734
-		$sourceSchema->expects($this->any())
735
-			->method('getTable')
736
-			->willThrowException(new SchemaException());
737
-		$sourceSchema->expects($this->any())
738
-			->method('hasSequence')
739
-			->willReturn(false);
740
-
741
-		self::invokePrivate($this->migrationService, 'ensureOracleConstraints', [$sourceSchema, $schema, 3]);
742
-	}
743
-
744
-
745
-	public function testEnsureOracleConstraintsStringLength4000(): void {
746
-		$this->expectException(\InvalidArgumentException::class);
747
-
748
-		$column = $this->createMock(Column::class);
749
-		$column->expects($this->any())
750
-			->method('getName')
751
-			->willReturn('aaaa');
752
-		$column->expects($this->any())
753
-			->method('getType')
754
-			->willReturn(Type::getType('string'));
755
-		$column->expects($this->any())
756
-			->method('getLength')
757
-			->willReturn(4001);
758
-
759
-		$table = $this->createMock(Table::class);
760
-		$table->expects($this->any())
761
-			->method('getName')
762
-			->willReturn(\str_repeat('a', 30));
763
-
764
-		$table->expects($this->once())
765
-			->method('getColumns')
766
-			->willReturn([$column]);
767
-
768
-		$schema = $this->createMock(Schema::class);
769
-		$schema->expects($this->once())
770
-			->method('getTables')
771
-			->willReturn([$table]);
772
-
773
-		$sourceSchema = $this->createMock(Schema::class);
774
-		$sourceSchema->expects($this->any())
775
-			->method('getTable')
776
-			->willThrowException(new SchemaException());
777
-		$sourceSchema->expects($this->any())
778
-			->method('hasSequence')
779
-			->willReturn(false);
780
-
781
-		self::invokePrivate($this->migrationService, 'ensureOracleConstraints', [$sourceSchema, $schema, 3]);
782
-	}
783
-
784
-
785
-	public function testExtractMigrationAttributes(): void {
786
-		$metadataManager = Server::get(MetadataManager::class);
787
-		$this->appManager->loadApp('testing');
788
-
789
-		$this->assertEquals($this->getMigrationMetadata(), json_decode(json_encode($metadataManager->extractMigrationAttributes('testing')), true));
790
-
791
-		$this->appManager->disableApp('testing');
792
-	}
793
-
794
-	public function testDeserializeMigrationMetadata(): void {
795
-		$metadataManager = Server::get(MetadataManager::class);
796
-		$this->assertEquals(
797
-			[
798
-				'core' => [],
799
-				'apps' => [
800
-					'testing' => [
801
-						'30000Date20240102030405' => [
802
-							new DropTable('old_table'),
803
-							new CreateTable('new_table',
804
-								description: 'Table is used to store things, but also to get more things',
805
-								notes:       ['this is a notice', 'and another one, if really needed']
806
-							),
807
-							new AddColumn('my_table'),
808
-							new AddColumn('my_table', 'another_field'),
809
-							new AddColumn('other_table', 'last_one', ColumnType::DATE),
810
-							new AddIndex('my_table'),
811
-							new AddIndex('my_table', IndexType::PRIMARY),
812
-							new DropColumn('other_table'),
813
-							new DropColumn('other_table', 'old_column',
814
-								description: 'field is not used anymore and replaced by \'last_one\''
815
-							),
816
-							new DropIndex('other_table'),
817
-							new ModifyColumn('other_table'),
818
-							new ModifyColumn('other_table', 'this_field'),
819
-							new ModifyColumn('other_table', 'this_field', ColumnType::BIGINT)
820
-						]
821
-					]
822
-				]
823
-			],
824
-			$metadataManager->getMigrationsAttributesFromReleaseMetadata(
825
-				[
826
-					'core' => [],
827
-					'apps' => ['testing' => $this->getMigrationMetadata()]
828
-				]
829
-			)
830
-		);
831
-	}
832
-
833
-	private function getMigrationMetadata(): array {
834
-		return [
835
-			'30000Date20240102030405' => [
836
-				[
837
-					'class' => 'OCP\\Migration\\Attributes\\DropTable',
838
-					'table' => 'old_table',
839
-					'description' => '',
840
-					'notes' => [],
841
-					'columns' => []
842
-				],
843
-				[
844
-					'class' => 'OCP\\Migration\\Attributes\\CreateTable',
845
-					'table' => 'new_table',
846
-					'description' => 'Table is used to store things, but also to get more things',
847
-					'notes' =>
848
-						[
849
-							'this is a notice',
850
-							'and another one, if really needed'
851
-						],
852
-					'columns' => []
853
-				],
854
-				[
855
-					'class' => 'OCP\\Migration\\Attributes\\AddColumn',
856
-					'table' => 'my_table',
857
-					'description' => '',
858
-					'notes' => [],
859
-					'name' => '',
860
-					'type' => ''
861
-				],
862
-				[
863
-					'class' => 'OCP\\Migration\\Attributes\\AddColumn',
864
-					'table' => 'my_table',
865
-					'description' => '',
866
-					'notes' => [],
867
-					'name' => 'another_field',
868
-					'type' => ''
869
-				],
870
-				[
871
-					'class' => 'OCP\\Migration\\Attributes\\AddColumn',
872
-					'table' => 'other_table',
873
-					'description' => '',
874
-					'notes' => [],
875
-					'name' => 'last_one',
876
-					'type' => 'date'
877
-				],
878
-				[
879
-					'class' => 'OCP\\Migration\\Attributes\\AddIndex',
880
-					'table' => 'my_table',
881
-					'description' => '',
882
-					'notes' => [],
883
-					'type' => ''
884
-				],
885
-				[
886
-					'class' => 'OCP\\Migration\\Attributes\\AddIndex',
887
-					'table' => 'my_table',
888
-					'description' => '',
889
-					'notes' => [],
890
-					'type' => 'primary'
891
-				],
892
-				[
893
-					'class' => 'OCP\\Migration\\Attributes\\DropColumn',
894
-					'table' => 'other_table',
895
-					'description' => '',
896
-					'notes' => [],
897
-					'name' => '',
898
-					'type' => ''
899
-				],
900
-				[
901
-					'class' => 'OCP\\Migration\\Attributes\\DropColumn',
902
-					'table' => 'other_table',
903
-					'description' => 'field is not used anymore and replaced by \'last_one\'',
904
-					'notes' => [],
905
-					'name' => 'old_column',
906
-					'type' => ''
907
-				],
908
-				[
909
-					'class' => 'OCP\\Migration\\Attributes\\DropIndex',
910
-					'table' => 'other_table',
911
-					'description' => '',
912
-					'notes' => [],
913
-					'type' => ''
914
-				],
915
-				[
916
-					'class' => 'OCP\\Migration\\Attributes\\ModifyColumn',
917
-					'table' => 'other_table',
918
-					'description' => '',
919
-					'notes' => [],
920
-					'name' => '',
921
-					'type' => ''
922
-				],
923
-				[
924
-					'class' => 'OCP\\Migration\\Attributes\\ModifyColumn',
925
-					'table' => 'other_table',
926
-					'description' => '',
927
-					'notes' => [],
928
-					'name' => 'this_field',
929
-					'type' => ''
930
-				],
931
-				[
932
-					'class' => 'OCP\\Migration\\Attributes\\ModifyColumn',
933
-					'table' => 'other_table',
934
-					'description' => '',
935
-					'notes' => [],
936
-					'name' => 'this_field',
937
-					'type' => 'bigint'
938
-				],
939
-			]
940
-		];
941
-	}
44
+    private MigrationService|MockObject $migrationService;
45
+    private MockObject|IDBConnection $db;
46
+    private IAppManager $appManager;
47
+
48
+    protected function setUp(): void {
49
+        parent::setUp();
50
+
51
+        $this->db = $this->createMock(Connection::class);
52
+        $this->db->expects($this->any())->method('getPrefix')->willReturn('test_oc_');
53
+        $this->migrationService = new MigrationService('testing', $this->db);
54
+
55
+        $this->appManager = Server::get(IAppManager::class);
56
+    }
57
+
58
+    public function testGetters(): void {
59
+        $this->assertEquals('testing', $this->migrationService->getApp());
60
+        $this->assertEquals(\OC::$SERVERROOT . '/apps/testing/lib/Migration', $this->migrationService->getMigrationsDirectory());
61
+        $this->assertEquals('OCA\Testing\Migration', $this->migrationService->getMigrationsNamespace());
62
+        $this->assertEquals('test_oc_migrations', $this->migrationService->getMigrationsTableName());
63
+    }
64
+
65
+    public function testCore(): void {
66
+        $this->migrationService = new MigrationService('core', $this->db);
67
+
68
+        $this->assertEquals('core', $this->migrationService->getApp());
69
+        $this->assertEquals(\OC::$SERVERROOT . '/core/Migrations', $this->migrationService->getMigrationsDirectory());
70
+        $this->assertEquals('OC\Core\Migrations', $this->migrationService->getMigrationsNamespace());
71
+        $this->assertEquals('test_oc_migrations', $this->migrationService->getMigrationsTableName());
72
+    }
73
+
74
+
75
+    public function testExecuteUnknownStep(): void {
76
+        $this->expectException(\InvalidArgumentException::class);
77
+        $this->expectExceptionMessage('Version 20170130180000 is unknown.');
78
+
79
+        $this->migrationService->executeStep('20170130180000');
80
+    }
81
+
82
+
83
+    public function testUnknownApp(): void {
84
+        $this->expectException(\Exception::class);
85
+        $this->expectExceptionMessage('App not found');
86
+
87
+        $migrationService = new MigrationService('unknown-bloody-app', $this->db);
88
+    }
89
+
90
+
91
+    public function testExecuteStepWithUnknownClass(): void {
92
+        $this->expectException(\Exception::class);
93
+        $this->expectExceptionMessage('Migration step \'X\' is unknown');
94
+
95
+        $this->migrationService = $this->getMockBuilder(MigrationService::class)
96
+            ->onlyMethods(['findMigrations'])
97
+            ->setConstructorArgs(['testing', $this->db])
98
+            ->getMock();
99
+        $this->migrationService->expects($this->any())->method('findMigrations')->willReturn(
100
+            ['20170130180000' => 'X', '20170130180001' => 'Y', '20170130180002' => 'Z', '20170130180003' => 'A']
101
+        );
102
+        $this->migrationService->executeStep('20170130180000');
103
+    }
104
+
105
+    public function testExecuteStepWithSchemaChange(): void {
106
+        $schema = $this->createMock(Schema::class);
107
+        $this->db->expects($this->any())
108
+            ->method('createSchema')
109
+            ->willReturn($schema);
110
+
111
+        $this->db->expects($this->once())
112
+            ->method('migrateToSchema');
113
+
114
+        $wrappedSchema = $this->createMock(Schema::class);
115
+        $wrappedSchema->expects($this->exactly(2))
116
+            ->method('getTables')
117
+            ->willReturn([]);
118
+        $wrappedSchema->expects($this->exactly(2))
119
+            ->method('getSequences')
120
+            ->willReturn([]);
121
+
122
+        $schemaResult = $this->createMock(SchemaWrapper::class);
123
+        $schemaResult->expects($this->once())
124
+            ->method('getWrappedSchema')
125
+            ->willReturn($wrappedSchema);
126
+
127
+        $step = $this->createMock(IMigrationStep::class);
128
+        $step->expects($this->once())
129
+            ->method('preSchemaChange');
130
+        $step->expects($this->once())
131
+            ->method('changeSchema')
132
+            ->willReturn($schemaResult);
133
+        $step->expects($this->once())
134
+            ->method('postSchemaChange');
135
+
136
+        $this->migrationService = $this->getMockBuilder(MigrationService::class)
137
+            ->onlyMethods(['createInstance'])
138
+            ->setConstructorArgs(['testing', $this->db])
139
+            ->getMock();
140
+
141
+        $this->migrationService->expects($this->any())
142
+            ->method('createInstance')
143
+            ->with('20170130180000')
144
+            ->willReturn($step);
145
+        $this->migrationService->executeStep('20170130180000');
146
+    }
147
+
148
+    public function testExecuteStepWithoutSchemaChange(): void {
149
+        $schema = $this->createMock(Schema::class);
150
+        $this->db->expects($this->any())
151
+            ->method('createSchema')
152
+            ->willReturn($schema);
153
+
154
+        $this->db->expects($this->never())
155
+            ->method('migrateToSchema');
156
+
157
+        $step = $this->createMock(IMigrationStep::class);
158
+        $step->expects($this->once())
159
+            ->method('preSchemaChange');
160
+        $step->expects($this->once())
161
+            ->method('changeSchema')
162
+            ->willReturn(null);
163
+        $step->expects($this->once())
164
+            ->method('postSchemaChange');
165
+
166
+        $this->migrationService = $this->getMockBuilder(MigrationService::class)
167
+            ->onlyMethods(['createInstance'])
168
+            ->setConstructorArgs(['testing', $this->db])
169
+            ->getMock();
170
+
171
+        $this->migrationService->expects($this->any())
172
+            ->method('createInstance')
173
+            ->with('20170130180000')
174
+            ->willReturn($step);
175
+        $this->migrationService->executeStep('20170130180000');
176
+    }
177
+
178
+    public function dataGetMigration() {
179
+        return [
180
+            ['current', '20170130180001'],
181
+            ['prev', '20170130180000'],
182
+            ['next', '20170130180002'],
183
+            ['latest', '20170130180003'],
184
+        ];
185
+    }
186
+
187
+    /**
188
+     * @dataProvider dataGetMigration
189
+     * @param string $alias
190
+     * @param string $expected
191
+     */
192
+    public function testGetMigration($alias, $expected): void {
193
+        $this->migrationService = $this->getMockBuilder(MigrationService::class)
194
+            ->onlyMethods(['getMigratedVersions', 'findMigrations'])
195
+            ->setConstructorArgs(['testing', $this->db])
196
+            ->getMock();
197
+        $this->migrationService->expects($this->any())->method('getMigratedVersions')->willReturn(
198
+            ['20170130180000', '20170130180001']
199
+        );
200
+        $this->migrationService->expects($this->any())->method('findMigrations')->willReturn(
201
+            ['20170130180000' => 'X', '20170130180001' => 'Y', '20170130180002' => 'Z', '20170130180003' => 'A']
202
+        );
203
+
204
+        $this->assertEquals(
205
+            ['20170130180000', '20170130180001', '20170130180002', '20170130180003'],
206
+            $this->migrationService->getAvailableVersions());
207
+
208
+        $migration = $this->migrationService->getMigration($alias);
209
+        $this->assertEquals($expected, $migration);
210
+    }
211
+
212
+    public function testMigrate(): void {
213
+        $this->migrationService = $this->getMockBuilder(MigrationService::class)
214
+            ->onlyMethods(['getMigratedVersions', 'findMigrations', 'executeStep'])
215
+            ->setConstructorArgs(['testing', $this->db])
216
+            ->getMock();
217
+        $this->migrationService->method('getMigratedVersions')
218
+            ->willReturn(
219
+                ['20170130180000', '20170130180001']
220
+            );
221
+        $this->migrationService->method('findMigrations')
222
+            ->willReturn(
223
+                ['20170130180000' => 'X', '20170130180001' => 'Y', '20170130180002' => 'Z', '20170130180003' => 'A']
224
+            );
225
+
226
+        $this->assertEquals(
227
+            ['20170130180000', '20170130180001', '20170130180002', '20170130180003'],
228
+            $this->migrationService->getAvailableVersions()
229
+        );
230
+
231
+        $calls = [
232
+            ['20170130180002', false],
233
+            ['20170130180003', false],
234
+        ];
235
+        $this->migrationService->expects($this->exactly(2))
236
+            ->method('executeStep')
237
+            ->willReturnCallback(function () use (&$calls) {
238
+                $expected = array_shift($calls);
239
+                $this->assertEquals($expected, func_get_args());
240
+            });
241
+        $this->migrationService->migrate();
242
+    }
243
+
244
+    public function testEnsureOracleConstraintsValid(): void {
245
+        $column = $this->createMock(Column::class);
246
+        $column->expects($this->once())
247
+            ->method('getName')
248
+            ->willReturn(\str_repeat('a', 30));
249
+
250
+        $index = $this->createMock(Index::class);
251
+        $index->expects($this->once())
252
+            ->method('getName')
253
+            ->willReturn(\str_repeat('a', 30));
254
+
255
+        $foreignKey = $this->createMock(ForeignKeyConstraint::class);
256
+        $foreignKey->expects($this->once())
257
+            ->method('getName')
258
+            ->willReturn(\str_repeat('a', 30));
259
+
260
+        $table = $this->createMock(Table::class);
261
+        $table->expects($this->atLeastOnce())
262
+            ->method('getName')
263
+            ->willReturn(\str_repeat('a', 30));
264
+
265
+        $sequence = $this->createMock(Sequence::class);
266
+        $sequence->expects($this->atLeastOnce())
267
+            ->method('getName')
268
+            ->willReturn(\str_repeat('a', 30));
269
+
270
+        $primaryKey = $this->createMock(Index::class);
271
+        $primaryKey->expects($this->once())
272
+            ->method('getName')
273
+            ->willReturn(\str_repeat('a', 30));
274
+
275
+        $table->expects($this->once())
276
+            ->method('getColumns')
277
+            ->willReturn([$column]);
278
+        $table->expects($this->once())
279
+            ->method('getIndexes')
280
+            ->willReturn([$index]);
281
+        $table->expects($this->once())
282
+            ->method('getForeignKeys')
283
+            ->willReturn([$foreignKey]);
284
+        $table->expects($this->once())
285
+            ->method('getPrimaryKey')
286
+            ->willReturn($primaryKey);
287
+
288
+        $schema = $this->createMock(Schema::class);
289
+        $schema->expects($this->once())
290
+            ->method('getTables')
291
+            ->willReturn([$table]);
292
+        $schema->expects($this->once())
293
+            ->method('getSequences')
294
+            ->willReturn([$sequence]);
295
+
296
+        $sourceSchema = $this->createMock(Schema::class);
297
+        $sourceSchema->expects($this->any())
298
+            ->method('getTable')
299
+            ->willThrowException(new SchemaException());
300
+        $sourceSchema->expects($this->any())
301
+            ->method('hasSequence')
302
+            ->willReturn(false);
303
+
304
+        self::invokePrivate($this->migrationService, 'ensureOracleConstraints', [$sourceSchema, $schema, 3]);
305
+    }
306
+
307
+    public function testEnsureOracleConstraintsValidWithPrimaryKey(): void {
308
+        $index = $this->createMock(Index::class);
309
+        $index->expects($this->any())
310
+            ->method('getName')
311
+            ->willReturn(\str_repeat('a', 30));
312
+
313
+        $table = $this->createMock(Table::class);
314
+        $table->expects($this->any())
315
+            ->method('getName')
316
+            ->willReturn(\str_repeat('a', 26));
317
+
318
+        $table->expects($this->once())
319
+            ->method('getColumns')
320
+            ->willReturn([]);
321
+        $table->expects($this->once())
322
+            ->method('getIndexes')
323
+            ->willReturn([]);
324
+        $table->expects($this->once())
325
+            ->method('getForeignKeys')
326
+            ->willReturn([]);
327
+        $table->expects($this->once())
328
+            ->method('getPrimaryKey')
329
+            ->willReturn($index);
330
+
331
+        $schema = $this->createMock(Schema::class);
332
+        $schema->expects($this->once())
333
+            ->method('getTables')
334
+            ->willReturn([$table]);
335
+        $schema->expects($this->once())
336
+            ->method('getSequences')
337
+            ->willReturn([]);
338
+
339
+        $sourceSchema = $this->createMock(Schema::class);
340
+        $sourceSchema->expects($this->any())
341
+            ->method('getTable')
342
+            ->willThrowException(new SchemaException());
343
+        $sourceSchema->expects($this->any())
344
+            ->method('hasSequence')
345
+            ->willReturn(false);
346
+
347
+        self::invokePrivate($this->migrationService, 'ensureOracleConstraints', [$sourceSchema, $schema, 3]);
348
+    }
349
+
350
+    public function testEnsureOracleConstraintsValidWithPrimaryKeyDefault(): void {
351
+        $defaultName = 'PRIMARY';
352
+        if ($this->db->getDatabaseProvider() === IDBConnection::PLATFORM_POSTGRES) {
353
+            $defaultName = \str_repeat('a', 26) . '_' . \str_repeat('b', 30) . '_seq';
354
+        } elseif ($this->db->getDatabaseProvider() === IDBConnection::PLATFORM_ORACLE) {
355
+            $defaultName = \str_repeat('a', 26) . '_seq';
356
+        }
357
+
358
+        $index = $this->createMock(Index::class);
359
+        $index->expects($this->any())
360
+            ->method('getName')
361
+            ->willReturn($defaultName);
362
+        $index->expects($this->any())
363
+            ->method('getColumns')
364
+            ->willReturn([\str_repeat('b', 30)]);
365
+
366
+        $table = $this->createMock(Table::class);
367
+        $table->expects($this->any())
368
+            ->method('getName')
369
+            ->willReturn(\str_repeat('a', 25));
370
+
371
+        $table->expects($this->once())
372
+            ->method('getColumns')
373
+            ->willReturn([]);
374
+        $table->expects($this->once())
375
+            ->method('getIndexes')
376
+            ->willReturn([]);
377
+        $table->expects($this->once())
378
+            ->method('getForeignKeys')
379
+            ->willReturn([]);
380
+        $table->expects($this->once())
381
+            ->method('getPrimaryKey')
382
+            ->willReturn($index);
383
+
384
+        $schema = $this->createMock(Schema::class);
385
+        $schema->expects($this->once())
386
+            ->method('getTables')
387
+            ->willReturn([$table]);
388
+        $schema->expects($this->once())
389
+            ->method('getSequences')
390
+            ->willReturn([]);
391
+
392
+        $sourceSchema = $this->createMock(Schema::class);
393
+        $sourceSchema->expects($this->any())
394
+            ->method('getTable')
395
+            ->willThrowException(new SchemaException());
396
+        $sourceSchema->expects($this->any())
397
+            ->method('hasSequence')
398
+            ->willReturn(false);
399
+
400
+        self::invokePrivate($this->migrationService, 'ensureOracleConstraints', [$sourceSchema, $schema, 3]);
401
+    }
402
+
403
+
404
+    public function testEnsureOracleConstraintsTooLongTableName(): void {
405
+        $this->expectException(\InvalidArgumentException::class);
406
+
407
+        $table = $this->createMock(Table::class);
408
+        $table->expects($this->any())
409
+            ->method('getName')
410
+            ->willReturn(\str_repeat('a', 31));
411
+
412
+        $schema = $this->createMock(Schema::class);
413
+        $schema->expects($this->once())
414
+            ->method('getTables')
415
+            ->willReturn([$table]);
416
+
417
+        $sourceSchema = $this->createMock(Schema::class);
418
+        $sourceSchema->expects($this->any())
419
+            ->method('getTable')
420
+            ->willThrowException(new SchemaException());
421
+        $sourceSchema->expects($this->any())
422
+            ->method('hasSequence')
423
+            ->willReturn(false);
424
+
425
+        self::invokePrivate($this->migrationService, 'ensureOracleConstraints', [$sourceSchema, $schema, 3]);
426
+    }
427
+
428
+
429
+    public function testEnsureOracleConstraintsTooLongPrimaryWithDefault(): void {
430
+        $this->expectException(\InvalidArgumentException::class);
431
+
432
+        $defaultName = 'PRIMARY';
433
+        if ($this->db->getDatabaseProvider() === IDBConnection::PLATFORM_POSTGRES) {
434
+            $defaultName = \str_repeat('a', 27) . '_' . \str_repeat('b', 30) . '_seq';
435
+        } elseif ($this->db->getDatabaseProvider() === IDBConnection::PLATFORM_ORACLE) {
436
+            $defaultName = \str_repeat('a', 27) . '_seq';
437
+        }
438
+
439
+        $index = $this->createMock(Index::class);
440
+        $index->expects($this->any())
441
+            ->method('getName')
442
+            ->willReturn($defaultName);
443
+        $index->expects($this->any())
444
+            ->method('getColumns')
445
+            ->willReturn([\str_repeat('b', 30)]);
446
+
447
+        $table = $this->createMock(Table::class);
448
+        $table->expects($this->any())
449
+            ->method('getName')
450
+            ->willReturn(\str_repeat('a', 27));
451
+
452
+        $table->expects($this->once())
453
+            ->method('getColumns')
454
+            ->willReturn([]);
455
+        $table->expects($this->once())
456
+            ->method('getIndexes')
457
+            ->willReturn([]);
458
+        $table->expects($this->once())
459
+            ->method('getForeignKeys')
460
+            ->willReturn([]);
461
+        $table->expects($this->once())
462
+            ->method('getPrimaryKey')
463
+            ->willReturn($index);
464
+
465
+        $schema = $this->createMock(Schema::class);
466
+        $schema->expects($this->once())
467
+            ->method('getTables')
468
+            ->willReturn([$table]);
469
+
470
+        $sourceSchema = $this->createMock(Schema::class);
471
+        $sourceSchema->expects($this->any())
472
+            ->method('getTable')
473
+            ->willThrowException(new SchemaException());
474
+        $sourceSchema->expects($this->any())
475
+            ->method('hasSequence')
476
+            ->willReturn(false);
477
+
478
+        self::invokePrivate($this->migrationService, 'ensureOracleConstraints', [$sourceSchema, $schema, 3]);
479
+    }
480
+
481
+
482
+    public function testEnsureOracleConstraintsTooLongPrimaryWithName(): void {
483
+        $this->expectException(\InvalidArgumentException::class);
484
+
485
+        $index = $this->createMock(Index::class);
486
+        $index->expects($this->any())
487
+            ->method('getName')
488
+            ->willReturn(\str_repeat('a', 31));
489
+
490
+        $table = $this->createMock(Table::class);
491
+        $table->expects($this->any())
492
+            ->method('getName')
493
+            ->willReturn(\str_repeat('a', 26));
494
+
495
+        $table->expects($this->once())
496
+            ->method('getColumns')
497
+            ->willReturn([]);
498
+        $table->expects($this->once())
499
+            ->method('getIndexes')
500
+            ->willReturn([]);
501
+        $table->expects($this->once())
502
+            ->method('getForeignKeys')
503
+            ->willReturn([]);
504
+        $table->expects($this->once())
505
+            ->method('getPrimaryKey')
506
+            ->willReturn($index);
507
+
508
+        $schema = $this->createMock(Schema::class);
509
+        $schema->expects($this->once())
510
+            ->method('getTables')
511
+            ->willReturn([$table]);
512
+
513
+        $sourceSchema = $this->createMock(Schema::class);
514
+        $sourceSchema->expects($this->any())
515
+            ->method('getTable')
516
+            ->willThrowException(new SchemaException());
517
+        $sourceSchema->expects($this->any())
518
+            ->method('hasSequence')
519
+            ->willReturn(false);
520
+
521
+        self::invokePrivate($this->migrationService, 'ensureOracleConstraints', [$sourceSchema, $schema, 3]);
522
+    }
523
+
524
+
525
+    public function testEnsureOracleConstraintsTooLongColumnName(): void {
526
+        $this->expectException(\InvalidArgumentException::class);
527
+
528
+        $column = $this->createMock(Column::class);
529
+        $column->expects($this->any())
530
+            ->method('getName')
531
+            ->willReturn(\str_repeat('a', 31));
532
+
533
+        $table = $this->createMock(Table::class);
534
+        $table->expects($this->any())
535
+            ->method('getName')
536
+            ->willReturn(\str_repeat('a', 30));
537
+
538
+        $table->expects($this->once())
539
+            ->method('getColumns')
540
+            ->willReturn([$column]);
541
+
542
+        $schema = $this->createMock(Schema::class);
543
+        $schema->expects($this->once())
544
+            ->method('getTables')
545
+            ->willReturn([$table]);
546
+
547
+        $sourceSchema = $this->createMock(Schema::class);
548
+        $sourceSchema->expects($this->any())
549
+            ->method('getTable')
550
+            ->willThrowException(new SchemaException());
551
+        $sourceSchema->expects($this->any())
552
+            ->method('hasSequence')
553
+            ->willReturn(false);
554
+
555
+        self::invokePrivate($this->migrationService, 'ensureOracleConstraints', [$sourceSchema, $schema, 3]);
556
+    }
557
+
558
+
559
+    public function testEnsureOracleConstraintsTooLongIndexName(): void {
560
+        $this->expectException(\InvalidArgumentException::class);
561
+
562
+        $index = $this->createMock(Index::class);
563
+        $index->expects($this->any())
564
+            ->method('getName')
565
+            ->willReturn(\str_repeat('a', 31));
566
+
567
+        $table = $this->createMock(Table::class);
568
+        $table->expects($this->any())
569
+            ->method('getName')
570
+            ->willReturn(\str_repeat('a', 30));
571
+
572
+        $table->expects($this->once())
573
+            ->method('getColumns')
574
+            ->willReturn([]);
575
+        $table->expects($this->once())
576
+            ->method('getIndexes')
577
+            ->willReturn([$index]);
578
+
579
+        $schema = $this->createMock(Schema::class);
580
+        $schema->expects($this->once())
581
+            ->method('getTables')
582
+            ->willReturn([$table]);
583
+
584
+        $sourceSchema = $this->createMock(Schema::class);
585
+        $sourceSchema->expects($this->any())
586
+            ->method('getTable')
587
+            ->willThrowException(new SchemaException());
588
+        $sourceSchema->expects($this->any())
589
+            ->method('hasSequence')
590
+            ->willReturn(false);
591
+
592
+        self::invokePrivate($this->migrationService, 'ensureOracleConstraints', [$sourceSchema, $schema, 3]);
593
+    }
594
+
595
+
596
+    public function testEnsureOracleConstraintsTooLongForeignKeyName(): void {
597
+        $this->expectException(\InvalidArgumentException::class);
598
+
599
+        $foreignKey = $this->createMock(ForeignKeyConstraint::class);
600
+        $foreignKey->expects($this->any())
601
+            ->method('getName')
602
+            ->willReturn(\str_repeat('a', 31));
603
+
604
+        $table = $this->createMock(Table::class);
605
+        $table->expects($this->any())
606
+            ->method('getName')
607
+            ->willReturn(\str_repeat('a', 30));
608
+
609
+        $table->expects($this->once())
610
+            ->method('getColumns')
611
+            ->willReturn([]);
612
+        $table->expects($this->once())
613
+            ->method('getIndexes')
614
+            ->willReturn([]);
615
+        $table->expects($this->once())
616
+            ->method('getForeignKeys')
617
+            ->willReturn([$foreignKey]);
618
+
619
+        $schema = $this->createMock(Schema::class);
620
+        $schema->expects($this->once())
621
+            ->method('getTables')
622
+            ->willReturn([$table]);
623
+
624
+        $sourceSchema = $this->createMock(Schema::class);
625
+        $sourceSchema->expects($this->any())
626
+            ->method('getTable')
627
+            ->willThrowException(new SchemaException());
628
+        $sourceSchema->expects($this->any())
629
+            ->method('hasSequence')
630
+            ->willReturn(false);
631
+
632
+        self::invokePrivate($this->migrationService, 'ensureOracleConstraints', [$sourceSchema, $schema, 3]);
633
+    }
634
+
635
+
636
+    public function testEnsureOracleConstraintsNoPrimaryKey(): void {
637
+        $this->markTestSkipped('Test disabled for now due to multiple reasons, see https://github.com/nextcloud/server/pull/31580#issuecomment-1069182234 for details.');
638
+        $this->expectException(\InvalidArgumentException::class);
639
+
640
+        $table = $this->createMock(Table::class);
641
+        $table->expects($this->atLeastOnce())
642
+            ->method('getName')
643
+            ->willReturn(\str_repeat('a', 30));
644
+        $table->expects($this->once())
645
+            ->method('getColumns')
646
+            ->willReturn([]);
647
+        $table->expects($this->once())
648
+            ->method('getIndexes')
649
+            ->willReturn([]);
650
+        $table->expects($this->once())
651
+            ->method('getForeignKeys')
652
+            ->willReturn([]);
653
+        $table->expects($this->once())
654
+            ->method('getPrimaryKey')
655
+            ->willReturn(null);
656
+
657
+        $schema = $this->createMock(Schema::class);
658
+        $schema->expects($this->once())
659
+            ->method('getTables')
660
+            ->willReturn([$table]);
661
+        $schema->expects($this->once())
662
+            ->method('getSequences')
663
+            ->willReturn([]);
664
+
665
+        $sourceSchema = $this->createMock(Schema::class);
666
+        $sourceSchema->expects($this->any())
667
+            ->method('getTable')
668
+            ->willThrowException(new SchemaException());
669
+        $sourceSchema->expects($this->any())
670
+            ->method('hasSequence')
671
+            ->willReturn(false);
672
+
673
+        self::invokePrivate($this->migrationService, 'ensureOracleConstraints', [$sourceSchema, $schema, 3]);
674
+    }
675
+
676
+
677
+    public function testEnsureOracleConstraintsTooLongSequenceName(): void {
678
+        $this->expectException(\InvalidArgumentException::class);
679
+
680
+        $sequence = $this->createMock(Sequence::class);
681
+        $sequence->expects($this->any())
682
+            ->method('getName')
683
+            ->willReturn(\str_repeat('a', 31));
684
+
685
+        $schema = $this->createMock(Schema::class);
686
+        $schema->expects($this->once())
687
+            ->method('getTables')
688
+            ->willReturn([]);
689
+        $schema->expects($this->once())
690
+            ->method('getSequences')
691
+            ->willReturn([$sequence]);
692
+
693
+        $sourceSchema = $this->createMock(Schema::class);
694
+        $sourceSchema->expects($this->any())
695
+            ->method('getTable')
696
+            ->willThrowException(new SchemaException());
697
+        $sourceSchema->expects($this->any())
698
+            ->method('hasSequence')
699
+            ->willReturn(false);
700
+
701
+        self::invokePrivate($this->migrationService, 'ensureOracleConstraints', [$sourceSchema, $schema, 3]);
702
+    }
703
+
704
+
705
+    public function testEnsureOracleConstraintsBooleanNotNull(): void {
706
+        $this->expectException(\InvalidArgumentException::class);
707
+
708
+        $column = $this->createMock(Column::class);
709
+        $column->expects($this->any())
710
+            ->method('getName')
711
+            ->willReturn('aaaa');
712
+        $column->expects($this->any())
713
+            ->method('getType')
714
+            ->willReturn(Type::getType('boolean'));
715
+        $column->expects($this->any())
716
+            ->method('getNotnull')
717
+            ->willReturn(true);
718
+
719
+        $table = $this->createMock(Table::class);
720
+        $table->expects($this->any())
721
+            ->method('getName')
722
+            ->willReturn(\str_repeat('a', 30));
723
+
724
+        $table->expects($this->once())
725
+            ->method('getColumns')
726
+            ->willReturn([$column]);
727
+
728
+        $schema = $this->createMock(Schema::class);
729
+        $schema->expects($this->once())
730
+            ->method('getTables')
731
+            ->willReturn([$table]);
732
+
733
+        $sourceSchema = $this->createMock(Schema::class);
734
+        $sourceSchema->expects($this->any())
735
+            ->method('getTable')
736
+            ->willThrowException(new SchemaException());
737
+        $sourceSchema->expects($this->any())
738
+            ->method('hasSequence')
739
+            ->willReturn(false);
740
+
741
+        self::invokePrivate($this->migrationService, 'ensureOracleConstraints', [$sourceSchema, $schema, 3]);
742
+    }
743
+
744
+
745
+    public function testEnsureOracleConstraintsStringLength4000(): void {
746
+        $this->expectException(\InvalidArgumentException::class);
747
+
748
+        $column = $this->createMock(Column::class);
749
+        $column->expects($this->any())
750
+            ->method('getName')
751
+            ->willReturn('aaaa');
752
+        $column->expects($this->any())
753
+            ->method('getType')
754
+            ->willReturn(Type::getType('string'));
755
+        $column->expects($this->any())
756
+            ->method('getLength')
757
+            ->willReturn(4001);
758
+
759
+        $table = $this->createMock(Table::class);
760
+        $table->expects($this->any())
761
+            ->method('getName')
762
+            ->willReturn(\str_repeat('a', 30));
763
+
764
+        $table->expects($this->once())
765
+            ->method('getColumns')
766
+            ->willReturn([$column]);
767
+
768
+        $schema = $this->createMock(Schema::class);
769
+        $schema->expects($this->once())
770
+            ->method('getTables')
771
+            ->willReturn([$table]);
772
+
773
+        $sourceSchema = $this->createMock(Schema::class);
774
+        $sourceSchema->expects($this->any())
775
+            ->method('getTable')
776
+            ->willThrowException(new SchemaException());
777
+        $sourceSchema->expects($this->any())
778
+            ->method('hasSequence')
779
+            ->willReturn(false);
780
+
781
+        self::invokePrivate($this->migrationService, 'ensureOracleConstraints', [$sourceSchema, $schema, 3]);
782
+    }
783
+
784
+
785
+    public function testExtractMigrationAttributes(): void {
786
+        $metadataManager = Server::get(MetadataManager::class);
787
+        $this->appManager->loadApp('testing');
788
+
789
+        $this->assertEquals($this->getMigrationMetadata(), json_decode(json_encode($metadataManager->extractMigrationAttributes('testing')), true));
790
+
791
+        $this->appManager->disableApp('testing');
792
+    }
793
+
794
+    public function testDeserializeMigrationMetadata(): void {
795
+        $metadataManager = Server::get(MetadataManager::class);
796
+        $this->assertEquals(
797
+            [
798
+                'core' => [],
799
+                'apps' => [
800
+                    'testing' => [
801
+                        '30000Date20240102030405' => [
802
+                            new DropTable('old_table'),
803
+                            new CreateTable('new_table',
804
+                                description: 'Table is used to store things, but also to get more things',
805
+                                notes:       ['this is a notice', 'and another one, if really needed']
806
+                            ),
807
+                            new AddColumn('my_table'),
808
+                            new AddColumn('my_table', 'another_field'),
809
+                            new AddColumn('other_table', 'last_one', ColumnType::DATE),
810
+                            new AddIndex('my_table'),
811
+                            new AddIndex('my_table', IndexType::PRIMARY),
812
+                            new DropColumn('other_table'),
813
+                            new DropColumn('other_table', 'old_column',
814
+                                description: 'field is not used anymore and replaced by \'last_one\''
815
+                            ),
816
+                            new DropIndex('other_table'),
817
+                            new ModifyColumn('other_table'),
818
+                            new ModifyColumn('other_table', 'this_field'),
819
+                            new ModifyColumn('other_table', 'this_field', ColumnType::BIGINT)
820
+                        ]
821
+                    ]
822
+                ]
823
+            ],
824
+            $metadataManager->getMigrationsAttributesFromReleaseMetadata(
825
+                [
826
+                    'core' => [],
827
+                    'apps' => ['testing' => $this->getMigrationMetadata()]
828
+                ]
829
+            )
830
+        );
831
+    }
832
+
833
+    private function getMigrationMetadata(): array {
834
+        return [
835
+            '30000Date20240102030405' => [
836
+                [
837
+                    'class' => 'OCP\\Migration\\Attributes\\DropTable',
838
+                    'table' => 'old_table',
839
+                    'description' => '',
840
+                    'notes' => [],
841
+                    'columns' => []
842
+                ],
843
+                [
844
+                    'class' => 'OCP\\Migration\\Attributes\\CreateTable',
845
+                    'table' => 'new_table',
846
+                    'description' => 'Table is used to store things, but also to get more things',
847
+                    'notes' =>
848
+                        [
849
+                            'this is a notice',
850
+                            'and another one, if really needed'
851
+                        ],
852
+                    'columns' => []
853
+                ],
854
+                [
855
+                    'class' => 'OCP\\Migration\\Attributes\\AddColumn',
856
+                    'table' => 'my_table',
857
+                    'description' => '',
858
+                    'notes' => [],
859
+                    'name' => '',
860
+                    'type' => ''
861
+                ],
862
+                [
863
+                    'class' => 'OCP\\Migration\\Attributes\\AddColumn',
864
+                    'table' => 'my_table',
865
+                    'description' => '',
866
+                    'notes' => [],
867
+                    'name' => 'another_field',
868
+                    'type' => ''
869
+                ],
870
+                [
871
+                    'class' => 'OCP\\Migration\\Attributes\\AddColumn',
872
+                    'table' => 'other_table',
873
+                    'description' => '',
874
+                    'notes' => [],
875
+                    'name' => 'last_one',
876
+                    'type' => 'date'
877
+                ],
878
+                [
879
+                    'class' => 'OCP\\Migration\\Attributes\\AddIndex',
880
+                    'table' => 'my_table',
881
+                    'description' => '',
882
+                    'notes' => [],
883
+                    'type' => ''
884
+                ],
885
+                [
886
+                    'class' => 'OCP\\Migration\\Attributes\\AddIndex',
887
+                    'table' => 'my_table',
888
+                    'description' => '',
889
+                    'notes' => [],
890
+                    'type' => 'primary'
891
+                ],
892
+                [
893
+                    'class' => 'OCP\\Migration\\Attributes\\DropColumn',
894
+                    'table' => 'other_table',
895
+                    'description' => '',
896
+                    'notes' => [],
897
+                    'name' => '',
898
+                    'type' => ''
899
+                ],
900
+                [
901
+                    'class' => 'OCP\\Migration\\Attributes\\DropColumn',
902
+                    'table' => 'other_table',
903
+                    'description' => 'field is not used anymore and replaced by \'last_one\'',
904
+                    'notes' => [],
905
+                    'name' => 'old_column',
906
+                    'type' => ''
907
+                ],
908
+                [
909
+                    'class' => 'OCP\\Migration\\Attributes\\DropIndex',
910
+                    'table' => 'other_table',
911
+                    'description' => '',
912
+                    'notes' => [],
913
+                    'type' => ''
914
+                ],
915
+                [
916
+                    'class' => 'OCP\\Migration\\Attributes\\ModifyColumn',
917
+                    'table' => 'other_table',
918
+                    'description' => '',
919
+                    'notes' => [],
920
+                    'name' => '',
921
+                    'type' => ''
922
+                ],
923
+                [
924
+                    'class' => 'OCP\\Migration\\Attributes\\ModifyColumn',
925
+                    'table' => 'other_table',
926
+                    'description' => '',
927
+                    'notes' => [],
928
+                    'name' => 'this_field',
929
+                    'type' => ''
930
+                ],
931
+                [
932
+                    'class' => 'OCP\\Migration\\Attributes\\ModifyColumn',
933
+                    'table' => 'other_table',
934
+                    'description' => '',
935
+                    'notes' => [],
936
+                    'name' => 'this_field',
937
+                    'type' => 'bigint'
938
+                ],
939
+            ]
940
+        ];
941
+    }
942 942
 }
Please login to merge, or discard this patch.
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -41,8 +41,8 @@  discard block
 block discarded – undo
41 41
  * @package Test\DB
42 42
  */
43 43
 class MigrationsTest extends \Test\TestCase {
44
-	private MigrationService|MockObject $migrationService;
45
-	private MockObject|IDBConnection $db;
44
+	private MigrationService | MockObject $migrationService;
45
+	private MockObject | IDBConnection $db;
46 46
 	private IAppManager $appManager;
47 47
 
48 48
 	protected function setUp(): void {
@@ -57,7 +57,7 @@  discard block
 block discarded – undo
57 57
 
58 58
 	public function testGetters(): void {
59 59
 		$this->assertEquals('testing', $this->migrationService->getApp());
60
-		$this->assertEquals(\OC::$SERVERROOT . '/apps/testing/lib/Migration', $this->migrationService->getMigrationsDirectory());
60
+		$this->assertEquals(\OC::$SERVERROOT.'/apps/testing/lib/Migration', $this->migrationService->getMigrationsDirectory());
61 61
 		$this->assertEquals('OCA\Testing\Migration', $this->migrationService->getMigrationsNamespace());
62 62
 		$this->assertEquals('test_oc_migrations', $this->migrationService->getMigrationsTableName());
63 63
 	}
@@ -66,7 +66,7 @@  discard block
 block discarded – undo
66 66
 		$this->migrationService = new MigrationService('core', $this->db);
67 67
 
68 68
 		$this->assertEquals('core', $this->migrationService->getApp());
69
-		$this->assertEquals(\OC::$SERVERROOT . '/core/Migrations', $this->migrationService->getMigrationsDirectory());
69
+		$this->assertEquals(\OC::$SERVERROOT.'/core/Migrations', $this->migrationService->getMigrationsDirectory());
70 70
 		$this->assertEquals('OC\Core\Migrations', $this->migrationService->getMigrationsNamespace());
71 71
 		$this->assertEquals('test_oc_migrations', $this->migrationService->getMigrationsTableName());
72 72
 	}
@@ -234,7 +234,7 @@  discard block
 block discarded – undo
234 234
 		];
235 235
 		$this->migrationService->expects($this->exactly(2))
236 236
 			->method('executeStep')
237
-			->willReturnCallback(function () use (&$calls) {
237
+			->willReturnCallback(function() use (&$calls) {
238 238
 				$expected = array_shift($calls);
239 239
 				$this->assertEquals($expected, func_get_args());
240 240
 			});
@@ -350,9 +350,9 @@  discard block
 block discarded – undo
350 350
 	public function testEnsureOracleConstraintsValidWithPrimaryKeyDefault(): void {
351 351
 		$defaultName = 'PRIMARY';
352 352
 		if ($this->db->getDatabaseProvider() === IDBConnection::PLATFORM_POSTGRES) {
353
-			$defaultName = \str_repeat('a', 26) . '_' . \str_repeat('b', 30) . '_seq';
353
+			$defaultName = \str_repeat('a', 26).'_'.\str_repeat('b', 30).'_seq';
354 354
 		} elseif ($this->db->getDatabaseProvider() === IDBConnection::PLATFORM_ORACLE) {
355
-			$defaultName = \str_repeat('a', 26) . '_seq';
355
+			$defaultName = \str_repeat('a', 26).'_seq';
356 356
 		}
357 357
 
358 358
 		$index = $this->createMock(Index::class);
@@ -431,9 +431,9 @@  discard block
 block discarded – undo
431 431
 
432 432
 		$defaultName = 'PRIMARY';
433 433
 		if ($this->db->getDatabaseProvider() === IDBConnection::PLATFORM_POSTGRES) {
434
-			$defaultName = \str_repeat('a', 27) . '_' . \str_repeat('b', 30) . '_seq';
434
+			$defaultName = \str_repeat('a', 27).'_'.\str_repeat('b', 30).'_seq';
435 435
 		} elseif ($this->db->getDatabaseProvider() === IDBConnection::PLATFORM_ORACLE) {
436
-			$defaultName = \str_repeat('a', 27) . '_seq';
436
+			$defaultName = \str_repeat('a', 27).'_seq';
437 437
 		}
438 438
 
439 439
 		$index = $this->createMock(Index::class);
Please login to merge, or discard this patch.
tests/lib/User/AvailabilityCoordinatorTest.php 2 patches
Indentation   +194 added lines, -194 removed lines patch added patch discarded remove patch
@@ -23,198 +23,198 @@
 block discarded – undo
23 23
 use Test\TestCase;
24 24
 
25 25
 class AvailabilityCoordinatorTest extends TestCase {
26
-	private AvailabilityCoordinator $availabilityCoordinator;
27
-	private ICacheFactory $cacheFactory;
28
-	private ICache $cache;
29
-	private IConfig|MockObject $config;
30
-	private AbsenceService $absenceService;
31
-	private LoggerInterface $logger;
32
-	private MockObject|TimezoneService $timezoneService;
33
-
34
-	protected function setUp(): void {
35
-		parent::setUp();
36
-
37
-		$this->cacheFactory = $this->createMock(ICacheFactory::class);
38
-		$this->cache = $this->createMock(ICache::class);
39
-		$this->absenceService = $this->createMock(AbsenceService::class);
40
-		$this->config = $this->createMock(IConfig::class);
41
-		$this->logger = $this->createMock(LoggerInterface::class);
42
-		$this->timezoneService = $this->createMock(TimezoneService::class);
43
-
44
-		$this->cacheFactory->expects(self::once())
45
-			->method('createLocal')
46
-			->willReturn($this->cache);
47
-
48
-		$this->availabilityCoordinator = new AvailabilityCoordinator(
49
-			$this->cacheFactory,
50
-			$this->config,
51
-			$this->absenceService,
52
-			$this->logger,
53
-			$this->timezoneService,
54
-		);
55
-	}
56
-
57
-	public function testIsEnabled(): void {
58
-		$this->config->expects(self::once())
59
-			->method('getAppValue')
60
-			->with('dav', 'hide_absence_settings', 'no')
61
-			->willReturn('no');
62
-
63
-		$isEnabled = $this->availabilityCoordinator->isEnabled();
64
-
65
-		self::assertTrue($isEnabled);
66
-	}
67
-
68
-	public function testGetOutOfOfficeDataInEffect(): void {
69
-		$absence = new Absence();
70
-		$absence->setId(420);
71
-		$absence->setUserId('user');
72
-		$absence->setFirstDay('2023-10-01');
73
-		$absence->setLastDay('2023-10-08');
74
-		$absence->setStatus('Vacation');
75
-		$absence->setMessage('On vacation');
76
-		$absence->setReplacementUserId('batman');
77
-		$absence->setReplacementUserDisplayName('Bruce Wayne');
78
-		$this->timezoneService->method('getUserTimezone')->with('user')->willReturn('Europe/Berlin');
79
-
80
-		$user = $this->createMock(IUser::class);
81
-		$user->method('getUID')
82
-			->willReturn('user');
83
-
84
-		$this->cache->expects(self::exactly(2))
85
-			->method('get')
86
-			->willReturnOnConsecutiveCalls(null, null);
87
-		$this->absenceService->expects(self::once())
88
-			->method('getAbsence')
89
-			->with($user->getUID())
90
-			->willReturn($absence);
91
-
92
-		$calls = [
93
-			[$user->getUID() . '_timezone', 'Europe/Berlin', 3600],
94
-			[$user->getUID(), '{"id":"420","startDate":1696111200,"endDate":1696802340,"shortMessage":"Vacation","message":"On vacation","replacementUserId":"batman","replacementUserDisplayName":"Bruce Wayne"}', 300],
95
-		];
96
-		$this->cache->expects(self::exactly(2))
97
-			->method('set')
98
-			->willReturnCallback(static function () use (&$calls): void {
99
-				$expected = array_shift($calls);
100
-				self::assertEquals($expected, func_get_args());
101
-			});
102
-
103
-		$expected = new OutOfOfficeData(
104
-			'420',
105
-			$user,
106
-			1696111200,
107
-			1696802340,
108
-			'Vacation',
109
-			'On vacation',
110
-			'batman',
111
-			'Bruce Wayne',
112
-		);
113
-		$actual = $this->availabilityCoordinator->getCurrentOutOfOfficeData($user);
114
-		self::assertEquals($expected, $actual);
115
-	}
116
-
117
-	public function testGetOutOfOfficeDataCachedAll(): void {
118
-		$absence = new Absence();
119
-		$absence->setId(420);
120
-		$absence->setUserId('user');
121
-		$absence->setFirstDay('2023-10-01');
122
-		$absence->setLastDay('2023-10-08');
123
-		$absence->setStatus('Vacation');
124
-		$absence->setMessage('On vacation');
125
-		$absence->setReplacementUserId('batman');
126
-		$absence->setReplacementUserDisplayName('Bruce Wayne');
127
-
128
-		$user = $this->createMock(IUser::class);
129
-		$user->method('getUID')
130
-			->willReturn('user');
131
-
132
-		$this->cache->expects(self::exactly(2))
133
-			->method('get')
134
-			->willReturnOnConsecutiveCalls('UTC', '{"id":"420","startDate":1696118400,"endDate":1696809540,"shortMessage":"Vacation","message":"On vacation","replacementUserId":"batman","replacementUserDisplayName":"Bruce Wayne"}');
135
-		$this->absenceService->expects(self::never())
136
-			->method('getAbsence');
137
-		$this->cache->expects(self::exactly(1))
138
-			->method('set');
139
-
140
-		$expected = new OutOfOfficeData(
141
-			'420',
142
-			$user,
143
-			1696118400,
144
-			1696809540,
145
-			'Vacation',
146
-			'On vacation',
147
-			'batman',
148
-			'Bruce Wayne'
149
-		);
150
-		$actual = $this->availabilityCoordinator->getCurrentOutOfOfficeData($user);
151
-		self::assertEquals($expected, $actual);
152
-	}
153
-
154
-	public function testGetOutOfOfficeDataNoData(): void {
155
-		$absence = new Absence();
156
-		$absence->setId(420);
157
-		$absence->setUserId('user');
158
-		$absence->setFirstDay('2023-10-01');
159
-		$absence->setLastDay('2023-10-08');
160
-		$absence->setStatus('Vacation');
161
-		$absence->setMessage('On vacation');
162
-
163
-		$user = $this->createMock(IUser::class);
164
-		$user->method('getUID')
165
-			->willReturn('user');
166
-
167
-		$this->cache->expects(self::exactly(2))
168
-			->method('get')
169
-			->willReturnOnConsecutiveCalls('UTC', null);
170
-		$this->absenceService->expects(self::once())
171
-			->method('getAbsence')
172
-			->willReturn(null);
173
-		$this->cache->expects(self::never())
174
-			->method('set');
175
-
176
-		$actual = $this->availabilityCoordinator->getCurrentOutOfOfficeData($user);
177
-		self::assertNull($actual);
178
-	}
179
-
180
-	public function testGetOutOfOfficeDataWithInvalidCachedData(): void {
181
-		$absence = new Absence();
182
-		$absence->setId(420);
183
-		$absence->setUserId('user');
184
-		$absence->setFirstDay('2023-10-01');
185
-		$absence->setLastDay('2023-10-08');
186
-		$absence->setStatus('Vacation');
187
-		$absence->setMessage('On vacation');
188
-		$absence->setReplacementUserId('batman');
189
-		$absence->setReplacementUserDisplayName('Bruce Wayne');
190
-		$this->timezoneService->method('getUserTimezone')->with('user')->willReturn('Europe/Berlin');
191
-
192
-		$user = $this->createMock(IUser::class);
193
-		$user->method('getUID')
194
-			->willReturn('user');
195
-
196
-		$this->cache->expects(self::exactly(2))
197
-			->method('get')
198
-			->willReturnOnConsecutiveCalls('UTC', '{"id":"420",}');
199
-		$this->absenceService->expects(self::once())
200
-			->method('getAbsence')
201
-			->with('user')
202
-			->willReturn($absence);
203
-		$this->cache->expects(self::once())
204
-			->method('set')
205
-			->with('user', '{"id":"420","startDate":1696118400,"endDate":1696809540,"shortMessage":"Vacation","message":"On vacation","replacementUserId":"batman","replacementUserDisplayName":"Bruce Wayne"}', 300);
206
-
207
-		$expected = new OutOfOfficeData(
208
-			'420',
209
-			$user,
210
-			1696118400,
211
-			1696809540,
212
-			'Vacation',
213
-			'On vacation',
214
-			'batman',
215
-			'Bruce Wayne'
216
-		);
217
-		$actual = $this->availabilityCoordinator->getCurrentOutOfOfficeData($user);
218
-		self::assertEquals($expected, $actual);
219
-	}
26
+    private AvailabilityCoordinator $availabilityCoordinator;
27
+    private ICacheFactory $cacheFactory;
28
+    private ICache $cache;
29
+    private IConfig|MockObject $config;
30
+    private AbsenceService $absenceService;
31
+    private LoggerInterface $logger;
32
+    private MockObject|TimezoneService $timezoneService;
33
+
34
+    protected function setUp(): void {
35
+        parent::setUp();
36
+
37
+        $this->cacheFactory = $this->createMock(ICacheFactory::class);
38
+        $this->cache = $this->createMock(ICache::class);
39
+        $this->absenceService = $this->createMock(AbsenceService::class);
40
+        $this->config = $this->createMock(IConfig::class);
41
+        $this->logger = $this->createMock(LoggerInterface::class);
42
+        $this->timezoneService = $this->createMock(TimezoneService::class);
43
+
44
+        $this->cacheFactory->expects(self::once())
45
+            ->method('createLocal')
46
+            ->willReturn($this->cache);
47
+
48
+        $this->availabilityCoordinator = new AvailabilityCoordinator(
49
+            $this->cacheFactory,
50
+            $this->config,
51
+            $this->absenceService,
52
+            $this->logger,
53
+            $this->timezoneService,
54
+        );
55
+    }
56
+
57
+    public function testIsEnabled(): void {
58
+        $this->config->expects(self::once())
59
+            ->method('getAppValue')
60
+            ->with('dav', 'hide_absence_settings', 'no')
61
+            ->willReturn('no');
62
+
63
+        $isEnabled = $this->availabilityCoordinator->isEnabled();
64
+
65
+        self::assertTrue($isEnabled);
66
+    }
67
+
68
+    public function testGetOutOfOfficeDataInEffect(): void {
69
+        $absence = new Absence();
70
+        $absence->setId(420);
71
+        $absence->setUserId('user');
72
+        $absence->setFirstDay('2023-10-01');
73
+        $absence->setLastDay('2023-10-08');
74
+        $absence->setStatus('Vacation');
75
+        $absence->setMessage('On vacation');
76
+        $absence->setReplacementUserId('batman');
77
+        $absence->setReplacementUserDisplayName('Bruce Wayne');
78
+        $this->timezoneService->method('getUserTimezone')->with('user')->willReturn('Europe/Berlin');
79
+
80
+        $user = $this->createMock(IUser::class);
81
+        $user->method('getUID')
82
+            ->willReturn('user');
83
+
84
+        $this->cache->expects(self::exactly(2))
85
+            ->method('get')
86
+            ->willReturnOnConsecutiveCalls(null, null);
87
+        $this->absenceService->expects(self::once())
88
+            ->method('getAbsence')
89
+            ->with($user->getUID())
90
+            ->willReturn($absence);
91
+
92
+        $calls = [
93
+            [$user->getUID() . '_timezone', 'Europe/Berlin', 3600],
94
+            [$user->getUID(), '{"id":"420","startDate":1696111200,"endDate":1696802340,"shortMessage":"Vacation","message":"On vacation","replacementUserId":"batman","replacementUserDisplayName":"Bruce Wayne"}', 300],
95
+        ];
96
+        $this->cache->expects(self::exactly(2))
97
+            ->method('set')
98
+            ->willReturnCallback(static function () use (&$calls): void {
99
+                $expected = array_shift($calls);
100
+                self::assertEquals($expected, func_get_args());
101
+            });
102
+
103
+        $expected = new OutOfOfficeData(
104
+            '420',
105
+            $user,
106
+            1696111200,
107
+            1696802340,
108
+            'Vacation',
109
+            'On vacation',
110
+            'batman',
111
+            'Bruce Wayne',
112
+        );
113
+        $actual = $this->availabilityCoordinator->getCurrentOutOfOfficeData($user);
114
+        self::assertEquals($expected, $actual);
115
+    }
116
+
117
+    public function testGetOutOfOfficeDataCachedAll(): void {
118
+        $absence = new Absence();
119
+        $absence->setId(420);
120
+        $absence->setUserId('user');
121
+        $absence->setFirstDay('2023-10-01');
122
+        $absence->setLastDay('2023-10-08');
123
+        $absence->setStatus('Vacation');
124
+        $absence->setMessage('On vacation');
125
+        $absence->setReplacementUserId('batman');
126
+        $absence->setReplacementUserDisplayName('Bruce Wayne');
127
+
128
+        $user = $this->createMock(IUser::class);
129
+        $user->method('getUID')
130
+            ->willReturn('user');
131
+
132
+        $this->cache->expects(self::exactly(2))
133
+            ->method('get')
134
+            ->willReturnOnConsecutiveCalls('UTC', '{"id":"420","startDate":1696118400,"endDate":1696809540,"shortMessage":"Vacation","message":"On vacation","replacementUserId":"batman","replacementUserDisplayName":"Bruce Wayne"}');
135
+        $this->absenceService->expects(self::never())
136
+            ->method('getAbsence');
137
+        $this->cache->expects(self::exactly(1))
138
+            ->method('set');
139
+
140
+        $expected = new OutOfOfficeData(
141
+            '420',
142
+            $user,
143
+            1696118400,
144
+            1696809540,
145
+            'Vacation',
146
+            'On vacation',
147
+            'batman',
148
+            'Bruce Wayne'
149
+        );
150
+        $actual = $this->availabilityCoordinator->getCurrentOutOfOfficeData($user);
151
+        self::assertEquals($expected, $actual);
152
+    }
153
+
154
+    public function testGetOutOfOfficeDataNoData(): void {
155
+        $absence = new Absence();
156
+        $absence->setId(420);
157
+        $absence->setUserId('user');
158
+        $absence->setFirstDay('2023-10-01');
159
+        $absence->setLastDay('2023-10-08');
160
+        $absence->setStatus('Vacation');
161
+        $absence->setMessage('On vacation');
162
+
163
+        $user = $this->createMock(IUser::class);
164
+        $user->method('getUID')
165
+            ->willReturn('user');
166
+
167
+        $this->cache->expects(self::exactly(2))
168
+            ->method('get')
169
+            ->willReturnOnConsecutiveCalls('UTC', null);
170
+        $this->absenceService->expects(self::once())
171
+            ->method('getAbsence')
172
+            ->willReturn(null);
173
+        $this->cache->expects(self::never())
174
+            ->method('set');
175
+
176
+        $actual = $this->availabilityCoordinator->getCurrentOutOfOfficeData($user);
177
+        self::assertNull($actual);
178
+    }
179
+
180
+    public function testGetOutOfOfficeDataWithInvalidCachedData(): void {
181
+        $absence = new Absence();
182
+        $absence->setId(420);
183
+        $absence->setUserId('user');
184
+        $absence->setFirstDay('2023-10-01');
185
+        $absence->setLastDay('2023-10-08');
186
+        $absence->setStatus('Vacation');
187
+        $absence->setMessage('On vacation');
188
+        $absence->setReplacementUserId('batman');
189
+        $absence->setReplacementUserDisplayName('Bruce Wayne');
190
+        $this->timezoneService->method('getUserTimezone')->with('user')->willReturn('Europe/Berlin');
191
+
192
+        $user = $this->createMock(IUser::class);
193
+        $user->method('getUID')
194
+            ->willReturn('user');
195
+
196
+        $this->cache->expects(self::exactly(2))
197
+            ->method('get')
198
+            ->willReturnOnConsecutiveCalls('UTC', '{"id":"420",}');
199
+        $this->absenceService->expects(self::once())
200
+            ->method('getAbsence')
201
+            ->with('user')
202
+            ->willReturn($absence);
203
+        $this->cache->expects(self::once())
204
+            ->method('set')
205
+            ->with('user', '{"id":"420","startDate":1696118400,"endDate":1696809540,"shortMessage":"Vacation","message":"On vacation","replacementUserId":"batman","replacementUserDisplayName":"Bruce Wayne"}', 300);
206
+
207
+        $expected = new OutOfOfficeData(
208
+            '420',
209
+            $user,
210
+            1696118400,
211
+            1696809540,
212
+            'Vacation',
213
+            'On vacation',
214
+            'batman',
215
+            'Bruce Wayne'
216
+        );
217
+        $actual = $this->availabilityCoordinator->getCurrentOutOfOfficeData($user);
218
+        self::assertEquals($expected, $actual);
219
+    }
220 220
 }
Please login to merge, or discard this patch.
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -26,10 +26,10 @@  discard block
 block discarded – undo
26 26
 	private AvailabilityCoordinator $availabilityCoordinator;
27 27
 	private ICacheFactory $cacheFactory;
28 28
 	private ICache $cache;
29
-	private IConfig|MockObject $config;
29
+	private IConfig | MockObject $config;
30 30
 	private AbsenceService $absenceService;
31 31
 	private LoggerInterface $logger;
32
-	private MockObject|TimezoneService $timezoneService;
32
+	private MockObject | TimezoneService $timezoneService;
33 33
 
34 34
 	protected function setUp(): void {
35 35
 		parent::setUp();
@@ -90,12 +90,12 @@  discard block
 block discarded – undo
90 90
 			->willReturn($absence);
91 91
 
92 92
 		$calls = [
93
-			[$user->getUID() . '_timezone', 'Europe/Berlin', 3600],
93
+			[$user->getUID().'_timezone', 'Europe/Berlin', 3600],
94 94
 			[$user->getUID(), '{"id":"420","startDate":1696111200,"endDate":1696802340,"shortMessage":"Vacation","message":"On vacation","replacementUserId":"batman","replacementUserDisplayName":"Bruce Wayne"}', 300],
95 95
 		];
96 96
 		$this->cache->expects(self::exactly(2))
97 97
 			->method('set')
98
-			->willReturnCallback(static function () use (&$calls): void {
98
+			->willReturnCallback(static function() use (&$calls): void {
99 99
 				$expected = array_shift($calls);
100 100
 				self::assertEquals($expected, func_get_args());
101 101
 			});
Please login to merge, or discard this patch.
tests/lib/Collaboration/Resources/ProviderManagerTest.php 2 patches
Indentation   +78 added lines, -78 removed lines patch added patch discarded remove patch
@@ -17,82 +17,82 @@
 block discarded – undo
17 17
 use Test\TestCase;
18 18
 
19 19
 class ProviderManagerTest extends TestCase {
20
-	/** @var IServerContainer */
21
-	protected $serverContainer;
22
-	/** @var LoggerInterface */
23
-	protected $logger;
24
-	/** @var IProviderManager */
25
-	protected $providerManager;
26
-
27
-	protected function setUp(): void {
28
-		parent::setUp();
29
-
30
-		$this->serverContainer = $this->createMock(IServerContainer::class);
31
-		$this->logger = $this->createMock(LoggerInterface::class);
32
-
33
-		$this->providerManager = new class($this->serverContainer, $this->logger) extends ProviderManager {
34
-			public function countProviders(): int {
35
-				return count($this->providers);
36
-			}
37
-		};
38
-	}
39
-
40
-	public function testRegisterResourceProvider(): void {
41
-		$this->providerManager->registerResourceProvider('AwesomeResourceProvider');
42
-		$this->assertSame(1, $this->providerManager->countProviders());
43
-	}
44
-
45
-	public function testGetResourceProvidersNoProvider(): void {
46
-		$this->assertCount(0, $this->providerManager->getResourceProviders());
47
-	}
48
-
49
-	public function testGetResourceProvidersValidProvider(): void {
50
-		$this->serverContainer->expects($this->once())
51
-			->method('query')
52
-			->with($this->equalTo(ResourceProvider::class))
53
-			->willReturn($this->createMock(ResourceProvider::class));
54
-
55
-		$this->providerManager->registerResourceProvider(ResourceProvider::class);
56
-		$resourceProviders = $this->providerManager->getResourceProviders();
57
-
58
-		$this->assertCount(1, $resourceProviders);
59
-		$this->assertInstanceOf(ResourceProvider::class, $resourceProviders[0]);
60
-	}
61
-
62
-	public function testGetResourceProvidersInvalidProvider(): void {
63
-		$this->serverContainer->expects($this->once())
64
-			->method('query')
65
-			->with($this->equalTo('InvalidResourceProvider'))
66
-			->willThrowException(new QueryException('A meaningful error message'));
67
-
68
-		$this->logger->expects($this->once())
69
-			->method('error');
70
-
71
-		$this->providerManager->registerResourceProvider('InvalidResourceProvider');
72
-		$resourceProviders = $this->providerManager->getResourceProviders();
73
-
74
-		$this->assertCount(0, $resourceProviders);
75
-	}
76
-
77
-	public function testGetResourceProvidersValidAndInvalidProvider(): void {
78
-		$this->serverContainer->expects($this->exactly(2))
79
-			->method('query')
80
-			->willReturnCallback(function (string $service) {
81
-				if ($service === 'InvalidResourceProvider') {
82
-					throw new QueryException('A meaningful error message');
83
-				}
84
-				if ($service === ResourceProvider::class) {
85
-					return $this->createMock(ResourceProvider::class);
86
-				}
87
-			});
88
-
89
-		$this->logger->expects($this->once())
90
-			->method('error');
91
-
92
-		$this->providerManager->registerResourceProvider('InvalidResourceProvider');
93
-		$this->providerManager->registerResourceProvider(ResourceProvider::class);
94
-		$resourceProviders = $this->providerManager->getResourceProviders();
95
-
96
-		$this->assertCount(1, $resourceProviders);
97
-	}
20
+    /** @var IServerContainer */
21
+    protected $serverContainer;
22
+    /** @var LoggerInterface */
23
+    protected $logger;
24
+    /** @var IProviderManager */
25
+    protected $providerManager;
26
+
27
+    protected function setUp(): void {
28
+        parent::setUp();
29
+
30
+        $this->serverContainer = $this->createMock(IServerContainer::class);
31
+        $this->logger = $this->createMock(LoggerInterface::class);
32
+
33
+        $this->providerManager = new class($this->serverContainer, $this->logger) extends ProviderManager {
34
+            public function countProviders(): int {
35
+                return count($this->providers);
36
+            }
37
+        };
38
+    }
39
+
40
+    public function testRegisterResourceProvider(): void {
41
+        $this->providerManager->registerResourceProvider('AwesomeResourceProvider');
42
+        $this->assertSame(1, $this->providerManager->countProviders());
43
+    }
44
+
45
+    public function testGetResourceProvidersNoProvider(): void {
46
+        $this->assertCount(0, $this->providerManager->getResourceProviders());
47
+    }
48
+
49
+    public function testGetResourceProvidersValidProvider(): void {
50
+        $this->serverContainer->expects($this->once())
51
+            ->method('query')
52
+            ->with($this->equalTo(ResourceProvider::class))
53
+            ->willReturn($this->createMock(ResourceProvider::class));
54
+
55
+        $this->providerManager->registerResourceProvider(ResourceProvider::class);
56
+        $resourceProviders = $this->providerManager->getResourceProviders();
57
+
58
+        $this->assertCount(1, $resourceProviders);
59
+        $this->assertInstanceOf(ResourceProvider::class, $resourceProviders[0]);
60
+    }
61
+
62
+    public function testGetResourceProvidersInvalidProvider(): void {
63
+        $this->serverContainer->expects($this->once())
64
+            ->method('query')
65
+            ->with($this->equalTo('InvalidResourceProvider'))
66
+            ->willThrowException(new QueryException('A meaningful error message'));
67
+
68
+        $this->logger->expects($this->once())
69
+            ->method('error');
70
+
71
+        $this->providerManager->registerResourceProvider('InvalidResourceProvider');
72
+        $resourceProviders = $this->providerManager->getResourceProviders();
73
+
74
+        $this->assertCount(0, $resourceProviders);
75
+    }
76
+
77
+    public function testGetResourceProvidersValidAndInvalidProvider(): void {
78
+        $this->serverContainer->expects($this->exactly(2))
79
+            ->method('query')
80
+            ->willReturnCallback(function (string $service) {
81
+                if ($service === 'InvalidResourceProvider') {
82
+                    throw new QueryException('A meaningful error message');
83
+                }
84
+                if ($service === ResourceProvider::class) {
85
+                    return $this->createMock(ResourceProvider::class);
86
+                }
87
+            });
88
+
89
+        $this->logger->expects($this->once())
90
+            ->method('error');
91
+
92
+        $this->providerManager->registerResourceProvider('InvalidResourceProvider');
93
+        $this->providerManager->registerResourceProvider(ResourceProvider::class);
94
+        $resourceProviders = $this->providerManager->getResourceProviders();
95
+
96
+        $this->assertCount(1, $resourceProviders);
97
+    }
98 98
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -77,7 +77,7 @@
 block discarded – undo
77 77
 	public function testGetResourceProvidersValidAndInvalidProvider(): void {
78 78
 		$this->serverContainer->expects($this->exactly(2))
79 79
 			->method('query')
80
-			->willReturnCallback(function (string $service) {
80
+			->willReturnCallback(function(string $service) {
81 81
 				if ($service === 'InvalidResourceProvider') {
82 82
 					throw new QueryException('A meaningful error message');
83 83
 				}
Please login to merge, or discard this patch.
tests/lib/Log/LogFactoryTest.php 1 patch
Indentation   +123 added lines, -123 removed lines patch added patch discarded remove patch
@@ -21,127 +21,127 @@
 block discarded – undo
21 21
  * @package Test\Log
22 22
  */
23 23
 class LogFactoryTest extends TestCase {
24
-	/** @var IServerContainer|\PHPUnit\Framework\MockObject\MockObject */
25
-	protected $c;
26
-
27
-	/** @var LogFactory */
28
-	protected $factory;
29
-
30
-	/** @var SystemConfig|\PHPUnit\Framework\MockObject\MockObject */
31
-	protected $systemConfig;
32
-
33
-	protected function setUp(): void {
34
-		parent::setUp();
35
-
36
-		$this->c = $this->createMock(IServerContainer::class);
37
-		$this->systemConfig = $this->createMock(SystemConfig::class);
38
-
39
-		$this->factory = new LogFactory($this->c, $this->systemConfig);
40
-	}
41
-
42
-	public static function fileTypeProvider(): array {
43
-		return [
44
-			[
45
-				'file'
46
-			],
47
-			[
48
-				'nextcloud'
49
-			],
50
-			[
51
-				'owncloud'
52
-			],
53
-			[
54
-				'krzxkyr_default'
55
-			]
56
-		];
57
-	}
58
-
59
-	/**
60
-	 * @param string $type
61
-	 * @dataProvider fileTypeProvider
62
-	 * @throws \OCP\AppFramework\QueryException
63
-	 */
64
-	public function testFile(string $type): void {
65
-		$datadir = \OC::$SERVERROOT . '/data';
66
-		$defaultLog = $datadir . '/nextcloud.log';
67
-
68
-		$this->systemConfig->expects($this->exactly(3))
69
-			->method('getValue')
70
-			->willReturnMap([
71
-				['datadirectory', $datadir, $datadir],
72
-				['logfile', $defaultLog, $defaultLog],
73
-				['logfilemode', 0640, 0640],
74
-			]);
75
-
76
-		$log = $this->factory->get($type);
77
-		$this->assertInstanceOf(File::class, $log);
78
-	}
79
-
80
-	public static function logFilePathProvider():array {
81
-		return [
82
-			[
83
-				'/dev/null',
84
-				'/dev/null'
85
-			],
86
-			[
87
-				'/xdev/youshallfallback',
88
-				\OC::$SERVERROOT . '/data/nextcloud.log'
89
-			]
90
-		];
91
-	}
92
-
93
-	/**
94
-	 * @dataProvider logFilePathProvider
95
-	 * @throws \OCP\AppFramework\QueryException
96
-	 */
97
-	public function testFileCustomPath($path, $expected): void {
98
-		$datadir = \OC::$SERVERROOT . '/data';
99
-		$defaultLog = $datadir . '/nextcloud.log';
100
-
101
-		$this->systemConfig->expects($this->exactly(3))
102
-			->method('getValue')
103
-			->willReturnMap([
104
-				['datadirectory', $datadir, $datadir],
105
-				['logfile', $defaultLog, $path],
106
-				['logfilemode', 0640, 0640],
107
-			]);
108
-
109
-		$log = $this->factory->get('file');
110
-		$this->assertInstanceOf(File::class, $log);
111
-		$this->assertSame($expected, $log->getLogFilePath());
112
-	}
113
-
114
-	/**
115
-	 * @throws \OCP\AppFramework\QueryException
116
-	 */
117
-	public function testErrorLog(): void {
118
-		$log = $this->factory->get('errorlog');
119
-		$this->assertInstanceOf(Errorlog::class, $log);
120
-	}
121
-
122
-	/**
123
-	 * @throws \OCP\AppFramework\QueryException
124
-	 */
125
-	public function testSystemLog(): void {
126
-		$this->c->expects($this->once())
127
-			->method('resolve')
128
-			->with(Syslog::class)
129
-			->willReturn($this->createMock(Syslog::class));
130
-
131
-		$log = $this->factory->get('syslog');
132
-		$this->assertInstanceOf(Syslog::class, $log);
133
-	}
134
-
135
-	/**
136
-	 * @throws \OCP\AppFramework\QueryException
137
-	 */
138
-	public function testSystemdLog(): void {
139
-		$this->c->expects($this->once())
140
-			->method('resolve')
141
-			->with(Systemdlog::class)
142
-			->willReturn($this->createMock(Systemdlog::class));
143
-
144
-		$log = $this->factory->get('systemd');
145
-		$this->assertInstanceOf(Systemdlog::class, $log);
146
-	}
24
+    /** @var IServerContainer|\PHPUnit\Framework\MockObject\MockObject */
25
+    protected $c;
26
+
27
+    /** @var LogFactory */
28
+    protected $factory;
29
+
30
+    /** @var SystemConfig|\PHPUnit\Framework\MockObject\MockObject */
31
+    protected $systemConfig;
32
+
33
+    protected function setUp(): void {
34
+        parent::setUp();
35
+
36
+        $this->c = $this->createMock(IServerContainer::class);
37
+        $this->systemConfig = $this->createMock(SystemConfig::class);
38
+
39
+        $this->factory = new LogFactory($this->c, $this->systemConfig);
40
+    }
41
+
42
+    public static function fileTypeProvider(): array {
43
+        return [
44
+            [
45
+                'file'
46
+            ],
47
+            [
48
+                'nextcloud'
49
+            ],
50
+            [
51
+                'owncloud'
52
+            ],
53
+            [
54
+                'krzxkyr_default'
55
+            ]
56
+        ];
57
+    }
58
+
59
+    /**
60
+     * @param string $type
61
+     * @dataProvider fileTypeProvider
62
+     * @throws \OCP\AppFramework\QueryException
63
+     */
64
+    public function testFile(string $type): void {
65
+        $datadir = \OC::$SERVERROOT . '/data';
66
+        $defaultLog = $datadir . '/nextcloud.log';
67
+
68
+        $this->systemConfig->expects($this->exactly(3))
69
+            ->method('getValue')
70
+            ->willReturnMap([
71
+                ['datadirectory', $datadir, $datadir],
72
+                ['logfile', $defaultLog, $defaultLog],
73
+                ['logfilemode', 0640, 0640],
74
+            ]);
75
+
76
+        $log = $this->factory->get($type);
77
+        $this->assertInstanceOf(File::class, $log);
78
+    }
79
+
80
+    public static function logFilePathProvider():array {
81
+        return [
82
+            [
83
+                '/dev/null',
84
+                '/dev/null'
85
+            ],
86
+            [
87
+                '/xdev/youshallfallback',
88
+                \OC::$SERVERROOT . '/data/nextcloud.log'
89
+            ]
90
+        ];
91
+    }
92
+
93
+    /**
94
+     * @dataProvider logFilePathProvider
95
+     * @throws \OCP\AppFramework\QueryException
96
+     */
97
+    public function testFileCustomPath($path, $expected): void {
98
+        $datadir = \OC::$SERVERROOT . '/data';
99
+        $defaultLog = $datadir . '/nextcloud.log';
100
+
101
+        $this->systemConfig->expects($this->exactly(3))
102
+            ->method('getValue')
103
+            ->willReturnMap([
104
+                ['datadirectory', $datadir, $datadir],
105
+                ['logfile', $defaultLog, $path],
106
+                ['logfilemode', 0640, 0640],
107
+            ]);
108
+
109
+        $log = $this->factory->get('file');
110
+        $this->assertInstanceOf(File::class, $log);
111
+        $this->assertSame($expected, $log->getLogFilePath());
112
+    }
113
+
114
+    /**
115
+     * @throws \OCP\AppFramework\QueryException
116
+     */
117
+    public function testErrorLog(): void {
118
+        $log = $this->factory->get('errorlog');
119
+        $this->assertInstanceOf(Errorlog::class, $log);
120
+    }
121
+
122
+    /**
123
+     * @throws \OCP\AppFramework\QueryException
124
+     */
125
+    public function testSystemLog(): void {
126
+        $this->c->expects($this->once())
127
+            ->method('resolve')
128
+            ->with(Syslog::class)
129
+            ->willReturn($this->createMock(Syslog::class));
130
+
131
+        $log = $this->factory->get('syslog');
132
+        $this->assertInstanceOf(Syslog::class, $log);
133
+    }
134
+
135
+    /**
136
+     * @throws \OCP\AppFramework\QueryException
137
+     */
138
+    public function testSystemdLog(): void {
139
+        $this->c->expects($this->once())
140
+            ->method('resolve')
141
+            ->with(Systemdlog::class)
142
+            ->willReturn($this->createMock(Systemdlog::class));
143
+
144
+        $log = $this->factory->get('systemd');
145
+        $this->assertInstanceOf(Systemdlog::class, $log);
146
+    }
147 147
 }
Please login to merge, or discard this patch.