Completed
Push — master ( fafc07...340ea1 )
by
unknown
42:03
created
tests/lib/Cache/FileCacheTest.php 1 patch
Indentation   +129 added lines, -129 removed lines patch added patch discarded remove patch
@@ -29,133 +29,133 @@
 block discarded – undo
29 29
  */
30 30
 #[\PHPUnit\Framework\Attributes\Group('DB')]
31 31
 class FileCacheTest extends TestCache {
32
-	use UserTrait;
33
-
34
-	/**
35
-	 * @var string
36
-	 * */
37
-	private $user;
38
-	/**
39
-	 * @var string
40
-	 * */
41
-	private $datadir;
42
-	/**
43
-	 * @var Storage
44
-	 * */
45
-	private $storage;
46
-	/**
47
-	 * @var View
48
-	 * */
49
-	private $rootView;
50
-
51
-	public function skip() {
52
-		//$this->skipUnless(OC_User::isLoggedIn());
53
-	}
54
-
55
-	protected function setUp(): void {
56
-		parent::setUp();
57
-
58
-		//login
59
-		$this->createUser('test', 'test');
60
-
61
-		$this->user = \OC_User::getUser();
62
-		\OC_User::setUserId('test');
63
-
64
-		//clear all proxies and hooks so we can do clean testing
65
-		\OC_Hook::clear('OC_Filesystem');
66
-
67
-		/** @var IMountManager $manager */
68
-		$manager = Server::get(IMountManager::class);
69
-		$manager->removeMount('/test');
70
-
71
-		$storage = new Temporary([]);
72
-		Filesystem::mount($storage, [], '/test/cache');
73
-
74
-		//set up the users dir
75
-		$this->rootView = new View('');
76
-		$this->rootView->mkdir('/test');
77
-
78
-		$this->instance = new File();
79
-
80
-		// forces creation of cache folder for subsequent tests
81
-		$this->instance->set('hack', 'hack');
82
-	}
83
-
84
-	protected function tearDown(): void {
85
-		if ($this->instance) {
86
-			$this->instance->remove('hack', 'hack');
87
-		}
88
-
89
-		\OC_User::setUserId($this->user);
90
-
91
-		if ($this->instance) {
92
-			$this->instance->clear();
93
-			$this->instance = null;
94
-		}
95
-
96
-		parent::tearDown();
97
-	}
98
-
99
-	private function setupMockStorage() {
100
-		$mockStorage = $this->getMockBuilder(Local::class)
101
-			->onlyMethods(['filemtime', 'unlink'])
102
-			->setConstructorArgs([['datadir' => Server::get(ITempManager::class)->getTemporaryFolder()]])
103
-			->getMock();
104
-
105
-		Filesystem::mount($mockStorage, [], '/test/cache');
106
-
107
-		return $mockStorage;
108
-	}
109
-
110
-	public function testGarbageCollectOldKeys(): void {
111
-		$mockStorage = $this->setupMockStorage();
112
-
113
-		$mockStorage->expects($this->atLeastOnce())
114
-			->method('filemtime')
115
-			->willReturn(100);
116
-		$mockStorage->expects($this->once())
117
-			->method('unlink')
118
-			->with('key1')
119
-			->willReturn(true);
120
-
121
-		$this->instance->set('key1', 'value1');
122
-		$this->instance->gc();
123
-	}
124
-
125
-	public function testGarbageCollectLeaveRecentKeys(): void {
126
-		$mockStorage = $this->setupMockStorage();
127
-
128
-		$mockStorage->expects($this->atLeastOnce())
129
-			->method('filemtime')
130
-			->willReturn(time() + 3600);
131
-		$mockStorage->expects($this->never())
132
-			->method('unlink')
133
-			->with('key1');
134
-		$this->instance->set('key1', 'value1');
135
-		$this->instance->gc();
136
-	}
137
-
138
-	public static function lockExceptionProvider(): array {
139
-		return [
140
-			[new LockedException('key1')],
141
-			[new LockNotAcquiredException('key1', 1)],
142
-		];
143
-	}
144
-
145
-	#[\PHPUnit\Framework\Attributes\DataProvider('lockExceptionProvider')]
146
-	public function testGarbageCollectIgnoreLockedKeys($testException): void {
147
-		$mockStorage = $this->setupMockStorage();
148
-
149
-		$mockStorage->expects($this->atLeastOnce())
150
-			->method('filemtime')
151
-			->willReturn(100);
152
-		$mockStorage->expects($this->atLeastOnce())
153
-			->method('unlink')
154
-			->willReturnOnConsecutiveCalls($this->throwException($testException), true);
155
-
156
-		$this->instance->set('key1', 'value1');
157
-		$this->instance->set('key2', 'value2');
158
-
159
-		$this->instance->gc();
160
-	}
32
+    use UserTrait;
33
+
34
+    /**
35
+     * @var string
36
+     * */
37
+    private $user;
38
+    /**
39
+     * @var string
40
+     * */
41
+    private $datadir;
42
+    /**
43
+     * @var Storage
44
+     * */
45
+    private $storage;
46
+    /**
47
+     * @var View
48
+     * */
49
+    private $rootView;
50
+
51
+    public function skip() {
52
+        //$this->skipUnless(OC_User::isLoggedIn());
53
+    }
54
+
55
+    protected function setUp(): void {
56
+        parent::setUp();
57
+
58
+        //login
59
+        $this->createUser('test', 'test');
60
+
61
+        $this->user = \OC_User::getUser();
62
+        \OC_User::setUserId('test');
63
+
64
+        //clear all proxies and hooks so we can do clean testing
65
+        \OC_Hook::clear('OC_Filesystem');
66
+
67
+        /** @var IMountManager $manager */
68
+        $manager = Server::get(IMountManager::class);
69
+        $manager->removeMount('/test');
70
+
71
+        $storage = new Temporary([]);
72
+        Filesystem::mount($storage, [], '/test/cache');
73
+
74
+        //set up the users dir
75
+        $this->rootView = new View('');
76
+        $this->rootView->mkdir('/test');
77
+
78
+        $this->instance = new File();
79
+
80
+        // forces creation of cache folder for subsequent tests
81
+        $this->instance->set('hack', 'hack');
82
+    }
83
+
84
+    protected function tearDown(): void {
85
+        if ($this->instance) {
86
+            $this->instance->remove('hack', 'hack');
87
+        }
88
+
89
+        \OC_User::setUserId($this->user);
90
+
91
+        if ($this->instance) {
92
+            $this->instance->clear();
93
+            $this->instance = null;
94
+        }
95
+
96
+        parent::tearDown();
97
+    }
98
+
99
+    private function setupMockStorage() {
100
+        $mockStorage = $this->getMockBuilder(Local::class)
101
+            ->onlyMethods(['filemtime', 'unlink'])
102
+            ->setConstructorArgs([['datadir' => Server::get(ITempManager::class)->getTemporaryFolder()]])
103
+            ->getMock();
104
+
105
+        Filesystem::mount($mockStorage, [], '/test/cache');
106
+
107
+        return $mockStorage;
108
+    }
109
+
110
+    public function testGarbageCollectOldKeys(): void {
111
+        $mockStorage = $this->setupMockStorage();
112
+
113
+        $mockStorage->expects($this->atLeastOnce())
114
+            ->method('filemtime')
115
+            ->willReturn(100);
116
+        $mockStorage->expects($this->once())
117
+            ->method('unlink')
118
+            ->with('key1')
119
+            ->willReturn(true);
120
+
121
+        $this->instance->set('key1', 'value1');
122
+        $this->instance->gc();
123
+    }
124
+
125
+    public function testGarbageCollectLeaveRecentKeys(): void {
126
+        $mockStorage = $this->setupMockStorage();
127
+
128
+        $mockStorage->expects($this->atLeastOnce())
129
+            ->method('filemtime')
130
+            ->willReturn(time() + 3600);
131
+        $mockStorage->expects($this->never())
132
+            ->method('unlink')
133
+            ->with('key1');
134
+        $this->instance->set('key1', 'value1');
135
+        $this->instance->gc();
136
+    }
137
+
138
+    public static function lockExceptionProvider(): array {
139
+        return [
140
+            [new LockedException('key1')],
141
+            [new LockNotAcquiredException('key1', 1)],
142
+        ];
143
+    }
144
+
145
+    #[\PHPUnit\Framework\Attributes\DataProvider('lockExceptionProvider')]
146
+    public function testGarbageCollectIgnoreLockedKeys($testException): void {
147
+        $mockStorage = $this->setupMockStorage();
148
+
149
+        $mockStorage->expects($this->atLeastOnce())
150
+            ->method('filemtime')
151
+            ->willReturn(100);
152
+        $mockStorage->expects($this->atLeastOnce())
153
+            ->method('unlink')
154
+            ->willReturnOnConsecutiveCalls($this->throwException($testException), true);
155
+
156
+        $this->instance->set('key1', 'value1');
157
+        $this->instance->set('key2', 'value2');
158
+
159
+        $this->instance->gc();
160
+    }
161 161
 }
Please login to merge, or discard this patch.
tests/lib/User/ManagerTest.php 1 patch
Indentation   +766 added lines, -766 removed lines patch added patch discarded remove patch
@@ -32,770 +32,770 @@
 block discarded – undo
32 32
  */
33 33
 #[\PHPUnit\Framework\Attributes\Group('DB')]
34 34
 class ManagerTest extends TestCase {
35
-	private IConfig&MockObject $config;
36
-	private IEventDispatcher&MockObject $eventDispatcher;
37
-	private ICacheFactory&MockObject $cacheFactory;
38
-	private ICache&MockObject $cache;
39
-	private LoggerInterface&MockObject $logger;
40
-
41
-	protected function setUp(): void {
42
-		parent::setUp();
43
-
44
-		$this->config = $this->createMock(IConfig::class);
45
-		$this->eventDispatcher = $this->createMock(IEventDispatcher::class);
46
-		$this->cacheFactory = $this->createMock(ICacheFactory::class);
47
-		$this->cache = $this->createMock(ICache::class);
48
-		$this->logger = $this->createMock(LoggerInterface::class);
49
-
50
-		$this->cacheFactory->method('createDistributed')
51
-			->willReturn($this->cache);
52
-	}
53
-
54
-	public function testGetBackends(): void {
55
-		$userDummyBackend = $this->createMock(\Test\Util\User\Dummy::class);
56
-		$manager = new \OC\User\Manager($this->config, $this->cacheFactory, $this->eventDispatcher, $this->logger);
57
-		$manager->registerBackend($userDummyBackend);
58
-		$this->assertEquals([$userDummyBackend], $manager->getBackends());
59
-		$dummyDatabaseBackend = $this->createMock(Database::class);
60
-		$manager->registerBackend($dummyDatabaseBackend);
61
-		$this->assertEquals([$userDummyBackend, $dummyDatabaseBackend], $manager->getBackends());
62
-	}
63
-
64
-
65
-	public function testUserExistsSingleBackendExists(): void {
66
-		/**
67
-		 * @var \Test\Util\User\Dummy&MockObject $backend
68
-		 */
69
-		$backend = $this->createMock(\Test\Util\User\Dummy::class);
70
-		$backend->expects($this->once())
71
-			->method('userExists')
72
-			->with($this->equalTo('foo'))
73
-			->willReturn(true);
74
-
75
-		$manager = new \OC\User\Manager($this->config, $this->cacheFactory, $this->eventDispatcher, $this->logger);
76
-		$manager->registerBackend($backend);
77
-
78
-		$this->assertTrue($manager->userExists('foo'));
79
-	}
80
-
81
-	public function testUserExistsTooLong(): void {
82
-		/** @var \Test\Util\User\Dummy|MockObject $backend */
83
-		$backend = $this->createMock(\Test\Util\User\Dummy::class);
84
-		$backend->expects($this->never())
85
-			->method('userExists')
86
-			->with($this->equalTo('foo'))
87
-			->willReturn(true);
88
-
89
-		$manager = new \OC\User\Manager($this->config, $this->cacheFactory, $this->eventDispatcher, $this->logger);
90
-		$manager->registerBackend($backend);
91
-
92
-		$this->assertFalse($manager->userExists('foo' . str_repeat('a', 62)));
93
-	}
94
-
95
-	public function testUserExistsSingleBackendNotExists(): void {
96
-		/**
97
-		 * @var \Test\Util\User\Dummy&MockObject $backend
98
-		 */
99
-		$backend = $this->createMock(\Test\Util\User\Dummy::class);
100
-		$backend->expects($this->once())
101
-			->method('userExists')
102
-			->with($this->equalTo('foo'))
103
-			->willReturn(false);
104
-
105
-		$manager = new \OC\User\Manager($this->config, $this->cacheFactory, $this->eventDispatcher, $this->logger);
106
-		$manager->registerBackend($backend);
107
-
108
-		$this->assertFalse($manager->userExists('foo'));
109
-	}
110
-
111
-	public function testUserExistsNoBackends(): void {
112
-		$manager = new \OC\User\Manager($this->config, $this->cacheFactory, $this->eventDispatcher, $this->logger);
113
-
114
-		$this->assertFalse($manager->userExists('foo'));
115
-	}
116
-
117
-	public function testUserExistsTwoBackendsSecondExists(): void {
118
-		/**
119
-		 * @var \Test\Util\User\Dummy&MockObject $backend1
120
-		 */
121
-		$backend1 = $this->createMock(\Test\Util\User\Dummy::class);
122
-		$backend1->expects($this->once())
123
-			->method('userExists')
124
-			->with($this->equalTo('foo'))
125
-			->willReturn(false);
126
-
127
-		/**
128
-		 * @var \Test\Util\User\Dummy&MockObject $backend2
129
-		 */
130
-		$backend2 = $this->createMock(\Test\Util\User\Dummy::class);
131
-		$backend2->expects($this->once())
132
-			->method('userExists')
133
-			->with($this->equalTo('foo'))
134
-			->willReturn(true);
135
-
136
-		$manager = new \OC\User\Manager($this->config, $this->cacheFactory, $this->eventDispatcher, $this->logger);
137
-		$manager->registerBackend($backend1);
138
-		$manager->registerBackend($backend2);
139
-
140
-		$this->assertTrue($manager->userExists('foo'));
141
-	}
142
-
143
-	public function testUserExistsTwoBackendsFirstExists(): void {
144
-		/**
145
-		 * @var \Test\Util\User\Dummy&MockObject $backend1
146
-		 */
147
-		$backend1 = $this->createMock(\Test\Util\User\Dummy::class);
148
-		$backend1->expects($this->once())
149
-			->method('userExists')
150
-			->with($this->equalTo('foo'))
151
-			->willReturn(true);
152
-
153
-		/**
154
-		 * @var \Test\Util\User\Dummy&MockObject $backend2
155
-		 */
156
-		$backend2 = $this->createMock(\Test\Util\User\Dummy::class);
157
-		$backend2->expects($this->never())
158
-			->method('userExists');
159
-
160
-		$manager = new \OC\User\Manager($this->config, $this->cacheFactory, $this->eventDispatcher, $this->logger);
161
-		$manager->registerBackend($backend1);
162
-		$manager->registerBackend($backend2);
163
-
164
-		$this->assertTrue($manager->userExists('foo'));
165
-	}
166
-
167
-	public function testCheckPassword(): void {
168
-		/**
169
-		 * @var \OC\User\Backend&MockObject $backend
170
-		 */
171
-		$backend = $this->createMock(\Test\Util\User\Dummy::class);
172
-		$backend->expects($this->once())
173
-			->method('checkPassword')
174
-			->with($this->equalTo('foo'), $this->equalTo('bar'))
175
-			->willReturn(true);
176
-
177
-		$backend->expects($this->any())
178
-			->method('implementsActions')
179
-			->willReturnCallback(function ($actions) {
180
-				if ($actions === BACKEND::CHECK_PASSWORD) {
181
-					return true;
182
-				} else {
183
-					return false;
184
-				}
185
-			});
186
-
187
-		$manager = new \OC\User\Manager($this->config, $this->cacheFactory, $this->eventDispatcher, $this->logger);
188
-		$manager->registerBackend($backend);
189
-
190
-		$user = $manager->checkPassword('foo', 'bar');
191
-		$this->assertTrue($user instanceof User);
192
-	}
193
-
194
-	public function testCheckPasswordNotSupported(): void {
195
-		/**
196
-		 * @var \OC\User\Backend&MockObject $backend
197
-		 */
198
-		$backend = $this->createMock(\Test\Util\User\Dummy::class);
199
-		$backend->expects($this->never())
200
-			->method('checkPassword');
201
-
202
-		$backend->expects($this->any())
203
-			->method('implementsActions')
204
-			->willReturn(false);
205
-
206
-		$manager = new \OC\User\Manager($this->config, $this->cacheFactory, $this->eventDispatcher, $this->logger);
207
-		$manager->registerBackend($backend);
208
-
209
-		$this->assertFalse($manager->checkPassword('foo', 'bar'));
210
-	}
211
-
212
-	public function testGetOneBackendExists(): void {
213
-		/**
214
-		 * @var \Test\Util\User\Dummy&MockObject $backend
215
-		 */
216
-		$backend = $this->createMock(\Test\Util\User\Dummy::class);
217
-		$backend->expects($this->once())
218
-			->method('userExists')
219
-			->with($this->equalTo('foo'))
220
-			->willReturn(true);
221
-		$backend->expects($this->never())
222
-			->method('loginName2UserName');
223
-
224
-		$manager = new \OC\User\Manager($this->config, $this->cacheFactory, $this->eventDispatcher, $this->logger);
225
-		$manager->registerBackend($backend);
226
-
227
-		$this->assertEquals('foo', $manager->get('foo')->getUID());
228
-	}
229
-
230
-	public function testGetOneBackendNotExists(): void {
231
-		/**
232
-		 * @var \Test\Util\User\Dummy&MockObject $backend
233
-		 */
234
-		$backend = $this->createMock(\Test\Util\User\Dummy::class);
235
-		$backend->expects($this->once())
236
-			->method('userExists')
237
-			->with($this->equalTo('foo'))
238
-			->willReturn(false);
239
-
240
-		$manager = new \OC\User\Manager($this->config, $this->cacheFactory, $this->eventDispatcher, $this->logger);
241
-		$manager->registerBackend($backend);
242
-
243
-		$this->assertEquals(null, $manager->get('foo'));
244
-	}
245
-
246
-	public function testGetTooLong(): void {
247
-		/** @var \Test\Util\User\Dummy|MockObject $backend */
248
-		$backend = $this->createMock(\Test\Util\User\Dummy::class);
249
-		$backend->expects($this->never())
250
-			->method('userExists')
251
-			->with($this->equalTo('foo'))
252
-			->willReturn(false);
253
-
254
-		$manager = new \OC\User\Manager($this->config, $this->cacheFactory, $this->eventDispatcher, $this->logger);
255
-		$manager->registerBackend($backend);
256
-
257
-		$this->assertEquals(null, $manager->get('foo' . str_repeat('a', 62)));
258
-	}
259
-
260
-	public function testGetOneBackendDoNotTranslateLoginNames(): void {
261
-		/**
262
-		 * @var \Test\Util\User\Dummy&MockObject $backend
263
-		 */
264
-		$backend = $this->createMock(\Test\Util\User\Dummy::class);
265
-		$backend->expects($this->once())
266
-			->method('userExists')
267
-			->with($this->equalTo('bLeNdEr'))
268
-			->willReturn(true);
269
-		$backend->expects($this->never())
270
-			->method('loginName2UserName');
271
-
272
-		$manager = new \OC\User\Manager($this->config, $this->cacheFactory, $this->eventDispatcher, $this->logger);
273
-		$manager->registerBackend($backend);
274
-
275
-		$this->assertEquals('bLeNdEr', $manager->get('bLeNdEr')->getUID());
276
-	}
277
-
278
-	public function testSearchOneBackend(): void {
279
-		/**
280
-		 * @var \Test\Util\User\Dummy&MockObject $backend
281
-		 */
282
-		$backend = $this->createMock(\Test\Util\User\Dummy::class);
283
-		$backend->expects($this->once())
284
-			->method('getUsers')
285
-			->with($this->equalTo('fo'))
286
-			->willReturn(['foo', 'afoo', 'Afoo1', 'Bfoo']);
287
-		$backend->expects($this->never())
288
-			->method('loginName2UserName');
289
-
290
-		$manager = new \OC\User\Manager($this->config, $this->cacheFactory, $this->eventDispatcher, $this->logger);
291
-		$manager->registerBackend($backend);
292
-
293
-		$result = $manager->search('fo');
294
-		$this->assertEquals(4, count($result));
295
-		$this->assertEquals('afoo', array_shift($result)->getUID());
296
-		$this->assertEquals('Afoo1', array_shift($result)->getUID());
297
-		$this->assertEquals('Bfoo', array_shift($result)->getUID());
298
-		$this->assertEquals('foo', array_shift($result)->getUID());
299
-	}
300
-
301
-	public function testSearchTwoBackendLimitOffset(): void {
302
-		/**
303
-		 * @var \Test\Util\User\Dummy&MockObject $backend1
304
-		 */
305
-		$backend1 = $this->createMock(\Test\Util\User\Dummy::class);
306
-		$backend1->expects($this->once())
307
-			->method('getUsers')
308
-			->with($this->equalTo('fo'), $this->equalTo(3), $this->equalTo(1))
309
-			->willReturn(['foo1', 'foo2']);
310
-		$backend1->expects($this->never())
311
-			->method('loginName2UserName');
312
-
313
-		/**
314
-		 * @var \Test\Util\User\Dummy&MockObject $backend2
315
-		 */
316
-		$backend2 = $this->createMock(\Test\Util\User\Dummy::class);
317
-		$backend2->expects($this->once())
318
-			->method('getUsers')
319
-			->with($this->equalTo('fo'), $this->equalTo(3), $this->equalTo(1))
320
-			->willReturn(['foo3']);
321
-		$backend2->expects($this->never())
322
-			->method('loginName2UserName');
323
-
324
-		$manager = new \OC\User\Manager($this->config, $this->cacheFactory, $this->eventDispatcher, $this->logger);
325
-		$manager->registerBackend($backend1);
326
-		$manager->registerBackend($backend2);
327
-
328
-		$result = $manager->search('fo', 3, 1);
329
-		$this->assertEquals(3, count($result));
330
-		$this->assertEquals('foo1', array_shift($result)->getUID());
331
-		$this->assertEquals('foo2', array_shift($result)->getUID());
332
-		$this->assertEquals('foo3', array_shift($result)->getUID());
333
-	}
334
-
335
-	public static function dataCreateUserInvalid(): array {
336
-		return [
337
-			['te?st', 'foo', 'Only the following characters are allowed in a username:'
338
-				. ' "a-z", "A-Z", "0-9", spaces and "_.@-\'"'],
339
-			["te\tst", '', 'Only the following characters are allowed in a username:'
340
-				. ' "a-z", "A-Z", "0-9", spaces and "_.@-\'"'],
341
-			["te\nst", '', 'Only the following characters are allowed in a username:'
342
-				. ' "a-z", "A-Z", "0-9", spaces and "_.@-\'"'],
343
-			["te\rst", '', 'Only the following characters are allowed in a username:'
344
-				. ' "a-z", "A-Z", "0-9", spaces and "_.@-\'"'],
345
-			["te\0st", '', 'Only the following characters are allowed in a username:'
346
-				. ' "a-z", "A-Z", "0-9", spaces and "_.@-\'"'],
347
-			["te\x0Bst", '', 'Only the following characters are allowed in a username:'
348
-				. ' "a-z", "A-Z", "0-9", spaces and "_.@-\'"'],
349
-			["te\xe2st", '', 'Only the following characters are allowed in a username:'
350
-				. ' "a-z", "A-Z", "0-9", spaces and "_.@-\'"'],
351
-			["te\x80st", '', 'Only the following characters are allowed in a username:'
352
-				. ' "a-z", "A-Z", "0-9", spaces and "_.@-\'"'],
353
-			["te\x8bst", '', 'Only the following characters are allowed in a username:'
354
-				. ' "a-z", "A-Z", "0-9", spaces and "_.@-\'"'],
355
-			['', 'foo', 'A valid username must be provided'],
356
-			[' ', 'foo', 'A valid username must be provided'],
357
-			[' test', 'foo', 'Username contains whitespace at the beginning or at the end'],
358
-			['test ', 'foo', 'Username contains whitespace at the beginning or at the end'],
359
-			['.', 'foo', 'Username must not consist of dots only'],
360
-			['..', 'foo', 'Username must not consist of dots only'],
361
-			['.test', '', 'A valid password must be provided'],
362
-			['test', '', 'A valid password must be provided'],
363
-			['test' . str_repeat('a', 61), '', 'Login is too long'],
364
-		];
365
-	}
366
-
367
-	#[\PHPUnit\Framework\Attributes\DataProvider('dataCreateUserInvalid')]
368
-	public function testCreateUserInvalid($uid, $password, $exception): void {
369
-		/** @var \Test\Util\User\Dummy&MockObject $backend */
370
-		$backend = $this->createMock(\Test\Util\User\Dummy::class);
371
-		$backend->expects($this->once())
372
-			->method('implementsActions')
373
-			->with(\OC\User\Backend::CREATE_USER)
374
-			->willReturn(true);
375
-
376
-
377
-		$manager = new \OC\User\Manager($this->config, $this->cacheFactory, $this->eventDispatcher, $this->logger);
378
-		$manager->registerBackend($backend);
379
-
380
-		$this->expectException(\InvalidArgumentException::class, $exception);
381
-		$manager->createUser($uid, $password);
382
-	}
383
-
384
-	public function testCreateUserSingleBackendNotExists(): void {
385
-		/**
386
-		 * @var \Test\Util\User\Dummy&MockObject $backend
387
-		 */
388
-		$backend = $this->createMock(\Test\Util\User\Dummy::class);
389
-		$backend->expects($this->any())
390
-			->method('implementsActions')
391
-			->willReturn(true);
392
-
393
-		$backend->expects($this->once())
394
-			->method('createUser')
395
-			->with($this->equalTo('foo'), $this->equalTo('bar'));
396
-
397
-		$backend->expects($this->once())
398
-			->method('userExists')
399
-			->with($this->equalTo('foo'))
400
-			->willReturn(false);
401
-		$backend->expects($this->never())
402
-			->method('loginName2UserName');
403
-
404
-		$manager = new \OC\User\Manager($this->config, $this->cacheFactory, $this->eventDispatcher, $this->logger);
405
-		$manager->registerBackend($backend);
406
-
407
-		$user = $manager->createUser('foo', 'bar');
408
-		$this->assertEquals('foo', $user->getUID());
409
-	}
410
-
411
-
412
-	public function testCreateUserSingleBackendExists(): void {
413
-		$this->expectException(\Exception::class);
414
-
415
-		/**
416
-		 * @var \Test\Util\User\Dummy&MockObject $backend
417
-		 */
418
-		$backend = $this->createMock(\Test\Util\User\Dummy::class);
419
-		$backend->expects($this->any())
420
-			->method('implementsActions')
421
-			->willReturn(true);
422
-
423
-		$backend->expects($this->never())
424
-			->method('createUser');
425
-
426
-		$backend->expects($this->once())
427
-			->method('userExists')
428
-			->with($this->equalTo('foo'))
429
-			->willReturn(true);
430
-
431
-		$manager = new \OC\User\Manager($this->config, $this->cacheFactory, $this->eventDispatcher, $this->logger);
432
-		$manager->registerBackend($backend);
433
-
434
-		$manager->createUser('foo', 'bar');
435
-	}
436
-
437
-	public function testCreateUserSingleBackendNotSupported(): void {
438
-		/**
439
-		 * @var \Test\Util\User\Dummy&MockObject $backend
440
-		 */
441
-		$backend = $this->createMock(\Test\Util\User\Dummy::class);
442
-		$backend->expects($this->any())
443
-			->method('implementsActions')
444
-			->willReturn(false);
445
-
446
-		$backend->expects($this->never())
447
-			->method('createUser');
448
-
449
-		$backend->expects($this->never())
450
-			->method('userExists');
451
-
452
-		$manager = new \OC\User\Manager($this->config, $this->cacheFactory, $this->eventDispatcher, $this->logger);
453
-		$manager->registerBackend($backend);
454
-
455
-		$this->assertFalse($manager->createUser('foo', 'bar'));
456
-	}
457
-
458
-	public function testCreateUserNoBackends(): void {
459
-		$manager = new \OC\User\Manager($this->config, $this->cacheFactory, $this->eventDispatcher, $this->logger);
460
-
461
-		$this->assertFalse($manager->createUser('foo', 'bar'));
462
-	}
463
-
464
-
465
-	public function testCreateUserFromBackendWithBackendError(): void {
466
-		$this->expectException(\InvalidArgumentException::class);
467
-		$this->expectExceptionMessage('Could not create account');
468
-
469
-		/** @var \Test\Util\User\Dummy&MockObject $backend */
470
-		$backend = $this->createMock(\Test\Util\User\Dummy::class);
471
-		$backend
472
-			->expects($this->once())
473
-			->method('createUser')
474
-			->with('MyUid', 'MyPassword')
475
-			->willReturn(false);
476
-
477
-		$manager = new Manager($this->config, $this->cacheFactory, $this->eventDispatcher, $this->logger);
478
-		$manager->createUserFromBackend('MyUid', 'MyPassword', $backend);
479
-	}
480
-
481
-
482
-	public function testCreateUserTwoBackendExists(): void {
483
-		$this->expectException(\Exception::class);
484
-
485
-		/**
486
-		 * @var \Test\Util\User\Dummy&MockObject $backend1
487
-		 */
488
-		$backend1 = $this->createMock(\Test\Util\User\Dummy::class);
489
-		$backend1->expects($this->any())
490
-			->method('implementsActions')
491
-			->willReturn(true);
492
-
493
-		$backend1->expects($this->never())
494
-			->method('createUser');
495
-
496
-		$backend1->expects($this->once())
497
-			->method('userExists')
498
-			->with($this->equalTo('foo'))
499
-			->willReturn(false);
500
-
501
-		/**
502
-		 * @var \Test\Util\User\Dummy&MockObject $backend2
503
-		 */
504
-		$backend2 = $this->createMock(\Test\Util\User\Dummy::class);
505
-		$backend2->expects($this->any())
506
-			->method('implementsActions')
507
-			->willReturn(true);
508
-
509
-		$backend2->expects($this->never())
510
-			->method('createUser');
511
-
512
-		$backend2->expects($this->once())
513
-			->method('userExists')
514
-			->with($this->equalTo('foo'))
515
-			->willReturn(true);
516
-
517
-		$manager = new \OC\User\Manager($this->config, $this->cacheFactory, $this->eventDispatcher, $this->logger);
518
-		$manager->registerBackend($backend1);
519
-		$manager->registerBackend($backend2);
520
-
521
-		$manager->createUser('foo', 'bar');
522
-	}
523
-
524
-	public function testCountUsersNoBackend(): void {
525
-		$manager = new \OC\User\Manager($this->config, $this->cacheFactory, $this->eventDispatcher, $this->logger);
526
-
527
-		$result = $manager->countUsers();
528
-		$this->assertTrue(is_array($result));
529
-		$this->assertTrue(empty($result));
530
-	}
531
-
532
-	public function testCountUsersOneBackend(): void {
533
-		/**
534
-		 * @var \Test\Util\User\Dummy&MockObject $backend
535
-		 */
536
-		$backend = $this->createMock(\Test\Util\User\Dummy::class);
537
-		$backend->expects($this->once())
538
-			->method('countUsers')
539
-			->willReturn(7);
540
-
541
-		$backend->expects($this->once())
542
-			->method('implementsActions')
543
-			->with(BACKEND::COUNT_USERS)
544
-			->willReturn(true);
545
-
546
-		$backend->expects($this->once())
547
-			->method('getBackendName')
548
-			->willReturn('Mock_Test_Util_User_Dummy');
549
-
550
-		$manager = new \OC\User\Manager($this->config, $this->cacheFactory, $this->eventDispatcher, $this->logger);
551
-		$manager->registerBackend($backend);
552
-
553
-		$result = $manager->countUsers();
554
-		$keys = array_keys($result);
555
-		$this->assertTrue(strpos($keys[0], 'Mock_Test_Util_User_Dummy') !== false);
556
-
557
-		$users = array_shift($result);
558
-		$this->assertEquals(7, $users);
559
-	}
560
-
561
-	public function testCountUsersTwoBackends(): void {
562
-		/**
563
-		 * @var \Test\Util\User\Dummy&MockObject $backend
564
-		 */
565
-		$backend1 = $this->createMock(\Test\Util\User\Dummy::class);
566
-		$backend1->expects($this->once())
567
-			->method('countUsers')
568
-			->willReturn(7);
569
-
570
-		$backend1->expects($this->once())
571
-			->method('implementsActions')
572
-			->with(BACKEND::COUNT_USERS)
573
-			->willReturn(true);
574
-		$backend1->expects($this->once())
575
-			->method('getBackendName')
576
-			->willReturn('Mock_Test_Util_User_Dummy');
577
-
578
-		$backend2 = $this->createMock(\Test\Util\User\Dummy::class);
579
-		$backend2->expects($this->once())
580
-			->method('countUsers')
581
-			->willReturn(16);
582
-
583
-		$backend2->expects($this->once())
584
-			->method('implementsActions')
585
-			->with(BACKEND::COUNT_USERS)
586
-			->willReturn(true);
587
-		$backend2->expects($this->once())
588
-			->method('getBackendName')
589
-			->willReturn('Mock_Test_Util_User_Dummy');
590
-
591
-		$manager = new \OC\User\Manager($this->config, $this->cacheFactory, $this->eventDispatcher, $this->logger);
592
-		$manager->registerBackend($backend1);
593
-		$manager->registerBackend($backend2);
594
-
595
-		$result = $manager->countUsers();
596
-		//because the backends have the same class name, only one value expected
597
-		$this->assertEquals(1, count($result));
598
-		$keys = array_keys($result);
599
-		$this->assertTrue(strpos($keys[0], 'Mock_Test_Util_User_Dummy') !== false);
600
-
601
-		$users = array_shift($result);
602
-		//users from backends shall be summed up
603
-		$this->assertEquals(7 + 16, $users);
604
-	}
605
-
606
-	public function testCountUsersOnlyDisabled(): void {
607
-		$manager = Server::get(IUserManager::class);
608
-		// count other users in the db before adding our own
609
-		$countBefore = $manager->countDisabledUsers();
610
-
611
-		//Add test users
612
-		$user1 = $manager->createUser('testdisabledcount1', 'testdisabledcount1');
613
-
614
-		$user2 = $manager->createUser('testdisabledcount2', 'testdisabledcount2');
615
-		$user2->setEnabled(false);
616
-
617
-		$user3 = $manager->createUser('testdisabledcount3', 'testdisabledcount3');
618
-
619
-		$user4 = $manager->createUser('testdisabledcount4', 'testdisabledcount4');
620
-		$user4->setEnabled(false);
621
-
622
-		$this->assertEquals($countBefore + 2, $manager->countDisabledUsers());
623
-
624
-		//cleanup
625
-		$user1->delete();
626
-		$user2->delete();
627
-		$user3->delete();
628
-		$user4->delete();
629
-	}
630
-
631
-	public function testCountUsersOnlySeen(): void {
632
-		$manager = Server::get(IUserManager::class);
633
-		// count other users in the db before adding our own
634
-		$countBefore = $manager->countSeenUsers();
635
-
636
-		//Add test users
637
-		$user1 = $manager->createUser('testseencount1', 'testseencount1');
638
-		$user1->updateLastLoginTimestamp();
639
-
640
-		$user2 = $manager->createUser('testseencount2', 'testseencount2');
641
-		$user2->updateLastLoginTimestamp();
642
-
643
-		$user3 = $manager->createUser('testseencount3', 'testseencount3');
644
-
645
-		$user4 = $manager->createUser('testseencount4', 'testseencount4');
646
-		$user4->updateLastLoginTimestamp();
647
-
648
-		$this->assertEquals($countBefore + 3, $manager->countSeenUsers());
649
-
650
-		//cleanup
651
-		$user1->delete();
652
-		$user2->delete();
653
-		$user3->delete();
654
-		$user4->delete();
655
-	}
656
-
657
-	public function testCallForSeenUsers(): void {
658
-		$manager = Server::get(IUserManager::class);
659
-		// count other users in the db before adding our own
660
-		$count = 0;
661
-		$function = function (IUser $user) use (&$count): void {
662
-			$count++;
663
-		};
664
-		$manager->callForAllUsers($function, '', true);
665
-		$countBefore = $count;
666
-
667
-		//Add test users
668
-		$user1 = $manager->createUser('testseen1', 'testseen10');
669
-		$user1->updateLastLoginTimestamp();
670
-
671
-		$user2 = $manager->createUser('testseen2', 'testseen20');
672
-		$user2->updateLastLoginTimestamp();
673
-
674
-		$user3 = $manager->createUser('testseen3', 'testseen30');
675
-
676
-		$user4 = $manager->createUser('testseen4', 'testseen40');
677
-		$user4->updateLastLoginTimestamp();
678
-
679
-		$count = 0;
680
-		$manager->callForAllUsers($function, '', true);
681
-
682
-		$this->assertEquals($countBefore + 3, $count);
683
-
684
-		//cleanup
685
-		$user1->delete();
686
-		$user2->delete();
687
-		$user3->delete();
688
-		$user4->delete();
689
-	}
690
-
691
-	#[\PHPUnit\Framework\Attributes\RunInSeparateProcess]
692
-	#[\PHPUnit\Framework\Attributes\PreserveGlobalState(enabled: false)]
693
-	public function testRecentlyActive(): void {
694
-		$config = Server::get(IConfig::class);
695
-		$manager = Server::get(IUserManager::class);
696
-
697
-		// Create some users
698
-		$now = (string)time();
699
-		$user1 = $manager->createUser('test_active_1', 'test_active_1');
700
-		$config->setUserValue('test_active_1', 'login', 'lastLogin', $now);
701
-		$user1->setDisplayName('test active 1');
702
-		$user1->setSystemEMailAddress('[email protected]');
703
-
704
-		$user2 = $manager->createUser('TEST_ACTIVE_2_FRED', 'TEST_ACTIVE_2');
705
-		$config->setUserValue('TEST_ACTIVE_2_FRED', 'login', 'lastLogin', $now);
706
-		$user2->setDisplayName('TEST ACTIVE 2 UPPER');
707
-		$user2->setSystemEMailAddress('[email protected]');
708
-
709
-		$user3 = $manager->createUser('test_active_3', 'test_active_3');
710
-		$config->setUserValue('test_active_3', 'login', 'lastLogin', $now + 1);
711
-		$user3->setDisplayName('test active 3');
712
-
713
-		$user4 = $manager->createUser('test_active_4', 'test_active_4');
714
-		$config->setUserValue('test_active_4', 'login', 'lastLogin', $now);
715
-		$user4->setDisplayName('Test Active 4');
716
-
717
-		$user5 = $manager->createUser('test_inactive_1', 'test_inactive_1');
718
-		$user5->setDisplayName('Test Inactive 1');
719
-		$user2->setSystemEMailAddress('[email protected]');
720
-
721
-		// Search recently active
722
-		//  - No search, case-insensitive order
723
-		$users = $manager->getLastLoggedInUsers(4);
724
-		$this->assertEquals(['test_active_3', 'test_active_1', 'TEST_ACTIVE_2_FRED', 'test_active_4'], $users);
725
-		//  - Search, case-insensitive order
726
-		$users = $manager->getLastLoggedInUsers(search: 'act');
727
-		$this->assertEquals(['test_active_3', 'test_active_1', 'TEST_ACTIVE_2_FRED', 'test_active_4'], $users);
728
-		//  - No search with offset
729
-		$users = $manager->getLastLoggedInUsers(2, 2);
730
-		$this->assertEquals(['TEST_ACTIVE_2_FRED', 'test_active_4'], $users);
731
-		//  - Case insensitive search (email)
732
-		$users = $manager->getLastLoggedInUsers(search: 'active.com');
733
-		$this->assertEquals(['test_active_1', 'TEST_ACTIVE_2_FRED'], $users);
734
-		//  - Case insensitive search (display name)
735
-		$users = $manager->getLastLoggedInUsers(search: 'upper');
736
-		$this->assertEquals(['TEST_ACTIVE_2_FRED'], $users);
737
-		//  - Case insensitive search (uid)
738
-		$users = $manager->getLastLoggedInUsers(search: 'fred');
739
-		$this->assertEquals(['TEST_ACTIVE_2_FRED'], $users);
740
-
741
-		// Delete users and config keys
742
-		$user1->delete();
743
-		$user2->delete();
744
-		$user3->delete();
745
-		$user4->delete();
746
-		$user5->delete();
747
-	}
748
-
749
-	public function testDeleteUser(): void {
750
-		/** @var AllConfig&MockObject */
751
-		$config = $this->getMockBuilder(AllConfig::class)
752
-			->disableOriginalConstructor()
753
-			->getMock();
754
-		$config
755
-			->expects($this->any())
756
-			->method('getUserValue')
757
-			->willReturnArgument(3);
758
-		$config
759
-			->expects($this->any())
760
-			->method('getAppValue')
761
-			->willReturnArgument(2);
762
-
763
-		$manager = new \OC\User\Manager($config, $this->cacheFactory, $this->eventDispatcher, $this->logger);
764
-		$backend = new \Test\Util\User\Dummy();
765
-
766
-		$manager->registerBackend($backend);
767
-		$backend->createUser('foo', 'bar');
768
-		$this->assertTrue($manager->userExists('foo'));
769
-		$manager->get('foo')->delete();
770
-		$this->assertFalse($manager->userExists('foo'));
771
-	}
772
-
773
-	public function testGetByEmail(): void {
774
-		/** @var AllConfig&MockObject */
775
-		$config = $this->getMockBuilder(AllConfig::class)
776
-			->disableOriginalConstructor()
777
-			->getMock();
778
-		$config
779
-			->expects($this->once())
780
-			->method('getUsersForUserValueCaseInsensitive')
781
-			->with('settings', 'email', '[email protected]')
782
-			->willReturn(['uid1', 'uid99', 'uid2']);
783
-
784
-		$backend = $this->createMock(\Test\Util\User\Dummy::class);
785
-		$backend->expects($this->exactly(3))
786
-			->method('userExists')
787
-			->willReturnMap([
788
-				['uid1', true],
789
-				['uid99', false],
790
-				['uid2', true]
791
-			]);
792
-
793
-		$manager = new \OC\User\Manager($config, $this->cacheFactory, $this->eventDispatcher, $this->logger);
794
-		$manager->registerBackend($backend);
795
-
796
-		$users = $manager->getByEmail('[email protected]');
797
-		$this->assertCount(2, $users);
798
-		$this->assertEquals('uid1', $users[0]->getUID());
799
-		$this->assertEquals('uid2', $users[1]->getUID());
800
-	}
35
+    private IConfig&MockObject $config;
36
+    private IEventDispatcher&MockObject $eventDispatcher;
37
+    private ICacheFactory&MockObject $cacheFactory;
38
+    private ICache&MockObject $cache;
39
+    private LoggerInterface&MockObject $logger;
40
+
41
+    protected function setUp(): void {
42
+        parent::setUp();
43
+
44
+        $this->config = $this->createMock(IConfig::class);
45
+        $this->eventDispatcher = $this->createMock(IEventDispatcher::class);
46
+        $this->cacheFactory = $this->createMock(ICacheFactory::class);
47
+        $this->cache = $this->createMock(ICache::class);
48
+        $this->logger = $this->createMock(LoggerInterface::class);
49
+
50
+        $this->cacheFactory->method('createDistributed')
51
+            ->willReturn($this->cache);
52
+    }
53
+
54
+    public function testGetBackends(): void {
55
+        $userDummyBackend = $this->createMock(\Test\Util\User\Dummy::class);
56
+        $manager = new \OC\User\Manager($this->config, $this->cacheFactory, $this->eventDispatcher, $this->logger);
57
+        $manager->registerBackend($userDummyBackend);
58
+        $this->assertEquals([$userDummyBackend], $manager->getBackends());
59
+        $dummyDatabaseBackend = $this->createMock(Database::class);
60
+        $manager->registerBackend($dummyDatabaseBackend);
61
+        $this->assertEquals([$userDummyBackend, $dummyDatabaseBackend], $manager->getBackends());
62
+    }
63
+
64
+
65
+    public function testUserExistsSingleBackendExists(): void {
66
+        /**
67
+         * @var \Test\Util\User\Dummy&MockObject $backend
68
+         */
69
+        $backend = $this->createMock(\Test\Util\User\Dummy::class);
70
+        $backend->expects($this->once())
71
+            ->method('userExists')
72
+            ->with($this->equalTo('foo'))
73
+            ->willReturn(true);
74
+
75
+        $manager = new \OC\User\Manager($this->config, $this->cacheFactory, $this->eventDispatcher, $this->logger);
76
+        $manager->registerBackend($backend);
77
+
78
+        $this->assertTrue($manager->userExists('foo'));
79
+    }
80
+
81
+    public function testUserExistsTooLong(): void {
82
+        /** @var \Test\Util\User\Dummy|MockObject $backend */
83
+        $backend = $this->createMock(\Test\Util\User\Dummy::class);
84
+        $backend->expects($this->never())
85
+            ->method('userExists')
86
+            ->with($this->equalTo('foo'))
87
+            ->willReturn(true);
88
+
89
+        $manager = new \OC\User\Manager($this->config, $this->cacheFactory, $this->eventDispatcher, $this->logger);
90
+        $manager->registerBackend($backend);
91
+
92
+        $this->assertFalse($manager->userExists('foo' . str_repeat('a', 62)));
93
+    }
94
+
95
+    public function testUserExistsSingleBackendNotExists(): void {
96
+        /**
97
+         * @var \Test\Util\User\Dummy&MockObject $backend
98
+         */
99
+        $backend = $this->createMock(\Test\Util\User\Dummy::class);
100
+        $backend->expects($this->once())
101
+            ->method('userExists')
102
+            ->with($this->equalTo('foo'))
103
+            ->willReturn(false);
104
+
105
+        $manager = new \OC\User\Manager($this->config, $this->cacheFactory, $this->eventDispatcher, $this->logger);
106
+        $manager->registerBackend($backend);
107
+
108
+        $this->assertFalse($manager->userExists('foo'));
109
+    }
110
+
111
+    public function testUserExistsNoBackends(): void {
112
+        $manager = new \OC\User\Manager($this->config, $this->cacheFactory, $this->eventDispatcher, $this->logger);
113
+
114
+        $this->assertFalse($manager->userExists('foo'));
115
+    }
116
+
117
+    public function testUserExistsTwoBackendsSecondExists(): void {
118
+        /**
119
+         * @var \Test\Util\User\Dummy&MockObject $backend1
120
+         */
121
+        $backend1 = $this->createMock(\Test\Util\User\Dummy::class);
122
+        $backend1->expects($this->once())
123
+            ->method('userExists')
124
+            ->with($this->equalTo('foo'))
125
+            ->willReturn(false);
126
+
127
+        /**
128
+         * @var \Test\Util\User\Dummy&MockObject $backend2
129
+         */
130
+        $backend2 = $this->createMock(\Test\Util\User\Dummy::class);
131
+        $backend2->expects($this->once())
132
+            ->method('userExists')
133
+            ->with($this->equalTo('foo'))
134
+            ->willReturn(true);
135
+
136
+        $manager = new \OC\User\Manager($this->config, $this->cacheFactory, $this->eventDispatcher, $this->logger);
137
+        $manager->registerBackend($backend1);
138
+        $manager->registerBackend($backend2);
139
+
140
+        $this->assertTrue($manager->userExists('foo'));
141
+    }
142
+
143
+    public function testUserExistsTwoBackendsFirstExists(): void {
144
+        /**
145
+         * @var \Test\Util\User\Dummy&MockObject $backend1
146
+         */
147
+        $backend1 = $this->createMock(\Test\Util\User\Dummy::class);
148
+        $backend1->expects($this->once())
149
+            ->method('userExists')
150
+            ->with($this->equalTo('foo'))
151
+            ->willReturn(true);
152
+
153
+        /**
154
+         * @var \Test\Util\User\Dummy&MockObject $backend2
155
+         */
156
+        $backend2 = $this->createMock(\Test\Util\User\Dummy::class);
157
+        $backend2->expects($this->never())
158
+            ->method('userExists');
159
+
160
+        $manager = new \OC\User\Manager($this->config, $this->cacheFactory, $this->eventDispatcher, $this->logger);
161
+        $manager->registerBackend($backend1);
162
+        $manager->registerBackend($backend2);
163
+
164
+        $this->assertTrue($manager->userExists('foo'));
165
+    }
166
+
167
+    public function testCheckPassword(): void {
168
+        /**
169
+         * @var \OC\User\Backend&MockObject $backend
170
+         */
171
+        $backend = $this->createMock(\Test\Util\User\Dummy::class);
172
+        $backend->expects($this->once())
173
+            ->method('checkPassword')
174
+            ->with($this->equalTo('foo'), $this->equalTo('bar'))
175
+            ->willReturn(true);
176
+
177
+        $backend->expects($this->any())
178
+            ->method('implementsActions')
179
+            ->willReturnCallback(function ($actions) {
180
+                if ($actions === BACKEND::CHECK_PASSWORD) {
181
+                    return true;
182
+                } else {
183
+                    return false;
184
+                }
185
+            });
186
+
187
+        $manager = new \OC\User\Manager($this->config, $this->cacheFactory, $this->eventDispatcher, $this->logger);
188
+        $manager->registerBackend($backend);
189
+
190
+        $user = $manager->checkPassword('foo', 'bar');
191
+        $this->assertTrue($user instanceof User);
192
+    }
193
+
194
+    public function testCheckPasswordNotSupported(): void {
195
+        /**
196
+         * @var \OC\User\Backend&MockObject $backend
197
+         */
198
+        $backend = $this->createMock(\Test\Util\User\Dummy::class);
199
+        $backend->expects($this->never())
200
+            ->method('checkPassword');
201
+
202
+        $backend->expects($this->any())
203
+            ->method('implementsActions')
204
+            ->willReturn(false);
205
+
206
+        $manager = new \OC\User\Manager($this->config, $this->cacheFactory, $this->eventDispatcher, $this->logger);
207
+        $manager->registerBackend($backend);
208
+
209
+        $this->assertFalse($manager->checkPassword('foo', 'bar'));
210
+    }
211
+
212
+    public function testGetOneBackendExists(): void {
213
+        /**
214
+         * @var \Test\Util\User\Dummy&MockObject $backend
215
+         */
216
+        $backend = $this->createMock(\Test\Util\User\Dummy::class);
217
+        $backend->expects($this->once())
218
+            ->method('userExists')
219
+            ->with($this->equalTo('foo'))
220
+            ->willReturn(true);
221
+        $backend->expects($this->never())
222
+            ->method('loginName2UserName');
223
+
224
+        $manager = new \OC\User\Manager($this->config, $this->cacheFactory, $this->eventDispatcher, $this->logger);
225
+        $manager->registerBackend($backend);
226
+
227
+        $this->assertEquals('foo', $manager->get('foo')->getUID());
228
+    }
229
+
230
+    public function testGetOneBackendNotExists(): void {
231
+        /**
232
+         * @var \Test\Util\User\Dummy&MockObject $backend
233
+         */
234
+        $backend = $this->createMock(\Test\Util\User\Dummy::class);
235
+        $backend->expects($this->once())
236
+            ->method('userExists')
237
+            ->with($this->equalTo('foo'))
238
+            ->willReturn(false);
239
+
240
+        $manager = new \OC\User\Manager($this->config, $this->cacheFactory, $this->eventDispatcher, $this->logger);
241
+        $manager->registerBackend($backend);
242
+
243
+        $this->assertEquals(null, $manager->get('foo'));
244
+    }
245
+
246
+    public function testGetTooLong(): void {
247
+        /** @var \Test\Util\User\Dummy|MockObject $backend */
248
+        $backend = $this->createMock(\Test\Util\User\Dummy::class);
249
+        $backend->expects($this->never())
250
+            ->method('userExists')
251
+            ->with($this->equalTo('foo'))
252
+            ->willReturn(false);
253
+
254
+        $manager = new \OC\User\Manager($this->config, $this->cacheFactory, $this->eventDispatcher, $this->logger);
255
+        $manager->registerBackend($backend);
256
+
257
+        $this->assertEquals(null, $manager->get('foo' . str_repeat('a', 62)));
258
+    }
259
+
260
+    public function testGetOneBackendDoNotTranslateLoginNames(): void {
261
+        /**
262
+         * @var \Test\Util\User\Dummy&MockObject $backend
263
+         */
264
+        $backend = $this->createMock(\Test\Util\User\Dummy::class);
265
+        $backend->expects($this->once())
266
+            ->method('userExists')
267
+            ->with($this->equalTo('bLeNdEr'))
268
+            ->willReturn(true);
269
+        $backend->expects($this->never())
270
+            ->method('loginName2UserName');
271
+
272
+        $manager = new \OC\User\Manager($this->config, $this->cacheFactory, $this->eventDispatcher, $this->logger);
273
+        $manager->registerBackend($backend);
274
+
275
+        $this->assertEquals('bLeNdEr', $manager->get('bLeNdEr')->getUID());
276
+    }
277
+
278
+    public function testSearchOneBackend(): void {
279
+        /**
280
+         * @var \Test\Util\User\Dummy&MockObject $backend
281
+         */
282
+        $backend = $this->createMock(\Test\Util\User\Dummy::class);
283
+        $backend->expects($this->once())
284
+            ->method('getUsers')
285
+            ->with($this->equalTo('fo'))
286
+            ->willReturn(['foo', 'afoo', 'Afoo1', 'Bfoo']);
287
+        $backend->expects($this->never())
288
+            ->method('loginName2UserName');
289
+
290
+        $manager = new \OC\User\Manager($this->config, $this->cacheFactory, $this->eventDispatcher, $this->logger);
291
+        $manager->registerBackend($backend);
292
+
293
+        $result = $manager->search('fo');
294
+        $this->assertEquals(4, count($result));
295
+        $this->assertEquals('afoo', array_shift($result)->getUID());
296
+        $this->assertEquals('Afoo1', array_shift($result)->getUID());
297
+        $this->assertEquals('Bfoo', array_shift($result)->getUID());
298
+        $this->assertEquals('foo', array_shift($result)->getUID());
299
+    }
300
+
301
+    public function testSearchTwoBackendLimitOffset(): void {
302
+        /**
303
+         * @var \Test\Util\User\Dummy&MockObject $backend1
304
+         */
305
+        $backend1 = $this->createMock(\Test\Util\User\Dummy::class);
306
+        $backend1->expects($this->once())
307
+            ->method('getUsers')
308
+            ->with($this->equalTo('fo'), $this->equalTo(3), $this->equalTo(1))
309
+            ->willReturn(['foo1', 'foo2']);
310
+        $backend1->expects($this->never())
311
+            ->method('loginName2UserName');
312
+
313
+        /**
314
+         * @var \Test\Util\User\Dummy&MockObject $backend2
315
+         */
316
+        $backend2 = $this->createMock(\Test\Util\User\Dummy::class);
317
+        $backend2->expects($this->once())
318
+            ->method('getUsers')
319
+            ->with($this->equalTo('fo'), $this->equalTo(3), $this->equalTo(1))
320
+            ->willReturn(['foo3']);
321
+        $backend2->expects($this->never())
322
+            ->method('loginName2UserName');
323
+
324
+        $manager = new \OC\User\Manager($this->config, $this->cacheFactory, $this->eventDispatcher, $this->logger);
325
+        $manager->registerBackend($backend1);
326
+        $manager->registerBackend($backend2);
327
+
328
+        $result = $manager->search('fo', 3, 1);
329
+        $this->assertEquals(3, count($result));
330
+        $this->assertEquals('foo1', array_shift($result)->getUID());
331
+        $this->assertEquals('foo2', array_shift($result)->getUID());
332
+        $this->assertEquals('foo3', array_shift($result)->getUID());
333
+    }
334
+
335
+    public static function dataCreateUserInvalid(): array {
336
+        return [
337
+            ['te?st', 'foo', 'Only the following characters are allowed in a username:'
338
+                . ' "a-z", "A-Z", "0-9", spaces and "_.@-\'"'],
339
+            ["te\tst", '', 'Only the following characters are allowed in a username:'
340
+                . ' "a-z", "A-Z", "0-9", spaces and "_.@-\'"'],
341
+            ["te\nst", '', 'Only the following characters are allowed in a username:'
342
+                . ' "a-z", "A-Z", "0-9", spaces and "_.@-\'"'],
343
+            ["te\rst", '', 'Only the following characters are allowed in a username:'
344
+                . ' "a-z", "A-Z", "0-9", spaces and "_.@-\'"'],
345
+            ["te\0st", '', 'Only the following characters are allowed in a username:'
346
+                . ' "a-z", "A-Z", "0-9", spaces and "_.@-\'"'],
347
+            ["te\x0Bst", '', 'Only the following characters are allowed in a username:'
348
+                . ' "a-z", "A-Z", "0-9", spaces and "_.@-\'"'],
349
+            ["te\xe2st", '', 'Only the following characters are allowed in a username:'
350
+                . ' "a-z", "A-Z", "0-9", spaces and "_.@-\'"'],
351
+            ["te\x80st", '', 'Only the following characters are allowed in a username:'
352
+                . ' "a-z", "A-Z", "0-9", spaces and "_.@-\'"'],
353
+            ["te\x8bst", '', 'Only the following characters are allowed in a username:'
354
+                . ' "a-z", "A-Z", "0-9", spaces and "_.@-\'"'],
355
+            ['', 'foo', 'A valid username must be provided'],
356
+            [' ', 'foo', 'A valid username must be provided'],
357
+            [' test', 'foo', 'Username contains whitespace at the beginning or at the end'],
358
+            ['test ', 'foo', 'Username contains whitespace at the beginning or at the end'],
359
+            ['.', 'foo', 'Username must not consist of dots only'],
360
+            ['..', 'foo', 'Username must not consist of dots only'],
361
+            ['.test', '', 'A valid password must be provided'],
362
+            ['test', '', 'A valid password must be provided'],
363
+            ['test' . str_repeat('a', 61), '', 'Login is too long'],
364
+        ];
365
+    }
366
+
367
+    #[\PHPUnit\Framework\Attributes\DataProvider('dataCreateUserInvalid')]
368
+    public function testCreateUserInvalid($uid, $password, $exception): void {
369
+        /** @var \Test\Util\User\Dummy&MockObject $backend */
370
+        $backend = $this->createMock(\Test\Util\User\Dummy::class);
371
+        $backend->expects($this->once())
372
+            ->method('implementsActions')
373
+            ->with(\OC\User\Backend::CREATE_USER)
374
+            ->willReturn(true);
375
+
376
+
377
+        $manager = new \OC\User\Manager($this->config, $this->cacheFactory, $this->eventDispatcher, $this->logger);
378
+        $manager->registerBackend($backend);
379
+
380
+        $this->expectException(\InvalidArgumentException::class, $exception);
381
+        $manager->createUser($uid, $password);
382
+    }
383
+
384
+    public function testCreateUserSingleBackendNotExists(): void {
385
+        /**
386
+         * @var \Test\Util\User\Dummy&MockObject $backend
387
+         */
388
+        $backend = $this->createMock(\Test\Util\User\Dummy::class);
389
+        $backend->expects($this->any())
390
+            ->method('implementsActions')
391
+            ->willReturn(true);
392
+
393
+        $backend->expects($this->once())
394
+            ->method('createUser')
395
+            ->with($this->equalTo('foo'), $this->equalTo('bar'));
396
+
397
+        $backend->expects($this->once())
398
+            ->method('userExists')
399
+            ->with($this->equalTo('foo'))
400
+            ->willReturn(false);
401
+        $backend->expects($this->never())
402
+            ->method('loginName2UserName');
403
+
404
+        $manager = new \OC\User\Manager($this->config, $this->cacheFactory, $this->eventDispatcher, $this->logger);
405
+        $manager->registerBackend($backend);
406
+
407
+        $user = $manager->createUser('foo', 'bar');
408
+        $this->assertEquals('foo', $user->getUID());
409
+    }
410
+
411
+
412
+    public function testCreateUserSingleBackendExists(): void {
413
+        $this->expectException(\Exception::class);
414
+
415
+        /**
416
+         * @var \Test\Util\User\Dummy&MockObject $backend
417
+         */
418
+        $backend = $this->createMock(\Test\Util\User\Dummy::class);
419
+        $backend->expects($this->any())
420
+            ->method('implementsActions')
421
+            ->willReturn(true);
422
+
423
+        $backend->expects($this->never())
424
+            ->method('createUser');
425
+
426
+        $backend->expects($this->once())
427
+            ->method('userExists')
428
+            ->with($this->equalTo('foo'))
429
+            ->willReturn(true);
430
+
431
+        $manager = new \OC\User\Manager($this->config, $this->cacheFactory, $this->eventDispatcher, $this->logger);
432
+        $manager->registerBackend($backend);
433
+
434
+        $manager->createUser('foo', 'bar');
435
+    }
436
+
437
+    public function testCreateUserSingleBackendNotSupported(): void {
438
+        /**
439
+         * @var \Test\Util\User\Dummy&MockObject $backend
440
+         */
441
+        $backend = $this->createMock(\Test\Util\User\Dummy::class);
442
+        $backend->expects($this->any())
443
+            ->method('implementsActions')
444
+            ->willReturn(false);
445
+
446
+        $backend->expects($this->never())
447
+            ->method('createUser');
448
+
449
+        $backend->expects($this->never())
450
+            ->method('userExists');
451
+
452
+        $manager = new \OC\User\Manager($this->config, $this->cacheFactory, $this->eventDispatcher, $this->logger);
453
+        $manager->registerBackend($backend);
454
+
455
+        $this->assertFalse($manager->createUser('foo', 'bar'));
456
+    }
457
+
458
+    public function testCreateUserNoBackends(): void {
459
+        $manager = new \OC\User\Manager($this->config, $this->cacheFactory, $this->eventDispatcher, $this->logger);
460
+
461
+        $this->assertFalse($manager->createUser('foo', 'bar'));
462
+    }
463
+
464
+
465
+    public function testCreateUserFromBackendWithBackendError(): void {
466
+        $this->expectException(\InvalidArgumentException::class);
467
+        $this->expectExceptionMessage('Could not create account');
468
+
469
+        /** @var \Test\Util\User\Dummy&MockObject $backend */
470
+        $backend = $this->createMock(\Test\Util\User\Dummy::class);
471
+        $backend
472
+            ->expects($this->once())
473
+            ->method('createUser')
474
+            ->with('MyUid', 'MyPassword')
475
+            ->willReturn(false);
476
+
477
+        $manager = new Manager($this->config, $this->cacheFactory, $this->eventDispatcher, $this->logger);
478
+        $manager->createUserFromBackend('MyUid', 'MyPassword', $backend);
479
+    }
480
+
481
+
482
+    public function testCreateUserTwoBackendExists(): void {
483
+        $this->expectException(\Exception::class);
484
+
485
+        /**
486
+         * @var \Test\Util\User\Dummy&MockObject $backend1
487
+         */
488
+        $backend1 = $this->createMock(\Test\Util\User\Dummy::class);
489
+        $backend1->expects($this->any())
490
+            ->method('implementsActions')
491
+            ->willReturn(true);
492
+
493
+        $backend1->expects($this->never())
494
+            ->method('createUser');
495
+
496
+        $backend1->expects($this->once())
497
+            ->method('userExists')
498
+            ->with($this->equalTo('foo'))
499
+            ->willReturn(false);
500
+
501
+        /**
502
+         * @var \Test\Util\User\Dummy&MockObject $backend2
503
+         */
504
+        $backend2 = $this->createMock(\Test\Util\User\Dummy::class);
505
+        $backend2->expects($this->any())
506
+            ->method('implementsActions')
507
+            ->willReturn(true);
508
+
509
+        $backend2->expects($this->never())
510
+            ->method('createUser');
511
+
512
+        $backend2->expects($this->once())
513
+            ->method('userExists')
514
+            ->with($this->equalTo('foo'))
515
+            ->willReturn(true);
516
+
517
+        $manager = new \OC\User\Manager($this->config, $this->cacheFactory, $this->eventDispatcher, $this->logger);
518
+        $manager->registerBackend($backend1);
519
+        $manager->registerBackend($backend2);
520
+
521
+        $manager->createUser('foo', 'bar');
522
+    }
523
+
524
+    public function testCountUsersNoBackend(): void {
525
+        $manager = new \OC\User\Manager($this->config, $this->cacheFactory, $this->eventDispatcher, $this->logger);
526
+
527
+        $result = $manager->countUsers();
528
+        $this->assertTrue(is_array($result));
529
+        $this->assertTrue(empty($result));
530
+    }
531
+
532
+    public function testCountUsersOneBackend(): void {
533
+        /**
534
+         * @var \Test\Util\User\Dummy&MockObject $backend
535
+         */
536
+        $backend = $this->createMock(\Test\Util\User\Dummy::class);
537
+        $backend->expects($this->once())
538
+            ->method('countUsers')
539
+            ->willReturn(7);
540
+
541
+        $backend->expects($this->once())
542
+            ->method('implementsActions')
543
+            ->with(BACKEND::COUNT_USERS)
544
+            ->willReturn(true);
545
+
546
+        $backend->expects($this->once())
547
+            ->method('getBackendName')
548
+            ->willReturn('Mock_Test_Util_User_Dummy');
549
+
550
+        $manager = new \OC\User\Manager($this->config, $this->cacheFactory, $this->eventDispatcher, $this->logger);
551
+        $manager->registerBackend($backend);
552
+
553
+        $result = $manager->countUsers();
554
+        $keys = array_keys($result);
555
+        $this->assertTrue(strpos($keys[0], 'Mock_Test_Util_User_Dummy') !== false);
556
+
557
+        $users = array_shift($result);
558
+        $this->assertEquals(7, $users);
559
+    }
560
+
561
+    public function testCountUsersTwoBackends(): void {
562
+        /**
563
+         * @var \Test\Util\User\Dummy&MockObject $backend
564
+         */
565
+        $backend1 = $this->createMock(\Test\Util\User\Dummy::class);
566
+        $backend1->expects($this->once())
567
+            ->method('countUsers')
568
+            ->willReturn(7);
569
+
570
+        $backend1->expects($this->once())
571
+            ->method('implementsActions')
572
+            ->with(BACKEND::COUNT_USERS)
573
+            ->willReturn(true);
574
+        $backend1->expects($this->once())
575
+            ->method('getBackendName')
576
+            ->willReturn('Mock_Test_Util_User_Dummy');
577
+
578
+        $backend2 = $this->createMock(\Test\Util\User\Dummy::class);
579
+        $backend2->expects($this->once())
580
+            ->method('countUsers')
581
+            ->willReturn(16);
582
+
583
+        $backend2->expects($this->once())
584
+            ->method('implementsActions')
585
+            ->with(BACKEND::COUNT_USERS)
586
+            ->willReturn(true);
587
+        $backend2->expects($this->once())
588
+            ->method('getBackendName')
589
+            ->willReturn('Mock_Test_Util_User_Dummy');
590
+
591
+        $manager = new \OC\User\Manager($this->config, $this->cacheFactory, $this->eventDispatcher, $this->logger);
592
+        $manager->registerBackend($backend1);
593
+        $manager->registerBackend($backend2);
594
+
595
+        $result = $manager->countUsers();
596
+        //because the backends have the same class name, only one value expected
597
+        $this->assertEquals(1, count($result));
598
+        $keys = array_keys($result);
599
+        $this->assertTrue(strpos($keys[0], 'Mock_Test_Util_User_Dummy') !== false);
600
+
601
+        $users = array_shift($result);
602
+        //users from backends shall be summed up
603
+        $this->assertEquals(7 + 16, $users);
604
+    }
605
+
606
+    public function testCountUsersOnlyDisabled(): void {
607
+        $manager = Server::get(IUserManager::class);
608
+        // count other users in the db before adding our own
609
+        $countBefore = $manager->countDisabledUsers();
610
+
611
+        //Add test users
612
+        $user1 = $manager->createUser('testdisabledcount1', 'testdisabledcount1');
613
+
614
+        $user2 = $manager->createUser('testdisabledcount2', 'testdisabledcount2');
615
+        $user2->setEnabled(false);
616
+
617
+        $user3 = $manager->createUser('testdisabledcount3', 'testdisabledcount3');
618
+
619
+        $user4 = $manager->createUser('testdisabledcount4', 'testdisabledcount4');
620
+        $user4->setEnabled(false);
621
+
622
+        $this->assertEquals($countBefore + 2, $manager->countDisabledUsers());
623
+
624
+        //cleanup
625
+        $user1->delete();
626
+        $user2->delete();
627
+        $user3->delete();
628
+        $user4->delete();
629
+    }
630
+
631
+    public function testCountUsersOnlySeen(): void {
632
+        $manager = Server::get(IUserManager::class);
633
+        // count other users in the db before adding our own
634
+        $countBefore = $manager->countSeenUsers();
635
+
636
+        //Add test users
637
+        $user1 = $manager->createUser('testseencount1', 'testseencount1');
638
+        $user1->updateLastLoginTimestamp();
639
+
640
+        $user2 = $manager->createUser('testseencount2', 'testseencount2');
641
+        $user2->updateLastLoginTimestamp();
642
+
643
+        $user3 = $manager->createUser('testseencount3', 'testseencount3');
644
+
645
+        $user4 = $manager->createUser('testseencount4', 'testseencount4');
646
+        $user4->updateLastLoginTimestamp();
647
+
648
+        $this->assertEquals($countBefore + 3, $manager->countSeenUsers());
649
+
650
+        //cleanup
651
+        $user1->delete();
652
+        $user2->delete();
653
+        $user3->delete();
654
+        $user4->delete();
655
+    }
656
+
657
+    public function testCallForSeenUsers(): void {
658
+        $manager = Server::get(IUserManager::class);
659
+        // count other users in the db before adding our own
660
+        $count = 0;
661
+        $function = function (IUser $user) use (&$count): void {
662
+            $count++;
663
+        };
664
+        $manager->callForAllUsers($function, '', true);
665
+        $countBefore = $count;
666
+
667
+        //Add test users
668
+        $user1 = $manager->createUser('testseen1', 'testseen10');
669
+        $user1->updateLastLoginTimestamp();
670
+
671
+        $user2 = $manager->createUser('testseen2', 'testseen20');
672
+        $user2->updateLastLoginTimestamp();
673
+
674
+        $user3 = $manager->createUser('testseen3', 'testseen30');
675
+
676
+        $user4 = $manager->createUser('testseen4', 'testseen40');
677
+        $user4->updateLastLoginTimestamp();
678
+
679
+        $count = 0;
680
+        $manager->callForAllUsers($function, '', true);
681
+
682
+        $this->assertEquals($countBefore + 3, $count);
683
+
684
+        //cleanup
685
+        $user1->delete();
686
+        $user2->delete();
687
+        $user3->delete();
688
+        $user4->delete();
689
+    }
690
+
691
+    #[\PHPUnit\Framework\Attributes\RunInSeparateProcess]
692
+    #[\PHPUnit\Framework\Attributes\PreserveGlobalState(enabled: false)]
693
+    public function testRecentlyActive(): void {
694
+        $config = Server::get(IConfig::class);
695
+        $manager = Server::get(IUserManager::class);
696
+
697
+        // Create some users
698
+        $now = (string)time();
699
+        $user1 = $manager->createUser('test_active_1', 'test_active_1');
700
+        $config->setUserValue('test_active_1', 'login', 'lastLogin', $now);
701
+        $user1->setDisplayName('test active 1');
702
+        $user1->setSystemEMailAddress('[email protected]');
703
+
704
+        $user2 = $manager->createUser('TEST_ACTIVE_2_FRED', 'TEST_ACTIVE_2');
705
+        $config->setUserValue('TEST_ACTIVE_2_FRED', 'login', 'lastLogin', $now);
706
+        $user2->setDisplayName('TEST ACTIVE 2 UPPER');
707
+        $user2->setSystemEMailAddress('[email protected]');
708
+
709
+        $user3 = $manager->createUser('test_active_3', 'test_active_3');
710
+        $config->setUserValue('test_active_3', 'login', 'lastLogin', $now + 1);
711
+        $user3->setDisplayName('test active 3');
712
+
713
+        $user4 = $manager->createUser('test_active_4', 'test_active_4');
714
+        $config->setUserValue('test_active_4', 'login', 'lastLogin', $now);
715
+        $user4->setDisplayName('Test Active 4');
716
+
717
+        $user5 = $manager->createUser('test_inactive_1', 'test_inactive_1');
718
+        $user5->setDisplayName('Test Inactive 1');
719
+        $user2->setSystemEMailAddress('[email protected]');
720
+
721
+        // Search recently active
722
+        //  - No search, case-insensitive order
723
+        $users = $manager->getLastLoggedInUsers(4);
724
+        $this->assertEquals(['test_active_3', 'test_active_1', 'TEST_ACTIVE_2_FRED', 'test_active_4'], $users);
725
+        //  - Search, case-insensitive order
726
+        $users = $manager->getLastLoggedInUsers(search: 'act');
727
+        $this->assertEquals(['test_active_3', 'test_active_1', 'TEST_ACTIVE_2_FRED', 'test_active_4'], $users);
728
+        //  - No search with offset
729
+        $users = $manager->getLastLoggedInUsers(2, 2);
730
+        $this->assertEquals(['TEST_ACTIVE_2_FRED', 'test_active_4'], $users);
731
+        //  - Case insensitive search (email)
732
+        $users = $manager->getLastLoggedInUsers(search: 'active.com');
733
+        $this->assertEquals(['test_active_1', 'TEST_ACTIVE_2_FRED'], $users);
734
+        //  - Case insensitive search (display name)
735
+        $users = $manager->getLastLoggedInUsers(search: 'upper');
736
+        $this->assertEquals(['TEST_ACTIVE_2_FRED'], $users);
737
+        //  - Case insensitive search (uid)
738
+        $users = $manager->getLastLoggedInUsers(search: 'fred');
739
+        $this->assertEquals(['TEST_ACTIVE_2_FRED'], $users);
740
+
741
+        // Delete users and config keys
742
+        $user1->delete();
743
+        $user2->delete();
744
+        $user3->delete();
745
+        $user4->delete();
746
+        $user5->delete();
747
+    }
748
+
749
+    public function testDeleteUser(): void {
750
+        /** @var AllConfig&MockObject */
751
+        $config = $this->getMockBuilder(AllConfig::class)
752
+            ->disableOriginalConstructor()
753
+            ->getMock();
754
+        $config
755
+            ->expects($this->any())
756
+            ->method('getUserValue')
757
+            ->willReturnArgument(3);
758
+        $config
759
+            ->expects($this->any())
760
+            ->method('getAppValue')
761
+            ->willReturnArgument(2);
762
+
763
+        $manager = new \OC\User\Manager($config, $this->cacheFactory, $this->eventDispatcher, $this->logger);
764
+        $backend = new \Test\Util\User\Dummy();
765
+
766
+        $manager->registerBackend($backend);
767
+        $backend->createUser('foo', 'bar');
768
+        $this->assertTrue($manager->userExists('foo'));
769
+        $manager->get('foo')->delete();
770
+        $this->assertFalse($manager->userExists('foo'));
771
+    }
772
+
773
+    public function testGetByEmail(): void {
774
+        /** @var AllConfig&MockObject */
775
+        $config = $this->getMockBuilder(AllConfig::class)
776
+            ->disableOriginalConstructor()
777
+            ->getMock();
778
+        $config
779
+            ->expects($this->once())
780
+            ->method('getUsersForUserValueCaseInsensitive')
781
+            ->with('settings', 'email', '[email protected]')
782
+            ->willReturn(['uid1', 'uid99', 'uid2']);
783
+
784
+        $backend = $this->createMock(\Test\Util\User\Dummy::class);
785
+        $backend->expects($this->exactly(3))
786
+            ->method('userExists')
787
+            ->willReturnMap([
788
+                ['uid1', true],
789
+                ['uid99', false],
790
+                ['uid2', true]
791
+            ]);
792
+
793
+        $manager = new \OC\User\Manager($config, $this->cacheFactory, $this->eventDispatcher, $this->logger);
794
+        $manager->registerBackend($backend);
795
+
796
+        $users = $manager->getByEmail('[email protected]');
797
+        $this->assertCount(2, $users);
798
+        $this->assertEquals('uid1', $users[0]->getUID());
799
+        $this->assertEquals('uid2', $users[1]->getUID());
800
+    }
801 801
 }
Please login to merge, or discard this patch.
tests/lib/Files/SimpleFS/InMemoryFileTest.php 2 patches
Indentation   +105 added lines, -105 removed lines patch added patch discarded remove patch
@@ -19,109 +19,109 @@
 block discarded – undo
19 19
  * @package Test\File\SimpleFS
20 20
  */
21 21
 class InMemoryFileTest extends TestCase {
22
-	/**
23
-	 * Holds a pdf file with know attributes for tests.
24
-	 */
25
-	private InMemoryFile $testPdf;
26
-
27
-	/**
28
-	 * Sets the test file from "./resources/test.pdf".
29
-	 */
30
-	#[\PHPUnit\Framework\Attributes\Before()]
31
-	public function setupTestPdf(): void {
32
-		$fileContents = file_get_contents(
33
-			__DIR__ . '/../../../data/test.pdf'
34
-		);
35
-		$this->testPdf = new InMemoryFile('test.pdf', $fileContents);
36
-	}
37
-
38
-	/**
39
-	 * Asserts that putContent replaces the file contents.
40
-	 *
41
-	 * @return void
42
-	 */
43
-	public function testPutContent(): void {
44
-		$this->testPdf->putContent('test');
45
-		self::assertEquals('test', $this->testPdf->getContent());
46
-	}
47
-
48
-	/**
49
-	 * Asserts that delete() doesn't rise an exception.
50
-	 *
51
-	 * @return void
52
-	 */
53
-	public function testDelete(): void {
54
-		$this->testPdf->delete();
55
-		// assert true, otherwise phpunit complains about not doing any assert
56
-		self::assertTrue(true);
57
-	}
58
-
59
-	/**
60
-	 * Asserts that getName returns the name passed on file creation.
61
-	 *
62
-	 * @return void
63
-	 */
64
-	public function testGetName(): void {
65
-		self::assertEquals('test.pdf', $this->testPdf->getName());
66
-	}
67
-
68
-	/**
69
-	 * Asserts that the file size is the size of the test file.
70
-	 *
71
-	 * @return void
72
-	 */
73
-	public function testGetSize(): void {
74
-		self::assertEquals(7083, $this->testPdf->getSize());
75
-	}
76
-
77
-	/**
78
-	 * Asserts the file contents are the same than the original file contents.
79
-	 *
80
-	 * @return void
81
-	 */
82
-	public function testGetContent(): void {
83
-		self::assertEquals(
84
-			file_get_contents(__DIR__ . '/../../../data/test.pdf'),
85
-			$this->testPdf->getContent()
86
-		);
87
-	}
88
-
89
-	/**
90
-	 * Asserts the test file modification time is an integer.
91
-	 *
92
-	 * @return void
93
-	 */
94
-	public function testGetMTime(): void {
95
-		self::assertTrue(is_int($this->testPdf->getMTime()));
96
-	}
97
-
98
-	/**
99
-	 * Asserts the test file mime type is "application/json".
100
-	 *
101
-	 * @return void
102
-	 */
103
-	public function testGetMimeType(): void {
104
-		self::assertEquals('application/pdf', $this->testPdf->getMimeType());
105
-	}
106
-
107
-
108
-	/**
109
-	 * Asserts that read() raises an NotPermittedException.
110
-	 *
111
-	 * @return void
112
-	 */
113
-	public function testRead(): void {
114
-		self::expectException(NotPermittedException::class);
115
-		$this->testPdf->read();
116
-	}
117
-
118
-	/**
119
-	 * Asserts that write() raises an NotPermittedException.
120
-	 *
121
-	 * @return void
122
-	 */
123
-	public function testWrite(): void {
124
-		self::expectException(NotPermittedException::class);
125
-		$this->testPdf->write();
126
-	}
22
+    /**
23
+     * Holds a pdf file with know attributes for tests.
24
+     */
25
+    private InMemoryFile $testPdf;
26
+
27
+    /**
28
+     * Sets the test file from "./resources/test.pdf".
29
+     */
30
+    #[\PHPUnit\Framework\Attributes\Before()]
31
+    public function setupTestPdf(): void {
32
+        $fileContents = file_get_contents(
33
+            __DIR__ . '/../../../data/test.pdf'
34
+        );
35
+        $this->testPdf = new InMemoryFile('test.pdf', $fileContents);
36
+    }
37
+
38
+    /**
39
+     * Asserts that putContent replaces the file contents.
40
+     *
41
+     * @return void
42
+     */
43
+    public function testPutContent(): void {
44
+        $this->testPdf->putContent('test');
45
+        self::assertEquals('test', $this->testPdf->getContent());
46
+    }
47
+
48
+    /**
49
+     * Asserts that delete() doesn't rise an exception.
50
+     *
51
+     * @return void
52
+     */
53
+    public function testDelete(): void {
54
+        $this->testPdf->delete();
55
+        // assert true, otherwise phpunit complains about not doing any assert
56
+        self::assertTrue(true);
57
+    }
58
+
59
+    /**
60
+     * Asserts that getName returns the name passed on file creation.
61
+     *
62
+     * @return void
63
+     */
64
+    public function testGetName(): void {
65
+        self::assertEquals('test.pdf', $this->testPdf->getName());
66
+    }
67
+
68
+    /**
69
+     * Asserts that the file size is the size of the test file.
70
+     *
71
+     * @return void
72
+     */
73
+    public function testGetSize(): void {
74
+        self::assertEquals(7083, $this->testPdf->getSize());
75
+    }
76
+
77
+    /**
78
+     * Asserts the file contents are the same than the original file contents.
79
+     *
80
+     * @return void
81
+     */
82
+    public function testGetContent(): void {
83
+        self::assertEquals(
84
+            file_get_contents(__DIR__ . '/../../../data/test.pdf'),
85
+            $this->testPdf->getContent()
86
+        );
87
+    }
88
+
89
+    /**
90
+     * Asserts the test file modification time is an integer.
91
+     *
92
+     * @return void
93
+     */
94
+    public function testGetMTime(): void {
95
+        self::assertTrue(is_int($this->testPdf->getMTime()));
96
+    }
97
+
98
+    /**
99
+     * Asserts the test file mime type is "application/json".
100
+     *
101
+     * @return void
102
+     */
103
+    public function testGetMimeType(): void {
104
+        self::assertEquals('application/pdf', $this->testPdf->getMimeType());
105
+    }
106
+
107
+
108
+    /**
109
+     * Asserts that read() raises an NotPermittedException.
110
+     *
111
+     * @return void
112
+     */
113
+    public function testRead(): void {
114
+        self::expectException(NotPermittedException::class);
115
+        $this->testPdf->read();
116
+    }
117
+
118
+    /**
119
+     * Asserts that write() raises an NotPermittedException.
120
+     *
121
+     * @return void
122
+     */
123
+    public function testWrite(): void {
124
+        self::expectException(NotPermittedException::class);
125
+        $this->testPdf->write();
126
+    }
127 127
 }
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -30,7 +30,7 @@  discard block
 block discarded – undo
30 30
 	#[\PHPUnit\Framework\Attributes\Before()]
31 31
 	public function setupTestPdf(): void {
32 32
 		$fileContents = file_get_contents(
33
-			__DIR__ . '/../../../data/test.pdf'
33
+			__DIR__.'/../../../data/test.pdf'
34 34
 		);
35 35
 		$this->testPdf = new InMemoryFile('test.pdf', $fileContents);
36 36
 	}
@@ -81,7 +81,7 @@  discard block
 block discarded – undo
81 81
 	 */
82 82
 	public function testGetContent(): void {
83 83
 		self::assertEquals(
84
-			file_get_contents(__DIR__ . '/../../../data/test.pdf'),
84
+			file_get_contents(__DIR__.'/../../../data/test.pdf'),
85 85
 			$this->testPdf->getContent()
86 86
 		);
87 87
 	}
Please login to merge, or discard this patch.
tests/lib/Files/FilenameValidatorTest.php 1 patch
Indentation   +461 added lines, -461 removed lines patch added patch discarded remove patch
@@ -26,465 +26,465 @@
 block discarded – undo
26 26
 
27 27
 class FilenameValidatorTest extends TestCase {
28 28
 
29
-	protected IFactory&MockObject $l10n;
30
-	protected IConfig&MockObject $config;
31
-	protected IDBConnection&MockObject $database;
32
-	protected LoggerInterface&MockObject $logger;
33
-
34
-	protected function setUp(): void {
35
-		parent::setUp();
36
-		$l10n = $this->createMock(IL10N::class);
37
-		$l10n->method('t')
38
-			->willReturnCallback(fn ($string, $params) => sprintf($string, ...$params));
39
-		$this->l10n = $this->createMock(IFactory::class);
40
-		$this->l10n
41
-			->method('get')
42
-			->willReturn($l10n);
43
-
44
-		$this->config = $this->createMock(IConfig::class);
45
-		$this->logger = $this->createMock(LoggerInterface::class);
46
-		$this->database = $this->createMock(IDBConnection::class);
47
-		$this->database->method('supports4ByteText')->willReturn(true);
48
-	}
49
-
50
-	#[\PHPUnit\Framework\Attributes\DataProvider('dataValidateFilename')]
51
-	public function testValidateFilename(
52
-		string $filename,
53
-		array $forbiddenNames,
54
-		array $forbiddenBasenames,
55
-		array $forbiddenExtensions,
56
-		array $forbiddenCharacters,
57
-		?string $exception,
58
-	): void {
59
-		/** @var FilenameValidator&MockObject */
60
-		$validator = $this->getMockBuilder(FilenameValidator::class)
61
-			->onlyMethods([
62
-				'getForbiddenBasenames',
63
-				'getForbiddenCharacters',
64
-				'getForbiddenExtensions',
65
-				'getForbiddenFilenames',
66
-			])
67
-			->setConstructorArgs([$this->l10n, $this->database, $this->config, $this->logger])
68
-			->getMock();
69
-
70
-		$validator->method('getForbiddenBasenames')
71
-			->willReturn($forbiddenBasenames);
72
-		$validator->method('getForbiddenCharacters')
73
-			->willReturn($forbiddenCharacters);
74
-		$validator->method('getForbiddenExtensions')
75
-			->willReturn($forbiddenExtensions);
76
-		$validator->method('getForbiddenFilenames')
77
-			->willReturn($forbiddenNames);
78
-
79
-		if ($exception !== null) {
80
-			$this->expectException($exception);
81
-		} else {
82
-			$this->expectNotToPerformAssertions();
83
-		}
84
-		$validator->validateFilename($filename);
85
-	}
86
-
87
-	#[\PHPUnit\Framework\Attributes\DataProvider('dataValidateFilename')]
88
-	public function testIsFilenameValid(
89
-		string $filename,
90
-		array $forbiddenNames,
91
-		array $forbiddenBasenames,
92
-		array $forbiddenExtensions,
93
-		array $forbiddenCharacters,
94
-		?string $exception,
95
-	): void {
96
-		/** @var FilenameValidator&MockObject */
97
-		$validator = $this->getMockBuilder(FilenameValidator::class)
98
-			->onlyMethods([
99
-				'getForbiddenBasenames',
100
-				'getForbiddenExtensions',
101
-				'getForbiddenFilenames',
102
-				'getForbiddenCharacters',
103
-			])
104
-			->setConstructorArgs([$this->l10n, $this->database, $this->config, $this->logger])
105
-			->getMock();
106
-
107
-		$validator->method('getForbiddenBasenames')
108
-			->willReturn($forbiddenBasenames);
109
-		$validator->method('getForbiddenCharacters')
110
-			->willReturn($forbiddenCharacters);
111
-		$validator->method('getForbiddenExtensions')
112
-			->willReturn($forbiddenExtensions);
113
-		$validator->method('getForbiddenFilenames')
114
-			->willReturn($forbiddenNames);
115
-
116
-
117
-		$this->assertEquals($exception === null, $validator->isFilenameValid($filename));
118
-	}
119
-
120
-	public static function dataValidateFilename(): array {
121
-		return [
122
-			'valid name' => [
123
-				'a: b.txt', ['.htaccess'], [], [], [], null
124
-			],
125
-			'forbidden name in the middle is ok' => [
126
-				'a.htaccess.txt', ['.htaccess'], [], [], [], null
127
-			],
128
-			'valid name with some more parameters' => [
129
-				'a: b.txt', ['.htaccess'], [], ['exe'], ['~'], null
130
-			],
131
-			'valid name checks only the full name' => [
132
-				'.htaccess.sample', ['.htaccess'], [], [], [], null
133
-			],
134
-			'forbidden name' => [
135
-				'.htaccess', ['.htaccess'], [], [], [], ReservedWordException::class
136
-			],
137
-			'forbidden name - name is case insensitive' => [
138
-				'COM1', ['.htaccess', 'com1'], [], [], [], ReservedWordException::class
139
-			],
140
-			'forbidden basename' => [
141
-				// needed for Windows namespaces
142
-				'com1.suffix', ['.htaccess'], ['com1'], [], [], ReservedWordException::class
143
-			],
144
-			'forbidden basename case insensitive' => [
145
-				// needed for Windows namespaces
146
-				'COM1.suffix', ['.htaccess'], ['com1'], [], [], ReservedWordException::class
147
-			],
148
-			'forbidden basename for hidden files' => [
149
-				// needed for Windows namespaces
150
-				'.thumbs.db', ['.htaccess'], ['.thumbs'], [], [], ReservedWordException::class
151
-			],
152
-			'invalid character' => [
153
-				'a: b.txt', ['.htaccess'], [], [], [':'], InvalidCharacterInPathException::class
154
-			],
155
-			'invalid path' => [
156
-				'../../foo.bar', ['.htaccess'], [], [], ['/', '\\'], InvalidCharacterInPathException::class,
157
-			],
158
-			'invalid extension' => [
159
-				'a: b.txt', ['.htaccess'], [], ['.txt'], [], InvalidPathException::class
160
-			],
161
-			'invalid extension case insensitive' => [
162
-				'a: b.TXT', ['.htaccess'], [], ['.txt'], [], InvalidPathException::class
163
-			],
164
-			'empty filename' => [
165
-				'', [], [], [], [], EmptyFileNameException::class
166
-			],
167
-			'reserved unix name "."' => [
168
-				'.', [], [], [], [], InvalidDirectoryException::class
169
-			],
170
-			'reserved unix name ".."' => [
171
-				'..', [], [], [], [], InvalidDirectoryException::class
172
-			],
173
-			'weird but valid tripple dot name' => [
174
-				'...', [], [], [], [], null // is valid
175
-			],
176
-			'too long filename "."' => [
177
-				str_repeat('a', 251), [], [], [], [], FileNameTooLongException::class
178
-			],
179
-			// make sure to not split the list entries as they migh contain Unicode sequences
180
-			// in this example the "face in clouds" emoji contains the clouds emoji so only having clouds is ok
181
-			['
Please login to merge, or discard this patch.
tests/lib/Repair/RepairCollationTest.php 2 patches
Indentation   +54 added lines, -54 removed lines patch added patch discarded remove patch
@@ -19,13 +19,13 @@  discard block
 block discarded – undo
19 19
 use Test\TestCase;
20 20
 
21 21
 class TestCollationRepair extends Collation {
22
-	/**
23
-	 * @param IDBConnection $connection
24
-	 * @return string[]
25
-	 */
26
-	public function getAllNonUTF8BinTables(IDBConnection $connection) {
27
-		return parent::getAllNonUTF8BinTables($connection);
28
-	}
22
+    /**
23
+     * @param IDBConnection $connection
24
+     * @return string[]
25
+     */
26
+    public function getAllNonUTF8BinTables(IDBConnection $connection) {
27
+        return parent::getAllNonUTF8BinTables($connection);
28
+    }
29 29
 }
30 30
 
31 31
 /**
@@ -36,51 +36,51 @@  discard block
 block discarded – undo
36 36
 #[\PHPUnit\Framework\Attributes\Group('DB')]
37 37
 class RepairCollationTest extends TestCase {
38 38
 
39
-	private TestCollationRepair $repair;
40
-	private ConnectionAdapter $connection;
41
-	private string $tableName;
42
-	private IConfig $config;
43
-
44
-	private LoggerInterface&MockObject $logger;
45
-
46
-	protected function setUp(): void {
47
-		parent::setUp();
48
-
49
-		$this->connection = Server::get(ConnectionAdapter::class);
50
-		if ($this->connection->getDatabaseProvider() !== IDBConnection::PLATFORM_MYSQL) {
51
-			$this->markTestSkipped('Test only relevant on MySql');
52
-			return;
53
-		}
54
-
55
-		$this->logger = $this->createMock(LoggerInterface::class);
56
-		$this->config = Server::get(IConfig::class);
57
-		$dbPrefix = $this->config->getSystemValueString('dbtableprefix');
58
-		$this->tableName = $this->getUniqueID($dbPrefix . '_collation_test');
59
-		$this->connection->prepare("CREATE TABLE $this->tableName(text VARCHAR(16)) COLLATE utf8_unicode_ci")->execute();
60
-
61
-		$this->repair = new TestCollationRepair($this->config, $this->logger, $this->connection, false);
62
-	}
63
-
64
-	protected function tearDown(): void {
65
-		$this->connection = Server::get(ConnectionAdapter::class);
66
-		if ($this->connection->getDatabaseProvider() === IDBConnection::PLATFORM_MYSQL) {
67
-			// tear down only needed on MySQL
68
-			$this->connection->getInner()->createSchemaManager()->dropTable($this->tableName);
69
-		}
70
-		parent::tearDown();
71
-	}
72
-
73
-	public function testCollationConvert(): void {
74
-		$tables = $this->repair->getAllNonUTF8BinTables($this->connection);
75
-		$this->assertGreaterThanOrEqual(1, count($tables));
76
-
77
-		$outputMock = $this->getMockBuilder(IOutput::class)
78
-			->disableOriginalConstructor()
79
-			->getMock();
80
-
81
-		$this->repair->run($outputMock);
82
-
83
-		$tables = $this->repair->getAllNonUTF8BinTables($this->connection);
84
-		$this->assertCount(0, $tables);
85
-	}
39
+    private TestCollationRepair $repair;
40
+    private ConnectionAdapter $connection;
41
+    private string $tableName;
42
+    private IConfig $config;
43
+
44
+    private LoggerInterface&MockObject $logger;
45
+
46
+    protected function setUp(): void {
47
+        parent::setUp();
48
+
49
+        $this->connection = Server::get(ConnectionAdapter::class);
50
+        if ($this->connection->getDatabaseProvider() !== IDBConnection::PLATFORM_MYSQL) {
51
+            $this->markTestSkipped('Test only relevant on MySql');
52
+            return;
53
+        }
54
+
55
+        $this->logger = $this->createMock(LoggerInterface::class);
56
+        $this->config = Server::get(IConfig::class);
57
+        $dbPrefix = $this->config->getSystemValueString('dbtableprefix');
58
+        $this->tableName = $this->getUniqueID($dbPrefix . '_collation_test');
59
+        $this->connection->prepare("CREATE TABLE $this->tableName(text VARCHAR(16)) COLLATE utf8_unicode_ci")->execute();
60
+
61
+        $this->repair = new TestCollationRepair($this->config, $this->logger, $this->connection, false);
62
+    }
63
+
64
+    protected function tearDown(): void {
65
+        $this->connection = Server::get(ConnectionAdapter::class);
66
+        if ($this->connection->getDatabaseProvider() === IDBConnection::PLATFORM_MYSQL) {
67
+            // tear down only needed on MySQL
68
+            $this->connection->getInner()->createSchemaManager()->dropTable($this->tableName);
69
+        }
70
+        parent::tearDown();
71
+    }
72
+
73
+    public function testCollationConvert(): void {
74
+        $tables = $this->repair->getAllNonUTF8BinTables($this->connection);
75
+        $this->assertGreaterThanOrEqual(1, count($tables));
76
+
77
+        $outputMock = $this->getMockBuilder(IOutput::class)
78
+            ->disableOriginalConstructor()
79
+            ->getMock();
80
+
81
+        $this->repair->run($outputMock);
82
+
83
+        $tables = $this->repair->getAllNonUTF8BinTables($this->connection);
84
+        $this->assertCount(0, $tables);
85
+    }
86 86
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -55,7 +55,7 @@
 block discarded – undo
55 55
 		$this->logger = $this->createMock(LoggerInterface::class);
56 56
 		$this->config = Server::get(IConfig::class);
57 57
 		$dbPrefix = $this->config->getSystemValueString('dbtableprefix');
58
-		$this->tableName = $this->getUniqueID($dbPrefix . '_collation_test');
58
+		$this->tableName = $this->getUniqueID($dbPrefix.'_collation_test');
59 59
 		$this->connection->prepare("CREATE TABLE $this->tableName(text VARCHAR(16)) COLLATE utf8_unicode_ci")->execute();
60 60
 
61 61
 		$this->repair = new TestCollationRepair($this->config, $this->logger, $this->connection, false);
Please login to merge, or discard this patch.
tests/lib/AppFramework/Middleware/MiddlewareDispatcherTest.php 1 patch
Indentation   +203 added lines, -203 removed lines patch added patch discarded remove patch
@@ -18,265 +18,265 @@
 block discarded – undo
18 18
 
19 19
 // needed to test ordering
20 20
 class TestMiddleware extends Middleware {
21
-	public static $beforeControllerCalled = 0;
22
-	public static $afterControllerCalled = 0;
23
-	public static $afterExceptionCalled = 0;
24
-	public static $beforeOutputCalled = 0;
25
-
26
-	public $beforeControllerOrder = 0;
27
-	public $afterControllerOrder = 0;
28
-	public $afterExceptionOrder = 0;
29
-	public $beforeOutputOrder = 0;
30
-
31
-	public $controller;
32
-	public $methodName;
33
-	public $exception;
34
-	public $response;
35
-	public $output;
36
-
37
-	/**
38
-	 * @param boolean $beforeControllerThrowsEx
39
-	 */
40
-	public function __construct(
41
-		private $beforeControllerThrowsEx,
42
-	) {
43
-		self::$beforeControllerCalled = 0;
44
-		self::$afterControllerCalled = 0;
45
-		self::$afterExceptionCalled = 0;
46
-		self::$beforeOutputCalled = 0;
47
-	}
48
-
49
-	public function beforeController($controller, $methodName) {
50
-		self::$beforeControllerCalled++;
51
-		$this->beforeControllerOrder = self::$beforeControllerCalled;
52
-		$this->controller = $controller;
53
-		$this->methodName = $methodName;
54
-		if ($this->beforeControllerThrowsEx) {
55
-			throw new \Exception();
56
-		}
57
-	}
58
-
59
-	public function afterException($controller, $methodName, \Exception $exception) {
60
-		self::$afterExceptionCalled++;
61
-		$this->afterExceptionOrder = self::$afterExceptionCalled;
62
-		$this->controller = $controller;
63
-		$this->methodName = $methodName;
64
-		$this->exception = $exception;
65
-		parent::afterException($controller, $methodName, $exception);
66
-	}
67
-
68
-	public function afterController($controller, $methodName, Response $response) {
69
-		self::$afterControllerCalled++;
70
-		$this->afterControllerOrder = self::$afterControllerCalled;
71
-		$this->controller = $controller;
72
-		$this->methodName = $methodName;
73
-		$this->response = $response;
74
-		return parent::afterController($controller, $methodName, $response);
75
-	}
76
-
77
-	public function beforeOutput($controller, $methodName, $output) {
78
-		self::$beforeOutputCalled++;
79
-		$this->beforeOutputOrder = self::$beforeOutputCalled;
80
-		$this->controller = $controller;
81
-		$this->methodName = $methodName;
82
-		$this->output = $output;
83
-		return parent::beforeOutput($controller, $methodName, $output);
84
-	}
21
+    public static $beforeControllerCalled = 0;
22
+    public static $afterControllerCalled = 0;
23
+    public static $afterExceptionCalled = 0;
24
+    public static $beforeOutputCalled = 0;
25
+
26
+    public $beforeControllerOrder = 0;
27
+    public $afterControllerOrder = 0;
28
+    public $afterExceptionOrder = 0;
29
+    public $beforeOutputOrder = 0;
30
+
31
+    public $controller;
32
+    public $methodName;
33
+    public $exception;
34
+    public $response;
35
+    public $output;
36
+
37
+    /**
38
+     * @param boolean $beforeControllerThrowsEx
39
+     */
40
+    public function __construct(
41
+        private $beforeControllerThrowsEx,
42
+    ) {
43
+        self::$beforeControllerCalled = 0;
44
+        self::$afterControllerCalled = 0;
45
+        self::$afterExceptionCalled = 0;
46
+        self::$beforeOutputCalled = 0;
47
+    }
48
+
49
+    public function beforeController($controller, $methodName) {
50
+        self::$beforeControllerCalled++;
51
+        $this->beforeControllerOrder = self::$beforeControllerCalled;
52
+        $this->controller = $controller;
53
+        $this->methodName = $methodName;
54
+        if ($this->beforeControllerThrowsEx) {
55
+            throw new \Exception();
56
+        }
57
+    }
58
+
59
+    public function afterException($controller, $methodName, \Exception $exception) {
60
+        self::$afterExceptionCalled++;
61
+        $this->afterExceptionOrder = self::$afterExceptionCalled;
62
+        $this->controller = $controller;
63
+        $this->methodName = $methodName;
64
+        $this->exception = $exception;
65
+        parent::afterException($controller, $methodName, $exception);
66
+    }
67
+
68
+    public function afterController($controller, $methodName, Response $response) {
69
+        self::$afterControllerCalled++;
70
+        $this->afterControllerOrder = self::$afterControllerCalled;
71
+        $this->controller = $controller;
72
+        $this->methodName = $methodName;
73
+        $this->response = $response;
74
+        return parent::afterController($controller, $methodName, $response);
75
+    }
76
+
77
+    public function beforeOutput($controller, $methodName, $output) {
78
+        self::$beforeOutputCalled++;
79
+        $this->beforeOutputOrder = self::$beforeOutputCalled;
80
+        $this->controller = $controller;
81
+        $this->methodName = $methodName;
82
+        $this->output = $output;
83
+        return parent::beforeOutput($controller, $methodName, $output);
84
+    }
85 85
 }
86 86
 
87 87
 class TestController extends Controller {
88
-	public function controllerMethod(): void {
89
-	}
88
+    public function controllerMethod(): void {
89
+    }
90 90
 }
91 91
 
92 92
 class MiddlewareDispatcherTest extends \Test\TestCase {
93
-	public $exception;
94
-	public $response;
95
-	private $out;
96
-	private $method;
97
-	private $controller;
93
+    public $exception;
94
+    public $response;
95
+    private $out;
96
+    private $method;
97
+    private $controller;
98 98
 
99
-	/**
100
-	 * @var MiddlewareDispatcher
101
-	 */
102
-	private $dispatcher;
99
+    /**
100
+     * @var MiddlewareDispatcher
101
+     */
102
+    private $dispatcher;
103 103
 
104
-	protected function setUp(): void {
105
-		parent::setUp();
104
+    protected function setUp(): void {
105
+        parent::setUp();
106 106
 
107
-		$this->dispatcher = new MiddlewareDispatcher();
108
-		$this->controller = $this->getControllerMock();
109
-		$this->method = 'method';
110
-		$this->response = new Response();
111
-		$this->out = 'hi';
112
-		$this->exception = new \Exception();
113
-	}
107
+        $this->dispatcher = new MiddlewareDispatcher();
108
+        $this->controller = $this->getControllerMock();
109
+        $this->method = 'method';
110
+        $this->response = new Response();
111
+        $this->out = 'hi';
112
+        $this->exception = new \Exception();
113
+    }
114 114
 
115 115
 
116
-	private function getControllerMock() {
117
-		return $this->getMockBuilder(TestController::class)
118
-			->onlyMethods(['controllerMethod'])
119
-			->setConstructorArgs(['app',
120
-				new Request(
121
-					['controllerMethod' => 'GET'],
122
-					$this->createMock(IRequestId::class),
123
-					$this->createMock(IConfig::class)
124
-				)
125
-			])->getMock();
126
-	}
116
+    private function getControllerMock() {
117
+        return $this->getMockBuilder(TestController::class)
118
+            ->onlyMethods(['controllerMethod'])
119
+            ->setConstructorArgs(['app',
120
+                new Request(
121
+                    ['controllerMethod' => 'GET'],
122
+                    $this->createMock(IRequestId::class),
123
+                    $this->createMock(IConfig::class)
124
+                )
125
+            ])->getMock();
126
+    }
127 127
 
128 128
 
129
-	private function getMiddleware($beforeControllerThrowsEx = false) {
130
-		$m1 = new TestMiddleware($beforeControllerThrowsEx);
131
-		$this->dispatcher->registerMiddleware($m1);
132
-		return $m1;
133
-	}
129
+    private function getMiddleware($beforeControllerThrowsEx = false) {
130
+        $m1 = new TestMiddleware($beforeControllerThrowsEx);
131
+        $this->dispatcher->registerMiddleware($m1);
132
+        return $m1;
133
+    }
134 134
 
135 135
 
136
-	public function testAfterExceptionShouldReturnResponseOfMiddleware(): void {
137
-		$response = new Response();
138
-		$m1 = $this->getMockBuilder(Middleware::class)
139
-			->onlyMethods(['afterException', 'beforeController'])
140
-			->getMock();
141
-		$m1->expects($this->never())
142
-			->method('afterException');
136
+    public function testAfterExceptionShouldReturnResponseOfMiddleware(): void {
137
+        $response = new Response();
138
+        $m1 = $this->getMockBuilder(Middleware::class)
139
+            ->onlyMethods(['afterException', 'beforeController'])
140
+            ->getMock();
141
+        $m1->expects($this->never())
142
+            ->method('afterException');
143 143
 
144
-		$m2 = $this->getMockBuilder(Middleware::class)
145
-			->onlyMethods(['afterException', 'beforeController'])
146
-			->getMock();
147
-		$m2->expects($this->once())
148
-			->method('afterException')
149
-			->willReturn($response);
144
+        $m2 = $this->getMockBuilder(Middleware::class)
145
+            ->onlyMethods(['afterException', 'beforeController'])
146
+            ->getMock();
147
+        $m2->expects($this->once())
148
+            ->method('afterException')
149
+            ->willReturn($response);
150 150
 
151
-		$this->dispatcher->registerMiddleware($m1);
152
-		$this->dispatcher->registerMiddleware($m2);
151
+        $this->dispatcher->registerMiddleware($m1);
152
+        $this->dispatcher->registerMiddleware($m2);
153 153
 
154
-		$this->dispatcher->beforeController($this->controller, $this->method);
155
-		$this->assertEquals($response, $this->dispatcher->afterException($this->controller, $this->method, $this->exception));
156
-	}
154
+        $this->dispatcher->beforeController($this->controller, $this->method);
155
+        $this->assertEquals($response, $this->dispatcher->afterException($this->controller, $this->method, $this->exception));
156
+    }
157 157
 
158 158
 
159
-	public function testAfterExceptionShouldThrowAgainWhenNotHandled(): void {
160
-		$m1 = new TestMiddleware(false);
161
-		$m2 = new TestMiddleware(true);
159
+    public function testAfterExceptionShouldThrowAgainWhenNotHandled(): void {
160
+        $m1 = new TestMiddleware(false);
161
+        $m2 = new TestMiddleware(true);
162 162
 
163
-		$this->dispatcher->registerMiddleware($m1);
164
-		$this->dispatcher->registerMiddleware($m2);
163
+        $this->dispatcher->registerMiddleware($m1);
164
+        $this->dispatcher->registerMiddleware($m2);
165 165
 
166
-		$this->expectException(\Exception::class);
167
-		$this->dispatcher->beforeController($this->controller, $this->method);
168
-		$this->dispatcher->afterException($this->controller, $this->method, $this->exception);
169
-	}
166
+        $this->expectException(\Exception::class);
167
+        $this->dispatcher->beforeController($this->controller, $this->method);
168
+        $this->dispatcher->afterException($this->controller, $this->method, $this->exception);
169
+    }
170 170
 
171 171
 
172
-	public function testBeforeControllerCorrectArguments(): void {
173
-		$m1 = $this->getMiddleware();
174
-		$this->dispatcher->beforeController($this->controller, $this->method);
172
+    public function testBeforeControllerCorrectArguments(): void {
173
+        $m1 = $this->getMiddleware();
174
+        $this->dispatcher->beforeController($this->controller, $this->method);
175 175
 
176
-		$this->assertEquals($this->controller, $m1->controller);
177
-		$this->assertEquals($this->method, $m1->methodName);
178
-	}
176
+        $this->assertEquals($this->controller, $m1->controller);
177
+        $this->assertEquals($this->method, $m1->methodName);
178
+    }
179 179
 
180 180
 
181
-	public function testAfterControllerCorrectArguments(): void {
182
-		$m1 = $this->getMiddleware();
181
+    public function testAfterControllerCorrectArguments(): void {
182
+        $m1 = $this->getMiddleware();
183 183
 
184
-		$this->dispatcher->afterController($this->controller, $this->method, $this->response);
184
+        $this->dispatcher->afterController($this->controller, $this->method, $this->response);
185 185
 
186
-		$this->assertEquals($this->controller, $m1->controller);
187
-		$this->assertEquals($this->method, $m1->methodName);
188
-		$this->assertEquals($this->response, $m1->response);
189
-	}
186
+        $this->assertEquals($this->controller, $m1->controller);
187
+        $this->assertEquals($this->method, $m1->methodName);
188
+        $this->assertEquals($this->response, $m1->response);
189
+    }
190 190
 
191 191
 
192
-	public function testAfterExceptionCorrectArguments(): void {
193
-		$m1 = $this->getMiddleware();
192
+    public function testAfterExceptionCorrectArguments(): void {
193
+        $m1 = $this->getMiddleware();
194 194
 
195
-		$this->expectException(\Exception::class);
195
+        $this->expectException(\Exception::class);
196 196
 
197
-		$this->dispatcher->beforeController($this->controller, $this->method);
198
-		$this->dispatcher->afterException($this->controller, $this->method, $this->exception);
197
+        $this->dispatcher->beforeController($this->controller, $this->method);
198
+        $this->dispatcher->afterException($this->controller, $this->method, $this->exception);
199 199
 
200
-		$this->assertEquals($this->controller, $m1->controller);
201
-		$this->assertEquals($this->method, $m1->methodName);
202
-		$this->assertEquals($this->exception, $m1->exception);
203
-	}
200
+        $this->assertEquals($this->controller, $m1->controller);
201
+        $this->assertEquals($this->method, $m1->methodName);
202
+        $this->assertEquals($this->exception, $m1->exception);
203
+    }
204 204
 
205 205
 
206
-	public function testBeforeOutputCorrectArguments(): void {
207
-		$m1 = $this->getMiddleware();
206
+    public function testBeforeOutputCorrectArguments(): void {
207
+        $m1 = $this->getMiddleware();
208 208
 
209
-		$this->dispatcher->beforeOutput($this->controller, $this->method, $this->out);
209
+        $this->dispatcher->beforeOutput($this->controller, $this->method, $this->out);
210 210
 
211
-		$this->assertEquals($this->controller, $m1->controller);
212
-		$this->assertEquals($this->method, $m1->methodName);
213
-		$this->assertEquals($this->out, $m1->output);
214
-	}
211
+        $this->assertEquals($this->controller, $m1->controller);
212
+        $this->assertEquals($this->method, $m1->methodName);
213
+        $this->assertEquals($this->out, $m1->output);
214
+    }
215 215
 
216 216
 
217
-	public function testBeforeControllerOrder(): void {
218
-		$m1 = $this->getMiddleware();
219
-		$m2 = $this->getMiddleware();
217
+    public function testBeforeControllerOrder(): void {
218
+        $m1 = $this->getMiddleware();
219
+        $m2 = $this->getMiddleware();
220 220
 
221
-		$this->dispatcher->beforeController($this->controller, $this->method);
221
+        $this->dispatcher->beforeController($this->controller, $this->method);
222 222
 
223
-		$this->assertEquals(1, $m1->beforeControllerOrder);
224
-		$this->assertEquals(2, $m2->beforeControllerOrder);
225
-	}
223
+        $this->assertEquals(1, $m1->beforeControllerOrder);
224
+        $this->assertEquals(2, $m2->beforeControllerOrder);
225
+    }
226 226
 
227
-	public function testAfterControllerOrder(): void {
228
-		$m1 = $this->getMiddleware();
229
-		$m2 = $this->getMiddleware();
227
+    public function testAfterControllerOrder(): void {
228
+        $m1 = $this->getMiddleware();
229
+        $m2 = $this->getMiddleware();
230 230
 
231
-		$this->dispatcher->afterController($this->controller, $this->method, $this->response);
231
+        $this->dispatcher->afterController($this->controller, $this->method, $this->response);
232 232
 
233
-		$this->assertEquals(2, $m1->afterControllerOrder);
234
-		$this->assertEquals(1, $m2->afterControllerOrder);
235
-	}
233
+        $this->assertEquals(2, $m1->afterControllerOrder);
234
+        $this->assertEquals(1, $m2->afterControllerOrder);
235
+    }
236 236
 
237 237
 
238
-	public function testAfterExceptionOrder(): void {
239
-		$m1 = $this->getMiddleware();
240
-		$m2 = $this->getMiddleware();
238
+    public function testAfterExceptionOrder(): void {
239
+        $m1 = $this->getMiddleware();
240
+        $m2 = $this->getMiddleware();
241 241
 
242
-		$this->expectException(\Exception::class);
243
-		$this->dispatcher->beforeController($this->controller, $this->method);
244
-		$this->dispatcher->afterException($this->controller, $this->method, $this->exception);
242
+        $this->expectException(\Exception::class);
243
+        $this->dispatcher->beforeController($this->controller, $this->method);
244
+        $this->dispatcher->afterException($this->controller, $this->method, $this->exception);
245 245
 
246
-		$this->assertEquals(1, $m1->afterExceptionOrder);
247
-		$this->assertEquals(1, $m2->afterExceptionOrder);
248
-	}
246
+        $this->assertEquals(1, $m1->afterExceptionOrder);
247
+        $this->assertEquals(1, $m2->afterExceptionOrder);
248
+    }
249 249
 
250 250
 
251
-	public function testBeforeOutputOrder(): void {
252
-		$m1 = $this->getMiddleware();
253
-		$m2 = $this->getMiddleware();
251
+    public function testBeforeOutputOrder(): void {
252
+        $m1 = $this->getMiddleware();
253
+        $m2 = $this->getMiddleware();
254 254
 
255
-		$this->dispatcher->beforeOutput($this->controller, $this->method, $this->out);
255
+        $this->dispatcher->beforeOutput($this->controller, $this->method, $this->out);
256 256
 
257
-		$this->assertEquals(2, $m1->beforeOutputOrder);
258
-		$this->assertEquals(1, $m2->beforeOutputOrder);
259
-	}
257
+        $this->assertEquals(2, $m1->beforeOutputOrder);
258
+        $this->assertEquals(1, $m2->beforeOutputOrder);
259
+    }
260 260
 
261 261
 
262
-	public function testExceptionShouldRunAfterExceptionOfOnlyPreviouslyExecutedMiddlewares(): void {
263
-		$m1 = $this->getMiddleware();
264
-		$m2 = $this->getMiddleware(true);
265
-		$m3 = $this->createMock(Middleware::class);
266
-		$m3->expects($this->never())
267
-			->method('afterException');
268
-		$m3->expects($this->never())
269
-			->method('beforeController');
270
-		$m3->expects($this->never())
271
-			->method('afterController');
272
-		$m3->method('beforeOutput')
273
-			->willReturnArgument(2);
262
+    public function testExceptionShouldRunAfterExceptionOfOnlyPreviouslyExecutedMiddlewares(): void {
263
+        $m1 = $this->getMiddleware();
264
+        $m2 = $this->getMiddleware(true);
265
+        $m3 = $this->createMock(Middleware::class);
266
+        $m3->expects($this->never())
267
+            ->method('afterException');
268
+        $m3->expects($this->never())
269
+            ->method('beforeController');
270
+        $m3->expects($this->never())
271
+            ->method('afterController');
272
+        $m3->method('beforeOutput')
273
+            ->willReturnArgument(2);
274 274
 
275
-		$this->dispatcher->registerMiddleware($m3);
275
+        $this->dispatcher->registerMiddleware($m3);
276 276
 
277
-		$this->dispatcher->beforeOutput($this->controller, $this->method, $this->out);
277
+        $this->dispatcher->beforeOutput($this->controller, $this->method, $this->out);
278 278
 
279
-		$this->assertEquals(2, $m1->beforeOutputOrder);
280
-		$this->assertEquals(1, $m2->beforeOutputOrder);
281
-	}
279
+        $this->assertEquals(2, $m1->beforeOutputOrder);
280
+        $this->assertEquals(1, $m2->beforeOutputOrder);
281
+    }
282 282
 }
Please login to merge, or discard this patch.
apps/settings/tests/SetupChecks/AppDirsWithDifferentOwnerTest.php 2 patches
Indentation   +74 added lines, -74 removed lines patch added patch discarded remove patch
@@ -14,85 +14,85 @@
 block discarded – undo
14 14
 use Test\TestCase;
15 15
 
16 16
 class AppDirsWithDifferentOwnerTest extends TestCase {
17
-	private AppDirsWithDifferentOwner $check;
17
+    private AppDirsWithDifferentOwner $check;
18 18
 
19
-	private IL10N&MockObject $l10n;
19
+    private IL10N&MockObject $l10n;
20 20
 
21
-	/**
22
-	 * Holds a list of directories created during tests.
23
-	 *
24
-	 * @var array
25
-	 */
26
-	private $dirsToRemove = [];
21
+    /**
22
+     * Holds a list of directories created during tests.
23
+     *
24
+     * @var array
25
+     */
26
+    private $dirsToRemove = [];
27 27
 
28
-	protected function setUp(): void {
29
-		parent::setUp();
28
+    protected function setUp(): void {
29
+        parent::setUp();
30 30
 
31
-		$this->l10n = $this->createMock(IL10N::class);
32
-		$this->l10n->expects($this->any())
33
-			->method('t')
34
-			->willReturnCallback(function ($message, array $replace) {
35
-				return vsprintf($message, $replace);
36
-			});
37
-		$this->check = new AppDirsWithDifferentOwner(
38
-			$this->l10n,
39
-		);
40
-	}
31
+        $this->l10n = $this->createMock(IL10N::class);
32
+        $this->l10n->expects($this->any())
33
+            ->method('t')
34
+            ->willReturnCallback(function ($message, array $replace) {
35
+                return vsprintf($message, $replace);
36
+            });
37
+        $this->check = new AppDirsWithDifferentOwner(
38
+            $this->l10n,
39
+        );
40
+    }
41 41
 
42
-	/**
43
-	 * Setups a temp directory and some subdirectories.
44
-	 * Then calls the 'getAppDirsWithDifferentOwner' method.
45
-	 * The result is expected to be empty since
46
-	 * there are no directories with different owners than the current user.
47
-	 */
48
-	public function testAppDirectoryOwnersOk(): void {
49
-		$tempDir = tempnam(sys_get_temp_dir(), 'apps') . 'dir';
50
-		mkdir($tempDir);
51
-		mkdir($tempDir . DIRECTORY_SEPARATOR . 'app1');
52
-		mkdir($tempDir . DIRECTORY_SEPARATOR . 'app2');
53
-		$this->dirsToRemove[] = $tempDir . DIRECTORY_SEPARATOR . 'app1';
54
-		$this->dirsToRemove[] = $tempDir . DIRECTORY_SEPARATOR . 'app2';
55
-		$this->dirsToRemove[] = $tempDir;
56
-		\OC::$APPSROOTS = [
57
-			[
58
-				'path' => $tempDir,
59
-				'url' => '/apps',
60
-				'writable' => true,
61
-			],
62
-		];
63
-		$this->assertSame(
64
-			[],
65
-			$this->invokePrivate($this->check, 'getAppDirsWithDifferentOwner', [posix_getuid()])
66
-		);
67
-	}
42
+    /**
43
+     * Setups a temp directory and some subdirectories.
44
+     * Then calls the 'getAppDirsWithDifferentOwner' method.
45
+     * The result is expected to be empty since
46
+     * there are no directories with different owners than the current user.
47
+     */
48
+    public function testAppDirectoryOwnersOk(): void {
49
+        $tempDir = tempnam(sys_get_temp_dir(), 'apps') . 'dir';
50
+        mkdir($tempDir);
51
+        mkdir($tempDir . DIRECTORY_SEPARATOR . 'app1');
52
+        mkdir($tempDir . DIRECTORY_SEPARATOR . 'app2');
53
+        $this->dirsToRemove[] = $tempDir . DIRECTORY_SEPARATOR . 'app1';
54
+        $this->dirsToRemove[] = $tempDir . DIRECTORY_SEPARATOR . 'app2';
55
+        $this->dirsToRemove[] = $tempDir;
56
+        \OC::$APPSROOTS = [
57
+            [
58
+                'path' => $tempDir,
59
+                'url' => '/apps',
60
+                'writable' => true,
61
+            ],
62
+        ];
63
+        $this->assertSame(
64
+            [],
65
+            $this->invokePrivate($this->check, 'getAppDirsWithDifferentOwner', [posix_getuid()])
66
+        );
67
+    }
68 68
 
69
-	/**
70
-	 * Calls the check for a none existing app root that is marked as not writable.
71
-	 * It's expected that no error happens since the check shouldn't apply.
72
-	 */
73
-	public function testAppDirectoryOwnersNotWritable(): void {
74
-		$tempDir = tempnam(sys_get_temp_dir(), 'apps') . 'dir';
75
-		\OC::$APPSROOTS = [
76
-			[
77
-				'path' => $tempDir,
78
-				'url' => '/apps',
79
-				'writable' => false,
80
-			],
81
-		];
82
-		$this->assertSame(
83
-			[],
84
-			$this->invokePrivate($this->check, 'getAppDirsWithDifferentOwner', [posix_getuid()])
85
-		);
86
-	}
69
+    /**
70
+     * Calls the check for a none existing app root that is marked as not writable.
71
+     * It's expected that no error happens since the check shouldn't apply.
72
+     */
73
+    public function testAppDirectoryOwnersNotWritable(): void {
74
+        $tempDir = tempnam(sys_get_temp_dir(), 'apps') . 'dir';
75
+        \OC::$APPSROOTS = [
76
+            [
77
+                'path' => $tempDir,
78
+                'url' => '/apps',
79
+                'writable' => false,
80
+            ],
81
+        ];
82
+        $this->assertSame(
83
+            [],
84
+            $this->invokePrivate($this->check, 'getAppDirsWithDifferentOwner', [posix_getuid()])
85
+        );
86
+    }
87 87
 
88
-	/**
89
-	 * Removes directories created during tests.
90
-	 */
91
-	#[\PHPUnit\Framework\Attributes\After()]
92
-	public function removeTestDirectories(): void {
93
-		foreach ($this->dirsToRemove as $dirToRemove) {
94
-			rmdir($dirToRemove);
95
-		}
96
-		$this->dirsToRemove = [];
97
-	}
88
+    /**
89
+     * Removes directories created during tests.
90
+     */
91
+    #[\PHPUnit\Framework\Attributes\After()]
92
+    public function removeTestDirectories(): void {
93
+        foreach ($this->dirsToRemove as $dirToRemove) {
94
+            rmdir($dirToRemove);
95
+        }
96
+        $this->dirsToRemove = [];
97
+    }
98 98
 }
Please login to merge, or discard this patch.
Spacing   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -31,7 +31,7 @@  discard block
 block discarded – undo
31 31
 		$this->l10n = $this->createMock(IL10N::class);
32 32
 		$this->l10n->expects($this->any())
33 33
 			->method('t')
34
-			->willReturnCallback(function ($message, array $replace) {
34
+			->willReturnCallback(function($message, array $replace) {
35 35
 				return vsprintf($message, $replace);
36 36
 			});
37 37
 		$this->check = new AppDirsWithDifferentOwner(
@@ -46,12 +46,12 @@  discard block
 block discarded – undo
46 46
 	 * there are no directories with different owners than the current user.
47 47
 	 */
48 48
 	public function testAppDirectoryOwnersOk(): void {
49
-		$tempDir = tempnam(sys_get_temp_dir(), 'apps') . 'dir';
49
+		$tempDir = tempnam(sys_get_temp_dir(), 'apps').'dir';
50 50
 		mkdir($tempDir);
51
-		mkdir($tempDir . DIRECTORY_SEPARATOR . 'app1');
52
-		mkdir($tempDir . DIRECTORY_SEPARATOR . 'app2');
53
-		$this->dirsToRemove[] = $tempDir . DIRECTORY_SEPARATOR . 'app1';
54
-		$this->dirsToRemove[] = $tempDir . DIRECTORY_SEPARATOR . 'app2';
51
+		mkdir($tempDir.DIRECTORY_SEPARATOR.'app1');
52
+		mkdir($tempDir.DIRECTORY_SEPARATOR.'app2');
53
+		$this->dirsToRemove[] = $tempDir.DIRECTORY_SEPARATOR.'app1';
54
+		$this->dirsToRemove[] = $tempDir.DIRECTORY_SEPARATOR.'app2';
55 55
 		$this->dirsToRemove[] = $tempDir;
56 56
 		\OC::$APPSROOTS = [
57 57
 			[
@@ -71,7 +71,7 @@  discard block
 block discarded – undo
71 71
 	 * It's expected that no error happens since the check shouldn't apply.
72 72
 	 */
73 73
 	public function testAppDirectoryOwnersNotWritable(): void {
74
-		$tempDir = tempnam(sys_get_temp_dir(), 'apps') . 'dir';
74
+		$tempDir = tempnam(sys_get_temp_dir(), 'apps').'dir';
75 75
 		\OC::$APPSROOTS = [
76 76
 			[
77 77
 				'path' => $tempDir,
Please login to merge, or discard this patch.
apps/dav/tests/unit/Listener/OutOfOfficeListenerTest.php 1 patch
Indentation   +562 added lines, -562 removed lines patch added patch discarded remove patch
@@ -39,566 +39,566 @@
 block discarded – undo
39 39
 #[\PHPUnit\Framework\Attributes\CoversClass(OutOfOfficeListener::class)]
40 40
 class OutOfOfficeListenerTest extends TestCase {
41 41
 
42
-	private ServerFactory&MockObject $serverFactory;
43
-	private IConfig&MockObject $appConfig;
44
-	private LoggerInterface&MockObject $loggerInterface;
45
-	private TimezoneService&MockObject $timezoneService;
46
-	private OutOfOfficeListener $listener;
47
-
48
-	protected function setUp(): void {
49
-		parent::setUp();
50
-
51
-		$this->serverFactory = $this->createMock(ServerFactory::class);
52
-		$this->appConfig = $this->createMock(IConfig::class);
53
-		$this->timezoneService = $this->createMock(TimezoneService::class);
54
-		$this->loggerInterface = $this->createMock(LoggerInterface::class);
55
-
56
-		$this->listener = new OutOfOfficeListener(
57
-			$this->serverFactory,
58
-			$this->appConfig,
59
-			$this->timezoneService,
60
-			$this->loggerInterface,
61
-		);
62
-	}
63
-
64
-	public function testHandleUnrelated(): void {
65
-		$event = new Event();
66
-
67
-		$this->listener->handle($event);
68
-
69
-		$this->addToAssertionCount(1);
70
-	}
71
-
72
-	public function testHandleSchedulingNoCalendarHome(): void {
73
-		$user = $this->createMock(IUser::class);
74
-		$user->method('getUID')->willReturn('user123');
75
-		$data = $this->createMock(IOutOfOfficeData::class);
76
-		$data->method('getUser')->willReturn($user);
77
-		$davServer = $this->createMock(Server::class);
78
-		$invitationServer = $this->createMock(InvitationResponseServer::class);
79
-		$invitationServer->method('getServer')->willReturn($davServer);
80
-		$this->serverFactory->method('createInviationResponseServer')->willReturn($invitationServer);
81
-		$caldavPlugin = $this->createMock(Plugin::class);
82
-		$davServer->expects(self::once())
83
-			->method('getPlugin')
84
-			->with('caldav')
85
-			->willReturn($caldavPlugin);
86
-		$event = new OutOfOfficeScheduledEvent($data);
87
-
88
-		$this->listener->handle($event);
89
-	}
90
-
91
-	public function testHandleSchedulingNoCalendarHomeNode(): void {
92
-		$user = $this->createMock(IUser::class);
93
-		$user->method('getUID')->willReturn('user123');
94
-		$data = $this->createMock(IOutOfOfficeData::class);
95
-		$data->method('getUser')->willReturn($user);
96
-		$davServer = $this->createMock(Server::class);
97
-		$invitationServer = $this->createMock(InvitationResponseServer::class);
98
-		$invitationServer->method('getServer')->willReturn($davServer);
99
-		$this->serverFactory->method('createInviationResponseServer')->willReturn($invitationServer);
100
-		$caldavPlugin = $this->createMock(Plugin::class);
101
-		$davServer->expects(self::once())
102
-			->method('getPlugin')
103
-			->with('caldav')
104
-			->willReturn($caldavPlugin);
105
-		$caldavPlugin->expects(self::once())
106
-			->method('getCalendarHomeForPrincipal')
107
-			->willReturn('/home/calendar');
108
-		$tree = $this->createMock(Tree::class);
109
-		$davServer->tree = $tree;
110
-		$tree->expects(self::once())
111
-			->method('getNodeForPath')
112
-			->with('/home/calendar')
113
-			->willThrowException(new NotFound('nope'));
114
-		$event = new OutOfOfficeScheduledEvent($data);
115
-
116
-		$this->listener->handle($event);
117
-	}
118
-
119
-	public function testHandleSchedulingPersonalCalendarNotFound(): void {
120
-		$user = $this->createMock(IUser::class);
121
-		$user->method('getUID')->willReturn('user123');
122
-		$data = $this->createMock(IOutOfOfficeData::class);
123
-		$data->method('getUser')->willReturn($user);
124
-		$davServer = $this->createMock(Server::class);
125
-		$invitationServer = $this->createMock(InvitationResponseServer::class);
126
-		$invitationServer->method('getServer')->willReturn($davServer);
127
-		$this->serverFactory->method('createInviationResponseServer')->willReturn($invitationServer);
128
-		$caldavPlugin = $this->createMock(Plugin::class);
129
-		$davServer->expects(self::once())
130
-			->method('getPlugin')
131
-			->with('caldav')
132
-			->willReturn($caldavPlugin);
133
-		$caldavPlugin->expects(self::once())
134
-			->method('getCalendarHomeForPrincipal')
135
-			->willReturn('/home/calendar');
136
-		$tree = $this->createMock(Tree::class);
137
-		$davServer->tree = $tree;
138
-		$calendarHome = $this->createMock(CalendarHome::class);
139
-		$tree->expects(self::once())
140
-			->method('getNodeForPath')
141
-			->with('/home/calendar')
142
-			->willReturn($calendarHome);
143
-		$this->appConfig->expects(self::once())
144
-			->method('getUserValue')
145
-			->with('user123', 'dav', 'defaultCalendar', 'personal')
146
-			->willReturn('personal-1');
147
-		$calendarHome->expects(self::once())
148
-			->method('getChild')
149
-			->with('personal-1')
150
-			->willThrowException(new NotFound('nope'));
151
-		$event = new OutOfOfficeScheduledEvent($data);
152
-
153
-		$this->listener->handle($event);
154
-	}
155
-
156
-	public function testHandleSchedulingWithDefaultTimezone(): void {
157
-		$user = $this->createMock(IUser::class);
158
-		$user->method('getUID')->willReturn('user123');
159
-		$data = $this->createMock(IOutOfOfficeData::class);
160
-		$data->method('getUser')->willReturn($user);
161
-		$data->method('getStartDate')
162
-			->willReturn((new DateTimeImmutable('2023-12-12T00:00:00Z'))->getTimestamp());
163
-		$data->method('getEndDate')
164
-			->willReturn((new DateTimeImmutable('2023-12-13T00:00:00Z'))->getTimestamp());
165
-		$davServer = $this->createMock(Server::class);
166
-		$invitationServer = $this->createMock(InvitationResponseServer::class);
167
-		$invitationServer->method('getServer')->willReturn($davServer);
168
-		$this->serverFactory->method('createInviationResponseServer')->willReturn($invitationServer);
169
-		$caldavPlugin = $this->createMock(Plugin::class);
170
-		$davServer->expects(self::once())
171
-			->method('getPlugin')
172
-			->with('caldav')
173
-			->willReturn($caldavPlugin);
174
-		$caldavPlugin->expects(self::once())
175
-			->method('getCalendarHomeForPrincipal')
176
-			->willReturn('/home/calendar');
177
-		$tree = $this->createMock(Tree::class);
178
-		$davServer->tree = $tree;
179
-		$calendarHome = $this->createMock(CalendarHome::class);
180
-		$tree->expects(self::once())
181
-			->method('getNodeForPath')
182
-			->with('/home/calendar')
183
-			->willReturn($calendarHome);
184
-		$this->appConfig->expects(self::once())
185
-			->method('getUserValue')
186
-			->with('user123', 'dav', 'defaultCalendar', 'personal')
187
-			->willReturn('personal-1');
188
-		$calendar = $this->createMock(Calendar::class);
189
-		$this->timezoneService->expects(self::once())
190
-			->method('getUserTimezone')
191
-			->with('user123')
192
-			->willReturn('Europe/Prague');
193
-		$calendarHome->expects(self::once())
194
-			->method('getChild')
195
-			->with('personal-1')
196
-			->willReturn($calendar);
197
-		$calendar->expects(self::once())
198
-			->method('createFile')
199
-			->willReturnCallback(function ($name, $data): void {
200
-				$vcalendar = Reader::read($data);
201
-				if (!($vcalendar instanceof VCalendar)) {
202
-					throw new InvalidArgumentException('Calendar data should be a VCALENDAR');
203
-				}
204
-				$vevent = $vcalendar->VEVENT;
205
-				if ($vevent === null || !($vevent instanceof VEvent)) {
206
-					throw new InvalidArgumentException('Calendar data should contain a VEVENT');
207
-				}
208
-				self::assertSame('Europe/Prague', $vevent->DTSTART['TZID']?->getValue());
209
-				self::assertSame('Europe/Prague', $vevent->DTEND['TZID']?->getValue());
210
-			});
211
-		$event = new OutOfOfficeScheduledEvent($data);
212
-
213
-		$this->listener->handle($event);
214
-	}
215
-
216
-	public function testHandleChangeNoCalendarHome(): void {
217
-		$user = $this->createMock(IUser::class);
218
-		$user->method('getUID')->willReturn('user123');
219
-		$data = $this->createMock(IOutOfOfficeData::class);
220
-		$data->method('getUser')->willReturn($user);
221
-		$davServer = $this->createMock(Server::class);
222
-		$invitationServer = $this->createMock(InvitationResponseServer::class);
223
-		$invitationServer->method('getServer')->willReturn($davServer);
224
-		$this->serverFactory->method('createInviationResponseServer')->willReturn($invitationServer);
225
-		$caldavPlugin = $this->createMock(Plugin::class);
226
-		$davServer->expects(self::once())
227
-			->method('getPlugin')
228
-			->with('caldav')
229
-			->willReturn($caldavPlugin);
230
-		$event = new OutOfOfficeChangedEvent($data);
231
-
232
-		$this->listener->handle($event);
233
-	}
234
-
235
-	public function testHandleChangeNoCalendarHomeNode(): void {
236
-		$user = $this->createMock(IUser::class);
237
-		$user->method('getUID')->willReturn('user123');
238
-		$data = $this->createMock(IOutOfOfficeData::class);
239
-		$data->method('getUser')->willReturn($user);
240
-		$davServer = $this->createMock(Server::class);
241
-		$invitationServer = $this->createMock(InvitationResponseServer::class);
242
-		$invitationServer->method('getServer')->willReturn($davServer);
243
-		$this->serverFactory->method('createInviationResponseServer')->willReturn($invitationServer);
244
-		$caldavPlugin = $this->createMock(Plugin::class);
245
-		$davServer->expects(self::once())
246
-			->method('getPlugin')
247
-			->with('caldav')
248
-			->willReturn($caldavPlugin);
249
-		$caldavPlugin->expects(self::once())
250
-			->method('getCalendarHomeForPrincipal')
251
-			->willReturn('/home/calendar');
252
-		$tree = $this->createMock(Tree::class);
253
-		$davServer->tree = $tree;
254
-		$tree->expects(self::once())
255
-			->method('getNodeForPath')
256
-			->with('/home/calendar')
257
-			->willThrowException(new NotFound('nope'));
258
-		$event = new OutOfOfficeChangedEvent($data);
259
-
260
-		$this->listener->handle($event);
261
-	}
262
-
263
-	public function testHandleChangePersonalCalendarNotFound(): void {
264
-		$user = $this->createMock(IUser::class);
265
-		$user->method('getUID')->willReturn('user123');
266
-		$data = $this->createMock(IOutOfOfficeData::class);
267
-		$data->method('getUser')->willReturn($user);
268
-		$davServer = $this->createMock(Server::class);
269
-		$invitationServer = $this->createMock(InvitationResponseServer::class);
270
-		$invitationServer->method('getServer')->willReturn($davServer);
271
-		$this->serverFactory->method('createInviationResponseServer')->willReturn($invitationServer);
272
-		$caldavPlugin = $this->createMock(Plugin::class);
273
-		$davServer->expects(self::once())
274
-			->method('getPlugin')
275
-			->with('caldav')
276
-			->willReturn($caldavPlugin);
277
-		$caldavPlugin->expects(self::once())
278
-			->method('getCalendarHomeForPrincipal')
279
-			->willReturn('/home/calendar');
280
-		$tree = $this->createMock(Tree::class);
281
-		$davServer->tree = $tree;
282
-		$calendarHome = $this->createMock(CalendarHome::class);
283
-		$tree->expects(self::once())
284
-			->method('getNodeForPath')
285
-			->with('/home/calendar')
286
-			->willReturn($calendarHome);
287
-		$this->appConfig->expects(self::once())
288
-			->method('getUserValue')
289
-			->with('user123', 'dav', 'defaultCalendar', 'personal')
290
-			->willReturn('personal-1');
291
-		$calendarHome->expects(self::once())
292
-			->method('getChild')
293
-			->with('personal-1')
294
-			->willThrowException(new NotFound('nope'));
295
-		$event = new OutOfOfficeChangedEvent($data);
296
-
297
-		$this->listener->handle($event);
298
-	}
299
-
300
-	public function testHandleChangeRecreate(): void {
301
-		$user = $this->createMock(IUser::class);
302
-		$user->method('getUID')->willReturn('user123');
303
-		$data = $this->createMock(IOutOfOfficeData::class);
304
-		$data->method('getUser')->willReturn($user);
305
-		$data->method('getStartDate')
306
-			->willReturn((new DateTimeImmutable('2023-12-12T00:00:00Z'))->getTimestamp());
307
-		$data->method('getEndDate')
308
-			->willReturn((new DateTimeImmutable('2023-12-14T00:00:00Z'))->getTimestamp());
309
-		$davServer = $this->createMock(Server::class);
310
-		$invitationServer = $this->createMock(InvitationResponseServer::class);
311
-		$invitationServer->method('getServer')->willReturn($davServer);
312
-		$this->serverFactory->method('createInviationResponseServer')->willReturn($invitationServer);
313
-		$caldavPlugin = $this->createMock(Plugin::class);
314
-		$davServer->expects(self::once())
315
-			->method('getPlugin')
316
-			->with('caldav')
317
-			->willReturn($caldavPlugin);
318
-		$caldavPlugin->expects(self::once())
319
-			->method('getCalendarHomeForPrincipal')
320
-			->willReturn('/home/calendar');
321
-		$tree = $this->createMock(Tree::class);
322
-		$davServer->tree = $tree;
323
-		$calendarHome = $this->createMock(CalendarHome::class);
324
-		$tree->expects(self::once())
325
-			->method('getNodeForPath')
326
-			->with('/home/calendar')
327
-			->willReturn($calendarHome);
328
-		$this->appConfig->expects(self::once())
329
-			->method('getUserValue')
330
-			->with('user123', 'dav', 'defaultCalendar', 'personal')
331
-			->willReturn('personal-1');
332
-		$calendar = $this->createMock(Calendar::class);
333
-		$this->timezoneService->expects(self::once())
334
-			->method('getUserTimezone')
335
-			->with('user123')
336
-			->willReturn(null);
337
-		$this->timezoneService->expects(self::once())
338
-			->method('getDefaultTimezone')
339
-			->willReturn('Europe/Berlin');
340
-		$calendarHome->expects(self::once())
341
-			->method('getChild')
342
-			->with('personal-1')
343
-			->willReturn($calendar);
344
-		$calendar->expects(self::once())
345
-			->method('getChild')
346
-			->willThrowException(new NotFound());
347
-		$calendar->expects(self::once())
348
-			->method('createFile')
349
-			->willReturnCallback(function ($name, $data): void {
350
-				$vcalendar = Reader::read($data);
351
-				if (!($vcalendar instanceof VCalendar)) {
352
-					throw new InvalidArgumentException('Calendar data should be a VCALENDAR');
353
-				}
354
-				$vevent = $vcalendar->VEVENT;
355
-				if ($vevent === null || !($vevent instanceof VEvent)) {
356
-					throw new InvalidArgumentException('Calendar data should contain a VEVENT');
357
-				}
358
-				self::assertSame('Europe/Berlin', $vevent->DTSTART['TZID']?->getValue());
359
-				self::assertSame('Europe/Berlin', $vevent->DTEND['TZID']?->getValue());
360
-			});
361
-		$event = new OutOfOfficeChangedEvent($data);
362
-
363
-		$this->listener->handle($event);
364
-	}
365
-
366
-	public function testHandleChangeWithoutTimezone(): void {
367
-		$user = $this->createMock(IUser::class);
368
-		$user->method('getUID')->willReturn('user123');
369
-		$data = $this->createMock(IOutOfOfficeData::class);
370
-		$data->method('getUser')->willReturn($user);
371
-		$data->method('getStartDate')
372
-			->willReturn((new DateTimeImmutable('2023-01-12T00:00:00Z'))->getTimestamp());
373
-		$data->method('getEndDate')
374
-			->willReturn((new DateTimeImmutable('2023-12-14T00:00:00Z'))->getTimestamp());
375
-		$davServer = $this->createMock(Server::class);
376
-		$invitationServer = $this->createMock(InvitationResponseServer::class);
377
-		$invitationServer->method('getServer')->willReturn($davServer);
378
-		$this->serverFactory->method('createInviationResponseServer')->willReturn($invitationServer);
379
-		$caldavPlugin = $this->createMock(Plugin::class);
380
-		$davServer->expects(self::once())
381
-			->method('getPlugin')
382
-			->with('caldav')
383
-			->willReturn($caldavPlugin);
384
-		$caldavPlugin->expects(self::once())
385
-			->method('getCalendarHomeForPrincipal')
386
-			->willReturn('/home/calendar');
387
-		$tree = $this->createMock(Tree::class);
388
-		$davServer->tree = $tree;
389
-		$calendarHome = $this->createMock(CalendarHome::class);
390
-		$tree->expects(self::once())
391
-			->method('getNodeForPath')
392
-			->with('/home/calendar')
393
-			->willReturn($calendarHome);
394
-		$this->appConfig->expects(self::once())
395
-			->method('getUserValue')
396
-			->with('user123', 'dav', 'defaultCalendar', 'personal')
397
-			->willReturn('personal-1');
398
-		$calendar = $this->createMock(Calendar::class);
399
-		$calendarHome->expects(self::once())
400
-			->method('getChild')
401
-			->with('personal-1')
402
-			->willReturn($calendar);
403
-		$eventNode = $this->createMock(CalendarObject::class);
404
-		$this->timezoneService->expects(self::once())
405
-			->method('getUserTimezone')
406
-			->with('user123')
407
-			->willReturn(null);
408
-		$this->timezoneService->expects(self::once())
409
-			->method('getDefaultTimezone')
410
-			->willReturn('UTC');
411
-		$calendar->expects(self::once())
412
-			->method('getChild')
413
-			->willReturn($eventNode);
414
-		$eventNode->expects(self::once())
415
-			->method('put')
416
-			->willReturnCallback(function ($data): void {
417
-				$vcalendar = Reader::read($data);
418
-				if (!($vcalendar instanceof VCalendar)) {
419
-					throw new InvalidArgumentException('Calendar data should be a VCALENDAR');
420
-				}
421
-				$vevent = $vcalendar->VEVENT;
422
-				if ($vevent === null || !($vevent instanceof VEvent)) {
423
-					throw new InvalidArgumentException('Calendar data should contain a VEVENT');
424
-				}
425
-				// UTC datetimes are stored without a TZID
426
-				self::assertSame(null, $vevent->DTSTART['TZID']?->getValue());
427
-				self::assertSame(null, $vevent->DTEND['TZID']?->getValue());
428
-			});
429
-		$calendar->expects(self::never())
430
-			->method('createFile');
431
-		$event = new OutOfOfficeChangedEvent($data);
432
-
433
-		$this->listener->handle($event);
434
-	}
435
-
436
-	public function testHandleClearNoCalendarHome(): void {
437
-		$user = $this->createMock(IUser::class);
438
-		$user->method('getUID')->willReturn('user123');
439
-		$data = $this->createMock(IOutOfOfficeData::class);
440
-		$data->method('getUser')->willReturn($user);
441
-		$davServer = $this->createMock(Server::class);
442
-		$invitationServer = $this->createMock(InvitationResponseServer::class);
443
-		$invitationServer->method('getServer')->willReturn($davServer);
444
-		$this->serverFactory->method('createInviationResponseServer')->willReturn($invitationServer);
445
-		$caldavPlugin = $this->createMock(Plugin::class);
446
-		$davServer->expects(self::once())
447
-			->method('getPlugin')
448
-			->with('caldav')
449
-			->willReturn($caldavPlugin);
450
-		$event = new OutOfOfficeClearedEvent($data);
451
-
452
-		$this->listener->handle($event);
453
-	}
454
-
455
-	public function testHandleClearNoCalendarHomeNode(): void {
456
-		$user = $this->createMock(IUser::class);
457
-		$user->method('getUID')->willReturn('user123');
458
-		$data = $this->createMock(IOutOfOfficeData::class);
459
-		$data->method('getUser')->willReturn($user);
460
-		$davServer = $this->createMock(Server::class);
461
-		$invitationServer = $this->createMock(InvitationResponseServer::class);
462
-		$invitationServer->method('getServer')->willReturn($davServer);
463
-		$this->serverFactory->method('createInviationResponseServer')->willReturn($invitationServer);
464
-		$caldavPlugin = $this->createMock(Plugin::class);
465
-		$davServer->expects(self::once())
466
-			->method('getPlugin')
467
-			->with('caldav')
468
-			->willReturn($caldavPlugin);
469
-		$caldavPlugin->expects(self::once())
470
-			->method('getCalendarHomeForPrincipal')
471
-			->willReturn('/home/calendar');
472
-		$tree = $this->createMock(Tree::class);
473
-		$davServer->tree = $tree;
474
-		$tree->expects(self::once())
475
-			->method('getNodeForPath')
476
-			->with('/home/calendar')
477
-			->willThrowException(new NotFound('nope'));
478
-		$event = new OutOfOfficeClearedEvent($data);
479
-
480
-		$this->listener->handle($event);
481
-	}
482
-
483
-	public function testHandleClearPersonalCalendarNotFound(): void {
484
-		$user = $this->createMock(IUser::class);
485
-		$user->method('getUID')->willReturn('user123');
486
-		$data = $this->createMock(IOutOfOfficeData::class);
487
-		$data->method('getUser')->willReturn($user);
488
-		$davServer = $this->createMock(Server::class);
489
-		$invitationServer = $this->createMock(InvitationResponseServer::class);
490
-		$invitationServer->method('getServer')->willReturn($davServer);
491
-		$this->serverFactory->method('createInviationResponseServer')->willReturn($invitationServer);
492
-		$caldavPlugin = $this->createMock(Plugin::class);
493
-		$davServer->expects(self::once())
494
-			->method('getPlugin')
495
-			->with('caldav')
496
-			->willReturn($caldavPlugin);
497
-		$caldavPlugin->expects(self::once())
498
-			->method('getCalendarHomeForPrincipal')
499
-			->willReturn('/home/calendar');
500
-		$tree = $this->createMock(Tree::class);
501
-		$davServer->tree = $tree;
502
-		$calendarHome = $this->createMock(CalendarHome::class);
503
-		$tree->expects(self::once())
504
-			->method('getNodeForPath')
505
-			->with('/home/calendar')
506
-			->willReturn($calendarHome);
507
-		$this->appConfig->expects(self::once())
508
-			->method('getUserValue')
509
-			->with('user123', 'dav', 'defaultCalendar', 'personal')
510
-			->willReturn('personal-1');
511
-		$calendarHome->expects(self::once())
512
-			->method('getChild')
513
-			->with('personal-1')
514
-			->willThrowException(new NotFound('nope'));
515
-		$event = new OutOfOfficeClearedEvent($data);
516
-
517
-		$this->listener->handle($event);
518
-	}
519
-
520
-	public function testHandleClearRecreate(): void {
521
-		$user = $this->createMock(IUser::class);
522
-		$user->method('getUID')->willReturn('user123');
523
-		$data = $this->createMock(IOutOfOfficeData::class);
524
-		$data->method('getUser')->willReturn($user);
525
-		$davServer = $this->createMock(Server::class);
526
-		$invitationServer = $this->createMock(InvitationResponseServer::class);
527
-		$invitationServer->method('getServer')->willReturn($davServer);
528
-		$this->serverFactory->method('createInviationResponseServer')->willReturn($invitationServer);
529
-		$caldavPlugin = $this->createMock(Plugin::class);
530
-		$davServer->expects(self::once())
531
-			->method('getPlugin')
532
-			->with('caldav')
533
-			->willReturn($caldavPlugin);
534
-		$caldavPlugin->expects(self::once())
535
-			->method('getCalendarHomeForPrincipal')
536
-			->willReturn('/home/calendar');
537
-		$tree = $this->createMock(Tree::class);
538
-		$davServer->tree = $tree;
539
-		$calendarHome = $this->createMock(CalendarHome::class);
540
-		$tree->expects(self::once())
541
-			->method('getNodeForPath')
542
-			->with('/home/calendar')
543
-			->willReturn($calendarHome);
544
-		$this->appConfig->expects(self::once())
545
-			->method('getUserValue')
546
-			->with('user123', 'dav', 'defaultCalendar', 'personal')
547
-			->willReturn('personal-1');
548
-		$calendar = $this->createMock(Calendar::class);
549
-		$calendarHome->expects(self::once())
550
-			->method('getChild')
551
-			->with('personal-1')
552
-			->willReturn($calendar);
553
-		$calendar->expects(self::once())
554
-			->method('getChild')
555
-			->willThrowException(new NotFound());
556
-		$event = new OutOfOfficeClearedEvent($data);
557
-
558
-		$this->listener->handle($event);
559
-	}
560
-
561
-	public function testHandleClear(): void {
562
-		$user = $this->createMock(IUser::class);
563
-		$user->method('getUID')->willReturn('user123');
564
-		$data = $this->createMock(IOutOfOfficeData::class);
565
-		$data->method('getUser')->willReturn($user);
566
-		$davServer = $this->createMock(Server::class);
567
-		$invitationServer = $this->createMock(InvitationResponseServer::class);
568
-		$invitationServer->method('getServer')->willReturn($davServer);
569
-		$this->serverFactory->method('createInviationResponseServer')->willReturn($invitationServer);
570
-		$caldavPlugin = $this->createMock(Plugin::class);
571
-		$davServer->expects(self::once())
572
-			->method('getPlugin')
573
-			->with('caldav')
574
-			->willReturn($caldavPlugin);
575
-		$caldavPlugin->expects(self::once())
576
-			->method('getCalendarHomeForPrincipal')
577
-			->willReturn('/home/calendar');
578
-		$tree = $this->createMock(Tree::class);
579
-		$davServer->tree = $tree;
580
-		$calendarHome = $this->createMock(CalendarHome::class);
581
-		$tree->expects(self::once())
582
-			->method('getNodeForPath')
583
-			->with('/home/calendar')
584
-			->willReturn($calendarHome);
585
-		$this->appConfig->expects(self::once())
586
-			->method('getUserValue')
587
-			->with('user123', 'dav', 'defaultCalendar', 'personal')
588
-			->willReturn('personal-1');
589
-		$calendar = $this->createMock(Calendar::class);
590
-		$calendarHome->expects(self::once())
591
-			->method('getChild')
592
-			->with('personal-1')
593
-			->willReturn($calendar);
594
-		$eventNode = $this->createMock(CalendarObject::class);
595
-		$calendar->expects(self::once())
596
-			->method('getChild')
597
-			->willReturn($eventNode);
598
-		$eventNode->expects(self::once())
599
-			->method('delete');
600
-		$event = new OutOfOfficeClearedEvent($data);
601
-
602
-		$this->listener->handle($event);
603
-	}
42
+    private ServerFactory&MockObject $serverFactory;
43
+    private IConfig&MockObject $appConfig;
44
+    private LoggerInterface&MockObject $loggerInterface;
45
+    private TimezoneService&MockObject $timezoneService;
46
+    private OutOfOfficeListener $listener;
47
+
48
+    protected function setUp(): void {
49
+        parent::setUp();
50
+
51
+        $this->serverFactory = $this->createMock(ServerFactory::class);
52
+        $this->appConfig = $this->createMock(IConfig::class);
53
+        $this->timezoneService = $this->createMock(TimezoneService::class);
54
+        $this->loggerInterface = $this->createMock(LoggerInterface::class);
55
+
56
+        $this->listener = new OutOfOfficeListener(
57
+            $this->serverFactory,
58
+            $this->appConfig,
59
+            $this->timezoneService,
60
+            $this->loggerInterface,
61
+        );
62
+    }
63
+
64
+    public function testHandleUnrelated(): void {
65
+        $event = new Event();
66
+
67
+        $this->listener->handle($event);
68
+
69
+        $this->addToAssertionCount(1);
70
+    }
71
+
72
+    public function testHandleSchedulingNoCalendarHome(): void {
73
+        $user = $this->createMock(IUser::class);
74
+        $user->method('getUID')->willReturn('user123');
75
+        $data = $this->createMock(IOutOfOfficeData::class);
76
+        $data->method('getUser')->willReturn($user);
77
+        $davServer = $this->createMock(Server::class);
78
+        $invitationServer = $this->createMock(InvitationResponseServer::class);
79
+        $invitationServer->method('getServer')->willReturn($davServer);
80
+        $this->serverFactory->method('createInviationResponseServer')->willReturn($invitationServer);
81
+        $caldavPlugin = $this->createMock(Plugin::class);
82
+        $davServer->expects(self::once())
83
+            ->method('getPlugin')
84
+            ->with('caldav')
85
+            ->willReturn($caldavPlugin);
86
+        $event = new OutOfOfficeScheduledEvent($data);
87
+
88
+        $this->listener->handle($event);
89
+    }
90
+
91
+    public function testHandleSchedulingNoCalendarHomeNode(): void {
92
+        $user = $this->createMock(IUser::class);
93
+        $user->method('getUID')->willReturn('user123');
94
+        $data = $this->createMock(IOutOfOfficeData::class);
95
+        $data->method('getUser')->willReturn($user);
96
+        $davServer = $this->createMock(Server::class);
97
+        $invitationServer = $this->createMock(InvitationResponseServer::class);
98
+        $invitationServer->method('getServer')->willReturn($davServer);
99
+        $this->serverFactory->method('createInviationResponseServer')->willReturn($invitationServer);
100
+        $caldavPlugin = $this->createMock(Plugin::class);
101
+        $davServer->expects(self::once())
102
+            ->method('getPlugin')
103
+            ->with('caldav')
104
+            ->willReturn($caldavPlugin);
105
+        $caldavPlugin->expects(self::once())
106
+            ->method('getCalendarHomeForPrincipal')
107
+            ->willReturn('/home/calendar');
108
+        $tree = $this->createMock(Tree::class);
109
+        $davServer->tree = $tree;
110
+        $tree->expects(self::once())
111
+            ->method('getNodeForPath')
112
+            ->with('/home/calendar')
113
+            ->willThrowException(new NotFound('nope'));
114
+        $event = new OutOfOfficeScheduledEvent($data);
115
+
116
+        $this->listener->handle($event);
117
+    }
118
+
119
+    public function testHandleSchedulingPersonalCalendarNotFound(): void {
120
+        $user = $this->createMock(IUser::class);
121
+        $user->method('getUID')->willReturn('user123');
122
+        $data = $this->createMock(IOutOfOfficeData::class);
123
+        $data->method('getUser')->willReturn($user);
124
+        $davServer = $this->createMock(Server::class);
125
+        $invitationServer = $this->createMock(InvitationResponseServer::class);
126
+        $invitationServer->method('getServer')->willReturn($davServer);
127
+        $this->serverFactory->method('createInviationResponseServer')->willReturn($invitationServer);
128
+        $caldavPlugin = $this->createMock(Plugin::class);
129
+        $davServer->expects(self::once())
130
+            ->method('getPlugin')
131
+            ->with('caldav')
132
+            ->willReturn($caldavPlugin);
133
+        $caldavPlugin->expects(self::once())
134
+            ->method('getCalendarHomeForPrincipal')
135
+            ->willReturn('/home/calendar');
136
+        $tree = $this->createMock(Tree::class);
137
+        $davServer->tree = $tree;
138
+        $calendarHome = $this->createMock(CalendarHome::class);
139
+        $tree->expects(self::once())
140
+            ->method('getNodeForPath')
141
+            ->with('/home/calendar')
142
+            ->willReturn($calendarHome);
143
+        $this->appConfig->expects(self::once())
144
+            ->method('getUserValue')
145
+            ->with('user123', 'dav', 'defaultCalendar', 'personal')
146
+            ->willReturn('personal-1');
147
+        $calendarHome->expects(self::once())
148
+            ->method('getChild')
149
+            ->with('personal-1')
150
+            ->willThrowException(new NotFound('nope'));
151
+        $event = new OutOfOfficeScheduledEvent($data);
152
+
153
+        $this->listener->handle($event);
154
+    }
155
+
156
+    public function testHandleSchedulingWithDefaultTimezone(): void {
157
+        $user = $this->createMock(IUser::class);
158
+        $user->method('getUID')->willReturn('user123');
159
+        $data = $this->createMock(IOutOfOfficeData::class);
160
+        $data->method('getUser')->willReturn($user);
161
+        $data->method('getStartDate')
162
+            ->willReturn((new DateTimeImmutable('2023-12-12T00:00:00Z'))->getTimestamp());
163
+        $data->method('getEndDate')
164
+            ->willReturn((new DateTimeImmutable('2023-12-13T00:00:00Z'))->getTimestamp());
165
+        $davServer = $this->createMock(Server::class);
166
+        $invitationServer = $this->createMock(InvitationResponseServer::class);
167
+        $invitationServer->method('getServer')->willReturn($davServer);
168
+        $this->serverFactory->method('createInviationResponseServer')->willReturn($invitationServer);
169
+        $caldavPlugin = $this->createMock(Plugin::class);
170
+        $davServer->expects(self::once())
171
+            ->method('getPlugin')
172
+            ->with('caldav')
173
+            ->willReturn($caldavPlugin);
174
+        $caldavPlugin->expects(self::once())
175
+            ->method('getCalendarHomeForPrincipal')
176
+            ->willReturn('/home/calendar');
177
+        $tree = $this->createMock(Tree::class);
178
+        $davServer->tree = $tree;
179
+        $calendarHome = $this->createMock(CalendarHome::class);
180
+        $tree->expects(self::once())
181
+            ->method('getNodeForPath')
182
+            ->with('/home/calendar')
183
+            ->willReturn($calendarHome);
184
+        $this->appConfig->expects(self::once())
185
+            ->method('getUserValue')
186
+            ->with('user123', 'dav', 'defaultCalendar', 'personal')
187
+            ->willReturn('personal-1');
188
+        $calendar = $this->createMock(Calendar::class);
189
+        $this->timezoneService->expects(self::once())
190
+            ->method('getUserTimezone')
191
+            ->with('user123')
192
+            ->willReturn('Europe/Prague');
193
+        $calendarHome->expects(self::once())
194
+            ->method('getChild')
195
+            ->with('personal-1')
196
+            ->willReturn($calendar);
197
+        $calendar->expects(self::once())
198
+            ->method('createFile')
199
+            ->willReturnCallback(function ($name, $data): void {
200
+                $vcalendar = Reader::read($data);
201
+                if (!($vcalendar instanceof VCalendar)) {
202
+                    throw new InvalidArgumentException('Calendar data should be a VCALENDAR');
203
+                }
204
+                $vevent = $vcalendar->VEVENT;
205
+                if ($vevent === null || !($vevent instanceof VEvent)) {
206
+                    throw new InvalidArgumentException('Calendar data should contain a VEVENT');
207
+                }
208
+                self::assertSame('Europe/Prague', $vevent->DTSTART['TZID']?->getValue());
209
+                self::assertSame('Europe/Prague', $vevent->DTEND['TZID']?->getValue());
210
+            });
211
+        $event = new OutOfOfficeScheduledEvent($data);
212
+
213
+        $this->listener->handle($event);
214
+    }
215
+
216
+    public function testHandleChangeNoCalendarHome(): void {
217
+        $user = $this->createMock(IUser::class);
218
+        $user->method('getUID')->willReturn('user123');
219
+        $data = $this->createMock(IOutOfOfficeData::class);
220
+        $data->method('getUser')->willReturn($user);
221
+        $davServer = $this->createMock(Server::class);
222
+        $invitationServer = $this->createMock(InvitationResponseServer::class);
223
+        $invitationServer->method('getServer')->willReturn($davServer);
224
+        $this->serverFactory->method('createInviationResponseServer')->willReturn($invitationServer);
225
+        $caldavPlugin = $this->createMock(Plugin::class);
226
+        $davServer->expects(self::once())
227
+            ->method('getPlugin')
228
+            ->with('caldav')
229
+            ->willReturn($caldavPlugin);
230
+        $event = new OutOfOfficeChangedEvent($data);
231
+
232
+        $this->listener->handle($event);
233
+    }
234
+
235
+    public function testHandleChangeNoCalendarHomeNode(): void {
236
+        $user = $this->createMock(IUser::class);
237
+        $user->method('getUID')->willReturn('user123');
238
+        $data = $this->createMock(IOutOfOfficeData::class);
239
+        $data->method('getUser')->willReturn($user);
240
+        $davServer = $this->createMock(Server::class);
241
+        $invitationServer = $this->createMock(InvitationResponseServer::class);
242
+        $invitationServer->method('getServer')->willReturn($davServer);
243
+        $this->serverFactory->method('createInviationResponseServer')->willReturn($invitationServer);
244
+        $caldavPlugin = $this->createMock(Plugin::class);
245
+        $davServer->expects(self::once())
246
+            ->method('getPlugin')
247
+            ->with('caldav')
248
+            ->willReturn($caldavPlugin);
249
+        $caldavPlugin->expects(self::once())
250
+            ->method('getCalendarHomeForPrincipal')
251
+            ->willReturn('/home/calendar');
252
+        $tree = $this->createMock(Tree::class);
253
+        $davServer->tree = $tree;
254
+        $tree->expects(self::once())
255
+            ->method('getNodeForPath')
256
+            ->with('/home/calendar')
257
+            ->willThrowException(new NotFound('nope'));
258
+        $event = new OutOfOfficeChangedEvent($data);
259
+
260
+        $this->listener->handle($event);
261
+    }
262
+
263
+    public function testHandleChangePersonalCalendarNotFound(): void {
264
+        $user = $this->createMock(IUser::class);
265
+        $user->method('getUID')->willReturn('user123');
266
+        $data = $this->createMock(IOutOfOfficeData::class);
267
+        $data->method('getUser')->willReturn($user);
268
+        $davServer = $this->createMock(Server::class);
269
+        $invitationServer = $this->createMock(InvitationResponseServer::class);
270
+        $invitationServer->method('getServer')->willReturn($davServer);
271
+        $this->serverFactory->method('createInviationResponseServer')->willReturn($invitationServer);
272
+        $caldavPlugin = $this->createMock(Plugin::class);
273
+        $davServer->expects(self::once())
274
+            ->method('getPlugin')
275
+            ->with('caldav')
276
+            ->willReturn($caldavPlugin);
277
+        $caldavPlugin->expects(self::once())
278
+            ->method('getCalendarHomeForPrincipal')
279
+            ->willReturn('/home/calendar');
280
+        $tree = $this->createMock(Tree::class);
281
+        $davServer->tree = $tree;
282
+        $calendarHome = $this->createMock(CalendarHome::class);
283
+        $tree->expects(self::once())
284
+            ->method('getNodeForPath')
285
+            ->with('/home/calendar')
286
+            ->willReturn($calendarHome);
287
+        $this->appConfig->expects(self::once())
288
+            ->method('getUserValue')
289
+            ->with('user123', 'dav', 'defaultCalendar', 'personal')
290
+            ->willReturn('personal-1');
291
+        $calendarHome->expects(self::once())
292
+            ->method('getChild')
293
+            ->with('personal-1')
294
+            ->willThrowException(new NotFound('nope'));
295
+        $event = new OutOfOfficeChangedEvent($data);
296
+
297
+        $this->listener->handle($event);
298
+    }
299
+
300
+    public function testHandleChangeRecreate(): void {
301
+        $user = $this->createMock(IUser::class);
302
+        $user->method('getUID')->willReturn('user123');
303
+        $data = $this->createMock(IOutOfOfficeData::class);
304
+        $data->method('getUser')->willReturn($user);
305
+        $data->method('getStartDate')
306
+            ->willReturn((new DateTimeImmutable('2023-12-12T00:00:00Z'))->getTimestamp());
307
+        $data->method('getEndDate')
308
+            ->willReturn((new DateTimeImmutable('2023-12-14T00:00:00Z'))->getTimestamp());
309
+        $davServer = $this->createMock(Server::class);
310
+        $invitationServer = $this->createMock(InvitationResponseServer::class);
311
+        $invitationServer->method('getServer')->willReturn($davServer);
312
+        $this->serverFactory->method('createInviationResponseServer')->willReturn($invitationServer);
313
+        $caldavPlugin = $this->createMock(Plugin::class);
314
+        $davServer->expects(self::once())
315
+            ->method('getPlugin')
316
+            ->with('caldav')
317
+            ->willReturn($caldavPlugin);
318
+        $caldavPlugin->expects(self::once())
319
+            ->method('getCalendarHomeForPrincipal')
320
+            ->willReturn('/home/calendar');
321
+        $tree = $this->createMock(Tree::class);
322
+        $davServer->tree = $tree;
323
+        $calendarHome = $this->createMock(CalendarHome::class);
324
+        $tree->expects(self::once())
325
+            ->method('getNodeForPath')
326
+            ->with('/home/calendar')
327
+            ->willReturn($calendarHome);
328
+        $this->appConfig->expects(self::once())
329
+            ->method('getUserValue')
330
+            ->with('user123', 'dav', 'defaultCalendar', 'personal')
331
+            ->willReturn('personal-1');
332
+        $calendar = $this->createMock(Calendar::class);
333
+        $this->timezoneService->expects(self::once())
334
+            ->method('getUserTimezone')
335
+            ->with('user123')
336
+            ->willReturn(null);
337
+        $this->timezoneService->expects(self::once())
338
+            ->method('getDefaultTimezone')
339
+            ->willReturn('Europe/Berlin');
340
+        $calendarHome->expects(self::once())
341
+            ->method('getChild')
342
+            ->with('personal-1')
343
+            ->willReturn($calendar);
344
+        $calendar->expects(self::once())
345
+            ->method('getChild')
346
+            ->willThrowException(new NotFound());
347
+        $calendar->expects(self::once())
348
+            ->method('createFile')
349
+            ->willReturnCallback(function ($name, $data): void {
350
+                $vcalendar = Reader::read($data);
351
+                if (!($vcalendar instanceof VCalendar)) {
352
+                    throw new InvalidArgumentException('Calendar data should be a VCALENDAR');
353
+                }
354
+                $vevent = $vcalendar->VEVENT;
355
+                if ($vevent === null || !($vevent instanceof VEvent)) {
356
+                    throw new InvalidArgumentException('Calendar data should contain a VEVENT');
357
+                }
358
+                self::assertSame('Europe/Berlin', $vevent->DTSTART['TZID']?->getValue());
359
+                self::assertSame('Europe/Berlin', $vevent->DTEND['TZID']?->getValue());
360
+            });
361
+        $event = new OutOfOfficeChangedEvent($data);
362
+
363
+        $this->listener->handle($event);
364
+    }
365
+
366
+    public function testHandleChangeWithoutTimezone(): void {
367
+        $user = $this->createMock(IUser::class);
368
+        $user->method('getUID')->willReturn('user123');
369
+        $data = $this->createMock(IOutOfOfficeData::class);
370
+        $data->method('getUser')->willReturn($user);
371
+        $data->method('getStartDate')
372
+            ->willReturn((new DateTimeImmutable('2023-01-12T00:00:00Z'))->getTimestamp());
373
+        $data->method('getEndDate')
374
+            ->willReturn((new DateTimeImmutable('2023-12-14T00:00:00Z'))->getTimestamp());
375
+        $davServer = $this->createMock(Server::class);
376
+        $invitationServer = $this->createMock(InvitationResponseServer::class);
377
+        $invitationServer->method('getServer')->willReturn($davServer);
378
+        $this->serverFactory->method('createInviationResponseServer')->willReturn($invitationServer);
379
+        $caldavPlugin = $this->createMock(Plugin::class);
380
+        $davServer->expects(self::once())
381
+            ->method('getPlugin')
382
+            ->with('caldav')
383
+            ->willReturn($caldavPlugin);
384
+        $caldavPlugin->expects(self::once())
385
+            ->method('getCalendarHomeForPrincipal')
386
+            ->willReturn('/home/calendar');
387
+        $tree = $this->createMock(Tree::class);
388
+        $davServer->tree = $tree;
389
+        $calendarHome = $this->createMock(CalendarHome::class);
390
+        $tree->expects(self::once())
391
+            ->method('getNodeForPath')
392
+            ->with('/home/calendar')
393
+            ->willReturn($calendarHome);
394
+        $this->appConfig->expects(self::once())
395
+            ->method('getUserValue')
396
+            ->with('user123', 'dav', 'defaultCalendar', 'personal')
397
+            ->willReturn('personal-1');
398
+        $calendar = $this->createMock(Calendar::class);
399
+        $calendarHome->expects(self::once())
400
+            ->method('getChild')
401
+            ->with('personal-1')
402
+            ->willReturn($calendar);
403
+        $eventNode = $this->createMock(CalendarObject::class);
404
+        $this->timezoneService->expects(self::once())
405
+            ->method('getUserTimezone')
406
+            ->with('user123')
407
+            ->willReturn(null);
408
+        $this->timezoneService->expects(self::once())
409
+            ->method('getDefaultTimezone')
410
+            ->willReturn('UTC');
411
+        $calendar->expects(self::once())
412
+            ->method('getChild')
413
+            ->willReturn($eventNode);
414
+        $eventNode->expects(self::once())
415
+            ->method('put')
416
+            ->willReturnCallback(function ($data): void {
417
+                $vcalendar = Reader::read($data);
418
+                if (!($vcalendar instanceof VCalendar)) {
419
+                    throw new InvalidArgumentException('Calendar data should be a VCALENDAR');
420
+                }
421
+                $vevent = $vcalendar->VEVENT;
422
+                if ($vevent === null || !($vevent instanceof VEvent)) {
423
+                    throw new InvalidArgumentException('Calendar data should contain a VEVENT');
424
+                }
425
+                // UTC datetimes are stored without a TZID
426
+                self::assertSame(null, $vevent->DTSTART['TZID']?->getValue());
427
+                self::assertSame(null, $vevent->DTEND['TZID']?->getValue());
428
+            });
429
+        $calendar->expects(self::never())
430
+            ->method('createFile');
431
+        $event = new OutOfOfficeChangedEvent($data);
432
+
433
+        $this->listener->handle($event);
434
+    }
435
+
436
+    public function testHandleClearNoCalendarHome(): void {
437
+        $user = $this->createMock(IUser::class);
438
+        $user->method('getUID')->willReturn('user123');
439
+        $data = $this->createMock(IOutOfOfficeData::class);
440
+        $data->method('getUser')->willReturn($user);
441
+        $davServer = $this->createMock(Server::class);
442
+        $invitationServer = $this->createMock(InvitationResponseServer::class);
443
+        $invitationServer->method('getServer')->willReturn($davServer);
444
+        $this->serverFactory->method('createInviationResponseServer')->willReturn($invitationServer);
445
+        $caldavPlugin = $this->createMock(Plugin::class);
446
+        $davServer->expects(self::once())
447
+            ->method('getPlugin')
448
+            ->with('caldav')
449
+            ->willReturn($caldavPlugin);
450
+        $event = new OutOfOfficeClearedEvent($data);
451
+
452
+        $this->listener->handle($event);
453
+    }
454
+
455
+    public function testHandleClearNoCalendarHomeNode(): void {
456
+        $user = $this->createMock(IUser::class);
457
+        $user->method('getUID')->willReturn('user123');
458
+        $data = $this->createMock(IOutOfOfficeData::class);
459
+        $data->method('getUser')->willReturn($user);
460
+        $davServer = $this->createMock(Server::class);
461
+        $invitationServer = $this->createMock(InvitationResponseServer::class);
462
+        $invitationServer->method('getServer')->willReturn($davServer);
463
+        $this->serverFactory->method('createInviationResponseServer')->willReturn($invitationServer);
464
+        $caldavPlugin = $this->createMock(Plugin::class);
465
+        $davServer->expects(self::once())
466
+            ->method('getPlugin')
467
+            ->with('caldav')
468
+            ->willReturn($caldavPlugin);
469
+        $caldavPlugin->expects(self::once())
470
+            ->method('getCalendarHomeForPrincipal')
471
+            ->willReturn('/home/calendar');
472
+        $tree = $this->createMock(Tree::class);
473
+        $davServer->tree = $tree;
474
+        $tree->expects(self::once())
475
+            ->method('getNodeForPath')
476
+            ->with('/home/calendar')
477
+            ->willThrowException(new NotFound('nope'));
478
+        $event = new OutOfOfficeClearedEvent($data);
479
+
480
+        $this->listener->handle($event);
481
+    }
482
+
483
+    public function testHandleClearPersonalCalendarNotFound(): void {
484
+        $user = $this->createMock(IUser::class);
485
+        $user->method('getUID')->willReturn('user123');
486
+        $data = $this->createMock(IOutOfOfficeData::class);
487
+        $data->method('getUser')->willReturn($user);
488
+        $davServer = $this->createMock(Server::class);
489
+        $invitationServer = $this->createMock(InvitationResponseServer::class);
490
+        $invitationServer->method('getServer')->willReturn($davServer);
491
+        $this->serverFactory->method('createInviationResponseServer')->willReturn($invitationServer);
492
+        $caldavPlugin = $this->createMock(Plugin::class);
493
+        $davServer->expects(self::once())
494
+            ->method('getPlugin')
495
+            ->with('caldav')
496
+            ->willReturn($caldavPlugin);
497
+        $caldavPlugin->expects(self::once())
498
+            ->method('getCalendarHomeForPrincipal')
499
+            ->willReturn('/home/calendar');
500
+        $tree = $this->createMock(Tree::class);
501
+        $davServer->tree = $tree;
502
+        $calendarHome = $this->createMock(CalendarHome::class);
503
+        $tree->expects(self::once())
504
+            ->method('getNodeForPath')
505
+            ->with('/home/calendar')
506
+            ->willReturn($calendarHome);
507
+        $this->appConfig->expects(self::once())
508
+            ->method('getUserValue')
509
+            ->with('user123', 'dav', 'defaultCalendar', 'personal')
510
+            ->willReturn('personal-1');
511
+        $calendarHome->expects(self::once())
512
+            ->method('getChild')
513
+            ->with('personal-1')
514
+            ->willThrowException(new NotFound('nope'));
515
+        $event = new OutOfOfficeClearedEvent($data);
516
+
517
+        $this->listener->handle($event);
518
+    }
519
+
520
+    public function testHandleClearRecreate(): void {
521
+        $user = $this->createMock(IUser::class);
522
+        $user->method('getUID')->willReturn('user123');
523
+        $data = $this->createMock(IOutOfOfficeData::class);
524
+        $data->method('getUser')->willReturn($user);
525
+        $davServer = $this->createMock(Server::class);
526
+        $invitationServer = $this->createMock(InvitationResponseServer::class);
527
+        $invitationServer->method('getServer')->willReturn($davServer);
528
+        $this->serverFactory->method('createInviationResponseServer')->willReturn($invitationServer);
529
+        $caldavPlugin = $this->createMock(Plugin::class);
530
+        $davServer->expects(self::once())
531
+            ->method('getPlugin')
532
+            ->with('caldav')
533
+            ->willReturn($caldavPlugin);
534
+        $caldavPlugin->expects(self::once())
535
+            ->method('getCalendarHomeForPrincipal')
536
+            ->willReturn('/home/calendar');
537
+        $tree = $this->createMock(Tree::class);
538
+        $davServer->tree = $tree;
539
+        $calendarHome = $this->createMock(CalendarHome::class);
540
+        $tree->expects(self::once())
541
+            ->method('getNodeForPath')
542
+            ->with('/home/calendar')
543
+            ->willReturn($calendarHome);
544
+        $this->appConfig->expects(self::once())
545
+            ->method('getUserValue')
546
+            ->with('user123', 'dav', 'defaultCalendar', 'personal')
547
+            ->willReturn('personal-1');
548
+        $calendar = $this->createMock(Calendar::class);
549
+        $calendarHome->expects(self::once())
550
+            ->method('getChild')
551
+            ->with('personal-1')
552
+            ->willReturn($calendar);
553
+        $calendar->expects(self::once())
554
+            ->method('getChild')
555
+            ->willThrowException(new NotFound());
556
+        $event = new OutOfOfficeClearedEvent($data);
557
+
558
+        $this->listener->handle($event);
559
+    }
560
+
561
+    public function testHandleClear(): void {
562
+        $user = $this->createMock(IUser::class);
563
+        $user->method('getUID')->willReturn('user123');
564
+        $data = $this->createMock(IOutOfOfficeData::class);
565
+        $data->method('getUser')->willReturn($user);
566
+        $davServer = $this->createMock(Server::class);
567
+        $invitationServer = $this->createMock(InvitationResponseServer::class);
568
+        $invitationServer->method('getServer')->willReturn($davServer);
569
+        $this->serverFactory->method('createInviationResponseServer')->willReturn($invitationServer);
570
+        $caldavPlugin = $this->createMock(Plugin::class);
571
+        $davServer->expects(self::once())
572
+            ->method('getPlugin')
573
+            ->with('caldav')
574
+            ->willReturn($caldavPlugin);
575
+        $caldavPlugin->expects(self::once())
576
+            ->method('getCalendarHomeForPrincipal')
577
+            ->willReturn('/home/calendar');
578
+        $tree = $this->createMock(Tree::class);
579
+        $davServer->tree = $tree;
580
+        $calendarHome = $this->createMock(CalendarHome::class);
581
+        $tree->expects(self::once())
582
+            ->method('getNodeForPath')
583
+            ->with('/home/calendar')
584
+            ->willReturn($calendarHome);
585
+        $this->appConfig->expects(self::once())
586
+            ->method('getUserValue')
587
+            ->with('user123', 'dav', 'defaultCalendar', 'personal')
588
+            ->willReturn('personal-1');
589
+        $calendar = $this->createMock(Calendar::class);
590
+        $calendarHome->expects(self::once())
591
+            ->method('getChild')
592
+            ->with('personal-1')
593
+            ->willReturn($calendar);
594
+        $eventNode = $this->createMock(CalendarObject::class);
595
+        $calendar->expects(self::once())
596
+            ->method('getChild')
597
+            ->willReturn($eventNode);
598
+        $eventNode->expects(self::once())
599
+            ->method('delete');
600
+        $event = new OutOfOfficeClearedEvent($data);
601
+
602
+        $this->listener->handle($event);
603
+    }
604 604
 }
Please login to merge, or discard this patch.
apps/dav/tests/unit/CalDAV/Schedule/IMipPluginCharsetTest.php 1 patch
Indentation   +150 added lines, -150 removed lines patch added patch discarded remove patch
@@ -41,154 +41,154 @@
 block discarded – undo
41 41
 use Test\Traits\EmailValidatorTrait;
42 42
 
43 43
 class IMipPluginCharsetTest extends TestCase {
44
-	use EmailValidatorTrait;
45
-	// Dependencies
46
-	private Defaults&MockObject $defaults;
47
-	private IAppConfig&MockObject $appConfig;
48
-	private IConfig&MockObject $config;
49
-	private IDBConnection&MockObject $db;
50
-	private IFactory $l10nFactory;
51
-	private IManager&MockObject $mailManager;
52
-	private IMailer&MockObject $mailer;
53
-	private ISecureRandom&MockObject $random;
54
-	private ITimeFactory&MockObject $timeFactory;
55
-	private IUrlGenerator&MockObject $urlGenerator;
56
-	private IUserSession&MockObject $userSession;
57
-	private LoggerInterface $logger;
58
-
59
-	// Services
60
-	private EventComparisonService $eventComparisonService;
61
-	private IMipPlugin $imipPlugin;
62
-	private IMipService $imipService;
63
-
64
-	// ITip Message
65
-	private Message $itipMessage;
66
-
67
-	protected function setUp(): void {
68
-		// Used by IMipService and IMipPlugin
69
-		$today = new \DateTime('2025-06-15 14:30');
70
-		$this->timeFactory = $this->createMock(ITimeFactory::class);
71
-		$this->timeFactory->method('getTime')
72
-			->willReturn($today->getTimestamp());
73
-		$this->timeFactory->method('getDateTime')
74
-			->willReturn($today);
75
-
76
-		// IMipService
77
-		$this->urlGenerator = $this->createMock(URLGenerator::class);
78
-		$this->config = $this->createMock(IConfig::class);
79
-		$this->db = $this->createMock(IDBConnection::class);
80
-		$this->random = $this->createMock(ISecureRandom::class);
81
-		$l10n = $this->createMock(L10N::class);
82
-		$this->l10nFactory = $this->createMock(IFactory::class);
83
-		$this->l10nFactory->method('findGenericLanguage')
84
-			->willReturn('en');
85
-		$this->l10nFactory->method('findLocale')
86
-			->willReturn('en_US');
87
-		$this->l10nFactory->method('get')
88
-			->willReturn($l10n);
89
-		$this->imipService = new IMipService(
90
-			$this->urlGenerator,
91
-			$this->config,
92
-			$this->db,
93
-			$this->random,
94
-			$this->l10nFactory,
95
-			$this->timeFactory,
96
-		);
97
-
98
-		// EventComparisonService
99
-		$this->eventComparisonService = new EventComparisonService();
100
-
101
-		// IMipPlugin
102
-		$this->appConfig = $this->createMock(IAppConfig::class);
103
-		$message = new \OC\Mail\Message(new Email(), false);
104
-		$this->mailer = $this->createMock(IMailer::class);
105
-		$this->mailer->method('createMessage')
106
-			->willReturn($message);
107
-		$this->logger = new NullLogger();
108
-		$this->defaults = $this->createMock(Defaults::class);
109
-		$this->defaults->method('getName')
110
-			->willReturn('Instance Name 123');
111
-		$user = $this->createMock(IUser::class);
112
-		$user->method('getUID')
113
-			->willReturn('luigi');
114
-		$this->userSession = $this->createMock(IUserSession::class);
115
-		$this->userSession->method('getUser')
116
-			->willReturn($user);
117
-		$this->mailManager = $this->createMock(IManager::class);
118
-		$this->imipPlugin = new IMipPlugin(
119
-			$this->appConfig,
120
-			$this->mailer,
121
-			$this->logger,
122
-			$this->timeFactory,
123
-			$this->defaults,
124
-			$this->userSession,
125
-			$this->imipService,
126
-			$this->eventComparisonService,
127
-			$this->mailManager,
128
-			$this->getEmailValidatorWithStrictEmailCheck(),
129
-		);
130
-
131
-		// ITipMessage
132
-		$calendar = new VCalendar();
133
-		$event = new VEvent($calendar, 'VEVENT');
134
-		$event->UID = 'uid-1234';
135
-		$event->SEQUENCE = 1;
136
-		$event->SUMMARY = 'Lunch';
137
-		$event->DTSTART = new \DateTime('2025-06-20 12:30:00');
138
-		$organizer = new CalAddress($calendar, 'ORGANIZER', 'mailto:[email protected]');
139
-		$event->add($organizer);
140
-		$attendee = new CalAddress($calendar, 'ATTENDEE', 'mailto:[email protected]', ['RSVP' => 'TRUE', 'CN' => 'José']);
141
-		$event->add($attendee);
142
-		$calendar->add($event);
143
-		$this->itipMessage = new Message();
144
-		$this->itipMessage->method = 'REQUEST';
145
-		$this->itipMessage->message = $calendar;
146
-		$this->itipMessage->sender = 'mailto:[email protected]';
147
-		$this->itipMessage->senderName = 'Luigi';
148
-		$this->itipMessage->recipient = 'mailto:' . '[email protected]';
149
-	}
150
-
151
-	public function testCharsetMailer(): void {
152
-		// Arrange
153
-		$symfonyEmail = null;
154
-		$this->mailer->expects(self::once())
155
-			->method('send')
156
-			->willReturnCallback(function (IMessage $message) use (&$symfonyEmail): array {
157
-				if ($message instanceof \OC\Mail\Message) {
158
-					$symfonyEmail = $message->getSymfonyEmail();
159
-				}
160
-				return [];
161
-			});
162
-
163
-		// Act
164
-		$this->imipPlugin->schedule($this->itipMessage);
165
-
166
-		// Assert
167
-		$this->assertNotNull($symfonyEmail);
168
-		$body = $symfonyEmail->getBody()->toString();
169
-		$this->assertStringContainsString('Content-Type: text/calendar; method=REQUEST; charset="utf-8"; name=event.ics', $body);
170
-	}
171
-
172
-	public function testCharsetMailProvider(): void {
173
-		// Arrange
174
-		$this->appConfig->method('getValueBool')
175
-			->with('core', 'mail_providers_enabled', true)
176
-			->willReturn(true);
177
-		$mailMessage = new MailProviderMessage();
178
-		$mailService = $this->createMockForIntersectionOfInterfaces([IService::class, IMessageSend::class]);
179
-		$mailService->method('initiateMessage')
180
-			->willReturn($mailMessage);
181
-		$mailService->expects(self::once())
182
-			->method('sendMessage');
183
-		$this->mailManager->method('findServiceByAddress')
184
-			->willReturn($mailService);
185
-
186
-		// Act
187
-		$this->imipPlugin->schedule($this->itipMessage);
188
-
189
-		// Assert
190
-		$attachments = $mailMessage->getAttachments();
191
-		$this->assertCount(1, $attachments);
192
-		$this->assertStringContainsString('text/calendar; method=REQUEST; charset="utf-8"; name=event.ics', $attachments[0]->getType());
193
-	}
44
+    use EmailValidatorTrait;
45
+    // Dependencies
46
+    private Defaults&MockObject $defaults;
47
+    private IAppConfig&MockObject $appConfig;
48
+    private IConfig&MockObject $config;
49
+    private IDBConnection&MockObject $db;
50
+    private IFactory $l10nFactory;
51
+    private IManager&MockObject $mailManager;
52
+    private IMailer&MockObject $mailer;
53
+    private ISecureRandom&MockObject $random;
54
+    private ITimeFactory&MockObject $timeFactory;
55
+    private IUrlGenerator&MockObject $urlGenerator;
56
+    private IUserSession&MockObject $userSession;
57
+    private LoggerInterface $logger;
58
+
59
+    // Services
60
+    private EventComparisonService $eventComparisonService;
61
+    private IMipPlugin $imipPlugin;
62
+    private IMipService $imipService;
63
+
64
+    // ITip Message
65
+    private Message $itipMessage;
66
+
67
+    protected function setUp(): void {
68
+        // Used by IMipService and IMipPlugin
69
+        $today = new \DateTime('2025-06-15 14:30');
70
+        $this->timeFactory = $this->createMock(ITimeFactory::class);
71
+        $this->timeFactory->method('getTime')
72
+            ->willReturn($today->getTimestamp());
73
+        $this->timeFactory->method('getDateTime')
74
+            ->willReturn($today);
75
+
76
+        // IMipService
77
+        $this->urlGenerator = $this->createMock(URLGenerator::class);
78
+        $this->config = $this->createMock(IConfig::class);
79
+        $this->db = $this->createMock(IDBConnection::class);
80
+        $this->random = $this->createMock(ISecureRandom::class);
81
+        $l10n = $this->createMock(L10N::class);
82
+        $this->l10nFactory = $this->createMock(IFactory::class);
83
+        $this->l10nFactory->method('findGenericLanguage')
84
+            ->willReturn('en');
85
+        $this->l10nFactory->method('findLocale')
86
+            ->willReturn('en_US');
87
+        $this->l10nFactory->method('get')
88
+            ->willReturn($l10n);
89
+        $this->imipService = new IMipService(
90
+            $this->urlGenerator,
91
+            $this->config,
92
+            $this->db,
93
+            $this->random,
94
+            $this->l10nFactory,
95
+            $this->timeFactory,
96
+        );
97
+
98
+        // EventComparisonService
99
+        $this->eventComparisonService = new EventComparisonService();
100
+
101
+        // IMipPlugin
102
+        $this->appConfig = $this->createMock(IAppConfig::class);
103
+        $message = new \OC\Mail\Message(new Email(), false);
104
+        $this->mailer = $this->createMock(IMailer::class);
105
+        $this->mailer->method('createMessage')
106
+            ->willReturn($message);
107
+        $this->logger = new NullLogger();
108
+        $this->defaults = $this->createMock(Defaults::class);
109
+        $this->defaults->method('getName')
110
+            ->willReturn('Instance Name 123');
111
+        $user = $this->createMock(IUser::class);
112
+        $user->method('getUID')
113
+            ->willReturn('luigi');
114
+        $this->userSession = $this->createMock(IUserSession::class);
115
+        $this->userSession->method('getUser')
116
+            ->willReturn($user);
117
+        $this->mailManager = $this->createMock(IManager::class);
118
+        $this->imipPlugin = new IMipPlugin(
119
+            $this->appConfig,
120
+            $this->mailer,
121
+            $this->logger,
122
+            $this->timeFactory,
123
+            $this->defaults,
124
+            $this->userSession,
125
+            $this->imipService,
126
+            $this->eventComparisonService,
127
+            $this->mailManager,
128
+            $this->getEmailValidatorWithStrictEmailCheck(),
129
+        );
130
+
131
+        // ITipMessage
132
+        $calendar = new VCalendar();
133
+        $event = new VEvent($calendar, 'VEVENT');
134
+        $event->UID = 'uid-1234';
135
+        $event->SEQUENCE = 1;
136
+        $event->SUMMARY = 'Lunch';
137
+        $event->DTSTART = new \DateTime('2025-06-20 12:30:00');
138
+        $organizer = new CalAddress($calendar, 'ORGANIZER', 'mailto:[email protected]');
139
+        $event->add($organizer);
140
+        $attendee = new CalAddress($calendar, 'ATTENDEE', 'mailto:[email protected]', ['RSVP' => 'TRUE', 'CN' => 'José']);
141
+        $event->add($attendee);
142
+        $calendar->add($event);
143
+        $this->itipMessage = new Message();
144
+        $this->itipMessage->method = 'REQUEST';
145
+        $this->itipMessage->message = $calendar;
146
+        $this->itipMessage->sender = 'mailto:[email protected]';
147
+        $this->itipMessage->senderName = 'Luigi';
148
+        $this->itipMessage->recipient = 'mailto:' . '[email protected]';
149
+    }
150
+
151
+    public function testCharsetMailer(): void {
152
+        // Arrange
153
+        $symfonyEmail = null;
154
+        $this->mailer->expects(self::once())
155
+            ->method('send')
156
+            ->willReturnCallback(function (IMessage $message) use (&$symfonyEmail): array {
157
+                if ($message instanceof \OC\Mail\Message) {
158
+                    $symfonyEmail = $message->getSymfonyEmail();
159
+                }
160
+                return [];
161
+            });
162
+
163
+        // Act
164
+        $this->imipPlugin->schedule($this->itipMessage);
165
+
166
+        // Assert
167
+        $this->assertNotNull($symfonyEmail);
168
+        $body = $symfonyEmail->getBody()->toString();
169
+        $this->assertStringContainsString('Content-Type: text/calendar; method=REQUEST; charset="utf-8"; name=event.ics', $body);
170
+    }
171
+
172
+    public function testCharsetMailProvider(): void {
173
+        // Arrange
174
+        $this->appConfig->method('getValueBool')
175
+            ->with('core', 'mail_providers_enabled', true)
176
+            ->willReturn(true);
177
+        $mailMessage = new MailProviderMessage();
178
+        $mailService = $this->createMockForIntersectionOfInterfaces([IService::class, IMessageSend::class]);
179
+        $mailService->method('initiateMessage')
180
+            ->willReturn($mailMessage);
181
+        $mailService->expects(self::once())
182
+            ->method('sendMessage');
183
+        $this->mailManager->method('findServiceByAddress')
184
+            ->willReturn($mailService);
185
+
186
+        // Act
187
+        $this->imipPlugin->schedule($this->itipMessage);
188
+
189
+        // Assert
190
+        $attachments = $mailMessage->getAttachments();
191
+        $this->assertCount(1, $attachments);
192
+        $this->assertStringContainsString('text/calendar; method=REQUEST; charset="utf-8"; name=event.ics', $attachments[0]->getType());
193
+    }
194 194
 }
Please login to merge, or discard this patch.