Completed
Push — master ( 5d14f8...2337bd )
by Robin
27:19 queued 16s
created
apps/dav/tests/unit/SystemTag/SystemTagMappingNodeTest.php 1 patch
Indentation   +136 added lines, -136 removed lines patch added patch discarded remove patch
@@ -18,140 +18,140 @@
 block discarded – undo
18 18
 use PHPUnit\Framework\MockObject\MockObject;
19 19
 
20 20
 class SystemTagMappingNodeTest extends \Test\TestCase {
21
-	private ISystemTagManager&MockObject $tagManager;
22
-	private ISystemTagObjectMapper&MockObject $tagMapper;
23
-	private IUser&MockObject $user;
24
-
25
-	protected function setUp(): void {
26
-		parent::setUp();
27
-
28
-		$this->tagManager = $this->createMock(ISystemTagManager::class);
29
-		$this->tagMapper = $this->createMock(ISystemTagObjectMapper::class);
30
-		$this->user = $this->createMock(IUser::class);
31
-	}
32
-
33
-	public function getMappingNode($tag = null, array $writableNodeIds = []) {
34
-		if ($tag === null) {
35
-			$tag = new SystemTag('1', 'Test', true, true);
36
-		}
37
-		return new SystemTagMappingNode(
38
-			$tag,
39
-			'123',
40
-			'files',
41
-			$this->user,
42
-			$this->tagManager,
43
-			$this->tagMapper,
44
-			fn ($id): bool => in_array($id, $writableNodeIds),
45
-		);
46
-	}
47
-
48
-	public function testGetters(): void {
49
-		$tag = new SystemTag('1', 'Test', true, false);
50
-		$node = $this->getMappingNode($tag);
51
-		$this->assertEquals('1', $node->getName());
52
-		$this->assertEquals($tag, $node->getSystemTag());
53
-		$this->assertEquals(123, $node->getObjectId());
54
-		$this->assertEquals('files', $node->getObjectType());
55
-	}
56
-
57
-	public function testDeleteTag(): void {
58
-		$node = $this->getMappingNode(null, [123]);
59
-		$this->tagManager->expects($this->once())
60
-			->method('canUserSeeTag')
61
-			->with($node->getSystemTag())
62
-			->willReturn(true);
63
-		$this->tagManager->expects($this->once())
64
-			->method('canUserAssignTag')
65
-			->with($node->getSystemTag())
66
-			->willReturn(true);
67
-		$this->tagManager->expects($this->never())
68
-			->method('deleteTags');
69
-		$this->tagMapper->expects($this->once())
70
-			->method('unassignTags')
71
-			->with(123, 'files', 1);
72
-
73
-		$node->delete();
74
-	}
75
-
76
-	public function testDeleteTagForbidden(): void {
77
-		$node = $this->getMappingNode();
78
-		$this->tagManager->expects($this->once())
79
-			->method('canUserSeeTag')
80
-			->with($node->getSystemTag())
81
-			->willReturn(true);
82
-		$this->tagManager->expects($this->once())
83
-			->method('canUserAssignTag')
84
-			->with($node->getSystemTag())
85
-			->willReturn(true);
86
-		$this->tagManager->expects($this->never())
87
-			->method('deleteTags');
88
-		$this->tagMapper->expects($this->never())
89
-			->method('unassignTags');
90
-
91
-		$this->expectException(\Sabre\DAV\Exception\Forbidden::class);
92
-		$node->delete();
93
-	}
94
-
95
-	public static function tagNodeDeleteProviderPermissionException(): array {
96
-		return [
97
-			[
98
-				// cannot unassign invisible tag
99
-				new SystemTag('1', 'Original', false, true),
100
-				'Sabre\DAV\Exception\NotFound',
101
-			],
102
-			[
103
-				// cannot unassign non-assignable tag
104
-				new SystemTag('1', 'Original', true, false),
105
-				'Sabre\DAV\Exception\Forbidden',
106
-			],
107
-		];
108
-	}
109
-
110
-	#[\PHPUnit\Framework\Attributes\DataProvider('tagNodeDeleteProviderPermissionException')]
111
-	public function testDeleteTagExpectedException(ISystemTag $tag, $expectedException): void {
112
-		$this->tagManager->expects($this->any())
113
-			->method('canUserSeeTag')
114
-			->with($tag)
115
-			->willReturn($tag->isUserVisible());
116
-		$this->tagManager->expects($this->any())
117
-			->method('canUserAssignTag')
118
-			->with($tag)
119
-			->willReturn($tag->isUserAssignable());
120
-		$this->tagManager->expects($this->never())
121
-			->method('deleteTags');
122
-		$this->tagMapper->expects($this->never())
123
-			->method('unassignTags');
124
-
125
-		$thrown = null;
126
-		try {
127
-			$this->getMappingNode($tag)->delete();
128
-		} catch (\Exception $e) {
129
-			$thrown = $e;
130
-		}
131
-
132
-		$this->assertInstanceOf($expectedException, $thrown);
133
-	}
134
-
135
-
136
-	public function testDeleteTagNotFound(): void {
137
-		$this->expectException(\Sabre\DAV\Exception\NotFound::class);
138
-
139
-		// assuming the tag existed at the time the node was created,
140
-		// but got deleted concurrently in the database
141
-		$tag = new SystemTag('1', 'Test', true, true);
142
-		$this->tagManager->expects($this->once())
143
-			->method('canUserSeeTag')
144
-			->with($tag)
145
-			->willReturn($tag->isUserVisible());
146
-		$this->tagManager->expects($this->once())
147
-			->method('canUserAssignTag')
148
-			->with($tag)
149
-			->willReturn($tag->isUserAssignable());
150
-		$this->tagMapper->expects($this->once())
151
-			->method('unassignTags')
152
-			->with(123, 'files', 1)
153
-			->willThrowException(new TagNotFoundException());
154
-
155
-		$this->getMappingNode($tag, [123])->delete();
156
-	}
21
+    private ISystemTagManager&MockObject $tagManager;
22
+    private ISystemTagObjectMapper&MockObject $tagMapper;
23
+    private IUser&MockObject $user;
24
+
25
+    protected function setUp(): void {
26
+        parent::setUp();
27
+
28
+        $this->tagManager = $this->createMock(ISystemTagManager::class);
29
+        $this->tagMapper = $this->createMock(ISystemTagObjectMapper::class);
30
+        $this->user = $this->createMock(IUser::class);
31
+    }
32
+
33
+    public function getMappingNode($tag = null, array $writableNodeIds = []) {
34
+        if ($tag === null) {
35
+            $tag = new SystemTag('1', 'Test', true, true);
36
+        }
37
+        return new SystemTagMappingNode(
38
+            $tag,
39
+            '123',
40
+            'files',
41
+            $this->user,
42
+            $this->tagManager,
43
+            $this->tagMapper,
44
+            fn ($id): bool => in_array($id, $writableNodeIds),
45
+        );
46
+    }
47
+
48
+    public function testGetters(): void {
49
+        $tag = new SystemTag('1', 'Test', true, false);
50
+        $node = $this->getMappingNode($tag);
51
+        $this->assertEquals('1', $node->getName());
52
+        $this->assertEquals($tag, $node->getSystemTag());
53
+        $this->assertEquals(123, $node->getObjectId());
54
+        $this->assertEquals('files', $node->getObjectType());
55
+    }
56
+
57
+    public function testDeleteTag(): void {
58
+        $node = $this->getMappingNode(null, [123]);
59
+        $this->tagManager->expects($this->once())
60
+            ->method('canUserSeeTag')
61
+            ->with($node->getSystemTag())
62
+            ->willReturn(true);
63
+        $this->tagManager->expects($this->once())
64
+            ->method('canUserAssignTag')
65
+            ->with($node->getSystemTag())
66
+            ->willReturn(true);
67
+        $this->tagManager->expects($this->never())
68
+            ->method('deleteTags');
69
+        $this->tagMapper->expects($this->once())
70
+            ->method('unassignTags')
71
+            ->with(123, 'files', 1);
72
+
73
+        $node->delete();
74
+    }
75
+
76
+    public function testDeleteTagForbidden(): void {
77
+        $node = $this->getMappingNode();
78
+        $this->tagManager->expects($this->once())
79
+            ->method('canUserSeeTag')
80
+            ->with($node->getSystemTag())
81
+            ->willReturn(true);
82
+        $this->tagManager->expects($this->once())
83
+            ->method('canUserAssignTag')
84
+            ->with($node->getSystemTag())
85
+            ->willReturn(true);
86
+        $this->tagManager->expects($this->never())
87
+            ->method('deleteTags');
88
+        $this->tagMapper->expects($this->never())
89
+            ->method('unassignTags');
90
+
91
+        $this->expectException(\Sabre\DAV\Exception\Forbidden::class);
92
+        $node->delete();
93
+    }
94
+
95
+    public static function tagNodeDeleteProviderPermissionException(): array {
96
+        return [
97
+            [
98
+                // cannot unassign invisible tag
99
+                new SystemTag('1', 'Original', false, true),
100
+                'Sabre\DAV\Exception\NotFound',
101
+            ],
102
+            [
103
+                // cannot unassign non-assignable tag
104
+                new SystemTag('1', 'Original', true, false),
105
+                'Sabre\DAV\Exception\Forbidden',
106
+            ],
107
+        ];
108
+    }
109
+
110
+    #[\PHPUnit\Framework\Attributes\DataProvider('tagNodeDeleteProviderPermissionException')]
111
+    public function testDeleteTagExpectedException(ISystemTag $tag, $expectedException): void {
112
+        $this->tagManager->expects($this->any())
113
+            ->method('canUserSeeTag')
114
+            ->with($tag)
115
+            ->willReturn($tag->isUserVisible());
116
+        $this->tagManager->expects($this->any())
117
+            ->method('canUserAssignTag')
118
+            ->with($tag)
119
+            ->willReturn($tag->isUserAssignable());
120
+        $this->tagManager->expects($this->never())
121
+            ->method('deleteTags');
122
+        $this->tagMapper->expects($this->never())
123
+            ->method('unassignTags');
124
+
125
+        $thrown = null;
126
+        try {
127
+            $this->getMappingNode($tag)->delete();
128
+        } catch (\Exception $e) {
129
+            $thrown = $e;
130
+        }
131
+
132
+        $this->assertInstanceOf($expectedException, $thrown);
133
+    }
134
+
135
+
136
+    public function testDeleteTagNotFound(): void {
137
+        $this->expectException(\Sabre\DAV\Exception\NotFound::class);
138
+
139
+        // assuming the tag existed at the time the node was created,
140
+        // but got deleted concurrently in the database
141
+        $tag = new SystemTag('1', 'Test', true, true);
142
+        $this->tagManager->expects($this->once())
143
+            ->method('canUserSeeTag')
144
+            ->with($tag)
145
+            ->willReturn($tag->isUserVisible());
146
+        $this->tagManager->expects($this->once())
147
+            ->method('canUserAssignTag')
148
+            ->with($tag)
149
+            ->willReturn($tag->isUserAssignable());
150
+        $this->tagMapper->expects($this->once())
151
+            ->method('unassignTags')
152
+            ->with(123, 'files', 1)
153
+            ->willThrowException(new TagNotFoundException());
154
+
155
+        $this->getMappingNode($tag, [123])->delete();
156
+    }
157 157
 }
Please login to merge, or discard this patch.
apps/dav/tests/unit/SystemTag/SystemTagNodeTest.php 1 patch
Indentation   +221 added lines, -221 removed lines patch added patch discarded remove patch
@@ -20,253 +20,253 @@
 block discarded – undo
20 20
 use Sabre\DAV\Exception\Forbidden;
21 21
 
22 22
 class SystemTagNodeTest extends \Test\TestCase {
23
-	private ISystemTagManager&MockObject $tagManager;
24
-	private ISystemTagObjectMapper&MockObject $tagMapper;
25
-	private IUser&MockObject $user;
23
+    private ISystemTagManager&MockObject $tagManager;
24
+    private ISystemTagObjectMapper&MockObject $tagMapper;
25
+    private IUser&MockObject $user;
26 26
 
27
-	protected function setUp(): void {
28
-		parent::setUp();
27
+    protected function setUp(): void {
28
+        parent::setUp();
29 29
 
30
-		$this->tagManager = $this->createMock(ISystemTagManager::class);
31
-		$this->tagMapper = $this->createMock(ISystemTagObjectMapper::class);
32
-		$this->user = $this->createMock(IUser::class);
33
-	}
30
+        $this->tagManager = $this->createMock(ISystemTagManager::class);
31
+        $this->tagMapper = $this->createMock(ISystemTagObjectMapper::class);
32
+        $this->user = $this->createMock(IUser::class);
33
+    }
34 34
 
35
-	protected function getTagNode($isAdmin = true, $tag = null) {
36
-		if ($tag === null) {
37
-			$tag = new SystemTag('1', 'Test', true, true);
38
-		}
39
-		return new SystemTagNode(
40
-			$tag,
41
-			$this->user,
42
-			$isAdmin,
43
-			$this->tagManager,
44
-			$this->tagMapper,
45
-		);
46
-	}
35
+    protected function getTagNode($isAdmin = true, $tag = null) {
36
+        if ($tag === null) {
37
+            $tag = new SystemTag('1', 'Test', true, true);
38
+        }
39
+        return new SystemTagNode(
40
+            $tag,
41
+            $this->user,
42
+            $isAdmin,
43
+            $this->tagManager,
44
+            $this->tagMapper,
45
+        );
46
+    }
47 47
 
48
-	public static function adminFlagProvider(): array {
49
-		return [[true], [false]];
50
-	}
48
+    public static function adminFlagProvider(): array {
49
+        return [[true], [false]];
50
+    }
51 51
 
52
-	#[\PHPUnit\Framework\Attributes\DataProvider('adminFlagProvider')]
53
-	public function testGetters(bool $isAdmin): void {
54
-		$tag = new SystemTag('1', 'Test', true, true);
55
-		$node = $this->getTagNode($isAdmin, $tag);
56
-		$this->assertEquals('1', $node->getName());
57
-		$this->assertEquals($tag, $node->getSystemTag());
58
-	}
52
+    #[\PHPUnit\Framework\Attributes\DataProvider('adminFlagProvider')]
53
+    public function testGetters(bool $isAdmin): void {
54
+        $tag = new SystemTag('1', 'Test', true, true);
55
+        $node = $this->getTagNode($isAdmin, $tag);
56
+        $this->assertEquals('1', $node->getName());
57
+        $this->assertEquals($tag, $node->getSystemTag());
58
+    }
59 59
 
60 60
 
61
-	public function testSetName(): void {
62
-		$this->expectException(\Sabre\DAV\Exception\MethodNotAllowed::class);
61
+    public function testSetName(): void {
62
+        $this->expectException(\Sabre\DAV\Exception\MethodNotAllowed::class);
63 63
 
64
-		$this->getTagNode()->setName('2');
65
-	}
64
+        $this->getTagNode()->setName('2');
65
+    }
66 66
 
67
-	public static function tagNodeProvider(): array {
68
-		return [
69
-			// admin
70
-			[
71
-				true,
72
-				new SystemTag('1', 'Original', true, true),
73
-				['Renamed', true, true, null]
74
-			],
75
-			[
76
-				true,
77
-				new SystemTag('1', 'Original', true, true),
78
-				['Original', false, false, null]
79
-			],
80
-			// non-admin
81
-			[
82
-				// renaming allowed
83
-				false,
84
-				new SystemTag('1', 'Original', true, true),
85
-				['Rename', true, true, '0082c9']
86
-			],
87
-		];
88
-	}
67
+    public static function tagNodeProvider(): array {
68
+        return [
69
+            // admin
70
+            [
71
+                true,
72
+                new SystemTag('1', 'Original', true, true),
73
+                ['Renamed', true, true, null]
74
+            ],
75
+            [
76
+                true,
77
+                new SystemTag('1', 'Original', true, true),
78
+                ['Original', false, false, null]
79
+            ],
80
+            // non-admin
81
+            [
82
+                // renaming allowed
83
+                false,
84
+                new SystemTag('1', 'Original', true, true),
85
+                ['Rename', true, true, '0082c9']
86
+            ],
87
+        ];
88
+    }
89 89
 
90
-	#[\PHPUnit\Framework\Attributes\DataProvider('tagNodeProvider')]
91
-	public function testUpdateTag(bool $isAdmin, ISystemTag $originalTag, array $changedArgs): void {
92
-		$this->tagManager->expects($this->once())
93
-			->method('canUserSeeTag')
94
-			->with($originalTag)
95
-			->willReturn($originalTag->isUserVisible() || $isAdmin);
96
-		$this->tagManager->expects($this->once())
97
-			->method('canUserAssignTag')
98
-			->with($originalTag)
99
-			->willReturn($originalTag->isUserAssignable() || $isAdmin);
100
-		$this->tagManager->expects($this->once())
101
-			->method('updateTag')
102
-			->with(1, $changedArgs[0], $changedArgs[1], $changedArgs[2], $changedArgs[3]);
103
-		$this->getTagNode($isAdmin, $originalTag)
104
-			->update($changedArgs[0], $changedArgs[1], $changedArgs[2], $changedArgs[3]);
105
-	}
90
+    #[\PHPUnit\Framework\Attributes\DataProvider('tagNodeProvider')]
91
+    public function testUpdateTag(bool $isAdmin, ISystemTag $originalTag, array $changedArgs): void {
92
+        $this->tagManager->expects($this->once())
93
+            ->method('canUserSeeTag')
94
+            ->with($originalTag)
95
+            ->willReturn($originalTag->isUserVisible() || $isAdmin);
96
+        $this->tagManager->expects($this->once())
97
+            ->method('canUserAssignTag')
98
+            ->with($originalTag)
99
+            ->willReturn($originalTag->isUserAssignable() || $isAdmin);
100
+        $this->tagManager->expects($this->once())
101
+            ->method('updateTag')
102
+            ->with(1, $changedArgs[0], $changedArgs[1], $changedArgs[2], $changedArgs[3]);
103
+        $this->getTagNode($isAdmin, $originalTag)
104
+            ->update($changedArgs[0], $changedArgs[1], $changedArgs[2], $changedArgs[3]);
105
+    }
106 106
 
107
-	public static function tagNodeProviderPermissionException(): array {
108
-		return [
109
-			[
110
-				// changing permissions not allowed
111
-				new SystemTag('1', 'Original', true, true),
112
-				['Original', false, true, ''],
113
-				'Sabre\DAV\Exception\Forbidden',
114
-			],
115
-			[
116
-				// changing permissions not allowed
117
-				new SystemTag('1', 'Original', true, true),
118
-				['Original', true, false, ''],
119
-				'Sabre\DAV\Exception\Forbidden',
120
-			],
121
-			[
122
-				// changing permissions not allowed
123
-				new SystemTag('1', 'Original', true, true),
124
-				['Original', false, false, ''],
125
-				'Sabre\DAV\Exception\Forbidden',
126
-			],
127
-			[
128
-				// changing non-assignable not allowed
129
-				new SystemTag('1', 'Original', true, false),
130
-				['Rename', true, false, ''],
131
-				'Sabre\DAV\Exception\Forbidden',
132
-			],
133
-			[
134
-				// changing non-assignable not allowed
135
-				new SystemTag('1', 'Original', true, false),
136
-				['Original', true, true, ''],
137
-				'Sabre\DAV\Exception\Forbidden',
138
-			],
139
-			[
140
-				// invisible tag does not exist
141
-				new SystemTag('1', 'Original', false, false),
142
-				['Rename', false, false, ''],
143
-				'Sabre\DAV\Exception\NotFound',
144
-			],
145
-		];
146
-	}
107
+    public static function tagNodeProviderPermissionException(): array {
108
+        return [
109
+            [
110
+                // changing permissions not allowed
111
+                new SystemTag('1', 'Original', true, true),
112
+                ['Original', false, true, ''],
113
+                'Sabre\DAV\Exception\Forbidden',
114
+            ],
115
+            [
116
+                // changing permissions not allowed
117
+                new SystemTag('1', 'Original', true, true),
118
+                ['Original', true, false, ''],
119
+                'Sabre\DAV\Exception\Forbidden',
120
+            ],
121
+            [
122
+                // changing permissions not allowed
123
+                new SystemTag('1', 'Original', true, true),
124
+                ['Original', false, false, ''],
125
+                'Sabre\DAV\Exception\Forbidden',
126
+            ],
127
+            [
128
+                // changing non-assignable not allowed
129
+                new SystemTag('1', 'Original', true, false),
130
+                ['Rename', true, false, ''],
131
+                'Sabre\DAV\Exception\Forbidden',
132
+            ],
133
+            [
134
+                // changing non-assignable not allowed
135
+                new SystemTag('1', 'Original', true, false),
136
+                ['Original', true, true, ''],
137
+                'Sabre\DAV\Exception\Forbidden',
138
+            ],
139
+            [
140
+                // invisible tag does not exist
141
+                new SystemTag('1', 'Original', false, false),
142
+                ['Rename', false, false, ''],
143
+                'Sabre\DAV\Exception\NotFound',
144
+            ],
145
+        ];
146
+    }
147 147
 
148
-	#[\PHPUnit\Framework\Attributes\DataProvider('tagNodeProviderPermissionException')]
149
-	public function testUpdateTagPermissionException(ISystemTag $originalTag, array $changedArgs, string $expectedException): void {
150
-		$this->tagManager->expects($this->any())
151
-			->method('canUserSeeTag')
152
-			->with($originalTag)
153
-			->willReturn($originalTag->isUserVisible());
154
-		$this->tagManager->expects($this->any())
155
-			->method('canUserAssignTag')
156
-			->with($originalTag)
157
-			->willReturn($originalTag->isUserAssignable());
158
-		$this->tagManager->expects($this->never())
159
-			->method('updateTag');
148
+    #[\PHPUnit\Framework\Attributes\DataProvider('tagNodeProviderPermissionException')]
149
+    public function testUpdateTagPermissionException(ISystemTag $originalTag, array $changedArgs, string $expectedException): void {
150
+        $this->tagManager->expects($this->any())
151
+            ->method('canUserSeeTag')
152
+            ->with($originalTag)
153
+            ->willReturn($originalTag->isUserVisible());
154
+        $this->tagManager->expects($this->any())
155
+            ->method('canUserAssignTag')
156
+            ->with($originalTag)
157
+            ->willReturn($originalTag->isUserAssignable());
158
+        $this->tagManager->expects($this->never())
159
+            ->method('updateTag');
160 160
 
161
-		$thrown = null;
161
+        $thrown = null;
162 162
 
163
-		try {
164
-			$this->getTagNode(false, $originalTag)
165
-				->update($changedArgs[0], $changedArgs[1], $changedArgs[2], $changedArgs[3]);
166
-		} catch (\Exception $e) {
167
-			$thrown = $e;
168
-		}
163
+        try {
164
+            $this->getTagNode(false, $originalTag)
165
+                ->update($changedArgs[0], $changedArgs[1], $changedArgs[2], $changedArgs[3]);
166
+        } catch (\Exception $e) {
167
+            $thrown = $e;
168
+        }
169 169
 
170
-		$this->assertInstanceOf($expectedException, $thrown);
171
-	}
170
+        $this->assertInstanceOf($expectedException, $thrown);
171
+    }
172 172
 
173 173
 
174
-	public function testUpdateTagAlreadyExists(): void {
175
-		$this->expectException(\Sabre\DAV\Exception\Conflict::class);
174
+    public function testUpdateTagAlreadyExists(): void {
175
+        $this->expectException(\Sabre\DAV\Exception\Conflict::class);
176 176
 
177
-		$tag = new SystemTag('1', 'tag1', true, true);
178
-		$this->tagManager->expects($this->any())
179
-			->method('canUserSeeTag')
180
-			->with($tag)
181
-			->willReturn(true);
182
-		$this->tagManager->expects($this->any())
183
-			->method('canUserAssignTag')
184
-			->with($tag)
185
-			->willReturn(true);
186
-		$this->tagManager->expects($this->once())
187
-			->method('updateTag')
188
-			->with(1, 'Renamed', true, true)
189
-			->willThrowException(new TagAlreadyExistsException());
190
-		$this->getTagNode(false, $tag)->update('Renamed', true, true, null);
191
-	}
177
+        $tag = new SystemTag('1', 'tag1', true, true);
178
+        $this->tagManager->expects($this->any())
179
+            ->method('canUserSeeTag')
180
+            ->with($tag)
181
+            ->willReturn(true);
182
+        $this->tagManager->expects($this->any())
183
+            ->method('canUserAssignTag')
184
+            ->with($tag)
185
+            ->willReturn(true);
186
+        $this->tagManager->expects($this->once())
187
+            ->method('updateTag')
188
+            ->with(1, 'Renamed', true, true)
189
+            ->willThrowException(new TagAlreadyExistsException());
190
+        $this->getTagNode(false, $tag)->update('Renamed', true, true, null);
191
+    }
192 192
 
193 193
 
194
-	public function testUpdateTagNotFound(): void {
195
-		$this->expectException(\Sabre\DAV\Exception\NotFound::class);
194
+    public function testUpdateTagNotFound(): void {
195
+        $this->expectException(\Sabre\DAV\Exception\NotFound::class);
196 196
 
197
-		$tag = new SystemTag('1', 'tag1', true, true);
198
-		$this->tagManager->expects($this->any())
199
-			->method('canUserSeeTag')
200
-			->with($tag)
201
-			->willReturn(true);
202
-		$this->tagManager->expects($this->any())
203
-			->method('canUserAssignTag')
204
-			->with($tag)
205
-			->willReturn(true);
206
-		$this->tagManager->expects($this->once())
207
-			->method('updateTag')
208
-			->with(1, 'Renamed', true, true)
209
-			->willThrowException(new TagNotFoundException());
210
-		$this->getTagNode(false, $tag)->update('Renamed', true, true, null);
211
-	}
197
+        $tag = new SystemTag('1', 'tag1', true, true);
198
+        $this->tagManager->expects($this->any())
199
+            ->method('canUserSeeTag')
200
+            ->with($tag)
201
+            ->willReturn(true);
202
+        $this->tagManager->expects($this->any())
203
+            ->method('canUserAssignTag')
204
+            ->with($tag)
205
+            ->willReturn(true);
206
+        $this->tagManager->expects($this->once())
207
+            ->method('updateTag')
208
+            ->with(1, 'Renamed', true, true)
209
+            ->willThrowException(new TagNotFoundException());
210
+        $this->getTagNode(false, $tag)->update('Renamed', true, true, null);
211
+    }
212 212
 
213
-	#[\PHPUnit\Framework\Attributes\DataProvider('adminFlagProvider')]
214
-	public function testDeleteTag(bool $isAdmin): void {
215
-		$tag = new SystemTag('1', 'tag1', true, true);
216
-		$this->tagManager->expects($isAdmin ? $this->once() : $this->never())
217
-			->method('canUserSeeTag')
218
-			->with($tag)
219
-			->willReturn(true);
220
-		$this->tagManager->expects($isAdmin ? $this->once() : $this->never())
221
-			->method('deleteTags')
222
-			->with('1');
223
-		if (!$isAdmin) {
224
-			$this->expectException(Forbidden::class);
225
-		}
226
-		$this->getTagNode($isAdmin, $tag)->delete();
227
-	}
213
+    #[\PHPUnit\Framework\Attributes\DataProvider('adminFlagProvider')]
214
+    public function testDeleteTag(bool $isAdmin): void {
215
+        $tag = new SystemTag('1', 'tag1', true, true);
216
+        $this->tagManager->expects($isAdmin ? $this->once() : $this->never())
217
+            ->method('canUserSeeTag')
218
+            ->with($tag)
219
+            ->willReturn(true);
220
+        $this->tagManager->expects($isAdmin ? $this->once() : $this->never())
221
+            ->method('deleteTags')
222
+            ->with('1');
223
+        if (!$isAdmin) {
224
+            $this->expectException(Forbidden::class);
225
+        }
226
+        $this->getTagNode($isAdmin, $tag)->delete();
227
+    }
228 228
 
229
-	public static function tagNodeDeleteProviderPermissionException(): array {
230
-		return [
231
-			[
232
-				// cannot delete invisible tag
233
-				new SystemTag('1', 'Original', false, true),
234
-				'Sabre\DAV\Exception\Forbidden',
235
-			],
236
-			[
237
-				// cannot delete non-assignable tag
238
-				new SystemTag('1', 'Original', true, false),
239
-				'Sabre\DAV\Exception\Forbidden',
240
-			],
241
-		];
242
-	}
229
+    public static function tagNodeDeleteProviderPermissionException(): array {
230
+        return [
231
+            [
232
+                // cannot delete invisible tag
233
+                new SystemTag('1', 'Original', false, true),
234
+                'Sabre\DAV\Exception\Forbidden',
235
+            ],
236
+            [
237
+                // cannot delete non-assignable tag
238
+                new SystemTag('1', 'Original', true, false),
239
+                'Sabre\DAV\Exception\Forbidden',
240
+            ],
241
+        ];
242
+    }
243 243
 
244
-	#[\PHPUnit\Framework\Attributes\DataProvider('tagNodeDeleteProviderPermissionException')]
245
-	public function testDeleteTagPermissionException(ISystemTag $tag, string $expectedException): void {
246
-		$this->tagManager->expects($this->any())
247
-			->method('canUserSeeTag')
248
-			->with($tag)
249
-			->willReturn($tag->isUserVisible());
250
-		$this->tagManager->expects($this->never())
251
-			->method('deleteTags');
244
+    #[\PHPUnit\Framework\Attributes\DataProvider('tagNodeDeleteProviderPermissionException')]
245
+    public function testDeleteTagPermissionException(ISystemTag $tag, string $expectedException): void {
246
+        $this->tagManager->expects($this->any())
247
+            ->method('canUserSeeTag')
248
+            ->with($tag)
249
+            ->willReturn($tag->isUserVisible());
250
+        $this->tagManager->expects($this->never())
251
+            ->method('deleteTags');
252 252
 
253
-		$this->expectException($expectedException);
254
-		$this->getTagNode(false, $tag)->delete();
255
-	}
253
+        $this->expectException($expectedException);
254
+        $this->getTagNode(false, $tag)->delete();
255
+    }
256 256
 
257 257
 
258
-	public function testDeleteTagNotFound(): void {
259
-		$this->expectException(\Sabre\DAV\Exception\NotFound::class);
258
+    public function testDeleteTagNotFound(): void {
259
+        $this->expectException(\Sabre\DAV\Exception\NotFound::class);
260 260
 
261
-		$tag = new SystemTag('1', 'tag1', true, true);
262
-		$this->tagManager->expects($this->any())
263
-			->method('canUserSeeTag')
264
-			->with($tag)
265
-			->willReturn($tag->isUserVisible());
266
-		$this->tagManager->expects($this->once())
267
-			->method('deleteTags')
268
-			->with('1')
269
-			->willThrowException(new TagNotFoundException());
270
-		$this->getTagNode(true, $tag)->delete();
271
-	}
261
+        $tag = new SystemTag('1', 'tag1', true, true);
262
+        $this->tagManager->expects($this->any())
263
+            ->method('canUserSeeTag')
264
+            ->with($tag)
265
+            ->willReturn($tag->isUserVisible());
266
+        $this->tagManager->expects($this->once())
267
+            ->method('deleteTags')
268
+            ->with('1')
269
+            ->willThrowException(new TagNotFoundException());
270
+        $this->getTagNode(true, $tag)->delete();
271
+    }
272 272
 }
Please login to merge, or discard this patch.
apps/dav/tests/unit/ServerTest.php 1 patch
Indentation   +19 added lines, -19 removed lines patch added patch discarded remove patch
@@ -20,23 +20,23 @@
 block discarded – undo
20 20
  */
21 21
 class ServerTest extends \Test\TestCase {
22 22
 
23
-	#[\PHPUnit\Framework\Attributes\DataProvider('providesUris')]
24
-	public function test(string $uri, array $plugins): void {
25
-		/** @var IRequest | \PHPUnit\Framework\MockObject\MockObject $r */
26
-		$r = $this->createMock(IRequest::class);
27
-		$r->expects($this->any())->method('getRequestUri')->willReturn($uri);
28
-		$this->loginAsUser('admin');
29
-		$s = new Server($r, '/');
30
-		$this->assertNotNull($s->server);
31
-		foreach ($plugins as $plugin) {
32
-			$this->assertNotNull($s->server->getPlugin($plugin));
33
-		}
34
-	}
35
-	public static function providesUris(): array {
36
-		return [
37
-			'principals' => ['principals/users/admin', ['caldav', 'oc-resource-sharing', 'carddav']],
38
-			'calendars' => ['calendars/admin', ['caldav', 'oc-resource-sharing']],
39
-			'addressbooks' => ['addressbooks/admin', ['carddav', 'oc-resource-sharing']],
40
-		];
41
-	}
23
+    #[\PHPUnit\Framework\Attributes\DataProvider('providesUris')]
24
+    public function test(string $uri, array $plugins): void {
25
+        /** @var IRequest | \PHPUnit\Framework\MockObject\MockObject $r */
26
+        $r = $this->createMock(IRequest::class);
27
+        $r->expects($this->any())->method('getRequestUri')->willReturn($uri);
28
+        $this->loginAsUser('admin');
29
+        $s = new Server($r, '/');
30
+        $this->assertNotNull($s->server);
31
+        foreach ($plugins as $plugin) {
32
+            $this->assertNotNull($s->server->getPlugin($plugin));
33
+        }
34
+    }
35
+    public static function providesUris(): array {
36
+        return [
37
+            'principals' => ['principals/users/admin', ['caldav', 'oc-resource-sharing', 'carddav']],
38
+            'calendars' => ['calendars/admin', ['caldav', 'oc-resource-sharing']],
39
+            'addressbooks' => ['addressbooks/admin', ['carddav', 'oc-resource-sharing']],
40
+        ];
41
+    }
42 42
 }
Please login to merge, or discard this patch.
apps/dav/tests/unit/CalDAV/PublicCalendarTest.php 1 patch
Indentation   +91 added lines, -91 removed lines patch added patch discarded remove patch
@@ -16,51 +16,51 @@  discard block
 block discarded – undo
16 16
 
17 17
 class PublicCalendarTest extends CalendarTest {
18 18
 
19
-	#[\PHPUnit\Framework\Attributes\DataProvider('providesConfidentialClassificationData')]
20
-	public function testPrivateClassification(int $expectedChildren, bool $isShared): void {
21
-		$calObject0 = ['uri' => 'event-0', 'classification' => CalDavBackend::CLASSIFICATION_PUBLIC];
22
-		$calObject1 = ['uri' => 'event-1', 'classification' => CalDavBackend::CLASSIFICATION_CONFIDENTIAL];
23
-		$calObject2 = ['uri' => 'event-2', 'classification' => CalDavBackend::CLASSIFICATION_PRIVATE];
24
-
25
-		/** @var CalDavBackend&MockObject $backend */
26
-		$backend = $this->getMockBuilder(CalDavBackend::class)->disableOriginalConstructor()->getMock();
27
-		$backend->expects($this->any())->method('getCalendarObjects')->willReturn([
28
-			$calObject0, $calObject1, $calObject2
29
-		]);
30
-		$backend->expects($this->any())->method('getMultipleCalendarObjects')
31
-			->with(666, ['event-0', 'event-1', 'event-2'])
32
-			->willReturn([
33
-				$calObject0, $calObject1, $calObject2
34
-			]);
35
-		$backend->expects($this->any())->method('getCalendarObject')
36
-			->willReturn($calObject2)->with(666, 'event-2');
37
-		$backend->expects($this->any())->method('applyShareAcl')->willReturnArgument(1);
38
-
39
-		$calendarInfo = [
40
-			'{http://owncloud.org/ns}owner-principal' => 'user2',
41
-			'principaluri' => 'user2',
42
-			'id' => 666,
43
-			'uri' => 'cal',
44
-		];
45
-		/** @var IConfig&MockObject $config */
46
-		$config = $this->createMock(IConfig::class);
47
-		/** @var LoggerInterface&MockObject $logger */
48
-		$logger = $this->createMock(LoggerInterface::class);
49
-		$c = new PublicCalendar($backend, $calendarInfo, $this->l10n, $config, $logger);
50
-		$children = $c->getChildren();
51
-		$this->assertEquals(2, count($children));
52
-		$children = $c->getMultipleChildren(['event-0', 'event-1', 'event-2']);
53
-		$this->assertEquals(2, count($children));
54
-
55
-		$this->assertFalse($c->childExists('event-2'));
56
-	}
57
-
58
-	#[\PHPUnit\Framework\Attributes\DataProvider('providesConfidentialClassificationData')]
59
-	public function testConfidentialClassification(int $expectedChildren, bool $isShared): void {
60
-		$start = '20160609';
61
-		$end = '20160610';
62
-
63
-		$calData = <<<EOD
19
+    #[\PHPUnit\Framework\Attributes\DataProvider('providesConfidentialClassificationData')]
20
+    public function testPrivateClassification(int $expectedChildren, bool $isShared): void {
21
+        $calObject0 = ['uri' => 'event-0', 'classification' => CalDavBackend::CLASSIFICATION_PUBLIC];
22
+        $calObject1 = ['uri' => 'event-1', 'classification' => CalDavBackend::CLASSIFICATION_CONFIDENTIAL];
23
+        $calObject2 = ['uri' => 'event-2', 'classification' => CalDavBackend::CLASSIFICATION_PRIVATE];
24
+
25
+        /** @var CalDavBackend&MockObject $backend */
26
+        $backend = $this->getMockBuilder(CalDavBackend::class)->disableOriginalConstructor()->getMock();
27
+        $backend->expects($this->any())->method('getCalendarObjects')->willReturn([
28
+            $calObject0, $calObject1, $calObject2
29
+        ]);
30
+        $backend->expects($this->any())->method('getMultipleCalendarObjects')
31
+            ->with(666, ['event-0', 'event-1', 'event-2'])
32
+            ->willReturn([
33
+                $calObject0, $calObject1, $calObject2
34
+            ]);
35
+        $backend->expects($this->any())->method('getCalendarObject')
36
+            ->willReturn($calObject2)->with(666, 'event-2');
37
+        $backend->expects($this->any())->method('applyShareAcl')->willReturnArgument(1);
38
+
39
+        $calendarInfo = [
40
+            '{http://owncloud.org/ns}owner-principal' => 'user2',
41
+            'principaluri' => 'user2',
42
+            'id' => 666,
43
+            'uri' => 'cal',
44
+        ];
45
+        /** @var IConfig&MockObject $config */
46
+        $config = $this->createMock(IConfig::class);
47
+        /** @var LoggerInterface&MockObject $logger */
48
+        $logger = $this->createMock(LoggerInterface::class);
49
+        $c = new PublicCalendar($backend, $calendarInfo, $this->l10n, $config, $logger);
50
+        $children = $c->getChildren();
51
+        $this->assertEquals(2, count($children));
52
+        $children = $c->getMultipleChildren(['event-0', 'event-1', 'event-2']);
53
+        $this->assertEquals(2, count($children));
54
+
55
+        $this->assertFalse($c->childExists('event-2'));
56
+    }
57
+
58
+    #[\PHPUnit\Framework\Attributes\DataProvider('providesConfidentialClassificationData')]
59
+    public function testConfidentialClassification(int $expectedChildren, bool $isShared): void {
60
+        $start = '20160609';
61
+        $end = '20160610';
62
+
63
+        $calData = <<<EOD
64 64
 BEGIN:VCALENDAR
65 65
 PRODID:-//ownCloud calendar v1.2.2
66 66
 BEGIN:VEVENT
@@ -102,50 +102,50 @@  discard block
 block discarded – undo
102 102
 END:VCALENDAR
103 103
 EOD;
104 104
 
105
-		$calObject0 = ['uri' => 'event-0', 'classification' => CalDavBackend::CLASSIFICATION_PUBLIC];
106
-		$calObject1 = ['uri' => 'event-1', 'classification' => CalDavBackend::CLASSIFICATION_CONFIDENTIAL, 'calendardata' => $calData];
107
-		$calObject2 = ['uri' => 'event-2', 'classification' => CalDavBackend::CLASSIFICATION_PRIVATE];
108
-
109
-		/** @var CalDavBackend&MockObject $backend */
110
-		$backend = $this->getMockBuilder(CalDavBackend::class)->disableOriginalConstructor()->getMock();
111
-		$backend->expects($this->any())->method('getCalendarObjects')->willReturn([
112
-			$calObject0, $calObject1, $calObject2
113
-		]);
114
-		$backend->expects($this->any())->method('getMultipleCalendarObjects')
115
-			->with(666, ['event-0', 'event-1', 'event-2'])
116
-			->willReturn([
117
-				$calObject0, $calObject1, $calObject2
118
-			]);
119
-		$backend->expects($this->any())->method('getCalendarObject')
120
-			->willReturn($calObject1)->with(666, 'event-1');
121
-		$backend->expects($this->any())->method('applyShareAcl')->willReturnArgument(1);
122
-
123
-		$calendarInfo = [
124
-			'{http://owncloud.org/ns}owner-principal' => 'user1',
125
-			'principaluri' => 'user2',
126
-			'id' => 666,
127
-			'uri' => 'cal',
128
-		];
129
-		/** @var IConfig&MockObject $config */
130
-		$config = $this->createMock(IConfig::class);
131
-		/** @var LoggerInterface&MockObject $logger */
132
-		$logger = $this->createMock(LoggerInterface::class);
133
-		$c = new PublicCalendar($backend, $calendarInfo, $this->l10n, $config, $logger);
134
-
135
-		$this->assertEquals(count($c->getChildren()), 2);
136
-
137
-		// test private event
138
-		$privateEvent = $c->getChild('event-1');
139
-		$calData = $privateEvent->get();
140
-		$event = Reader::read($calData);
141
-
142
-		$this->assertEquals($start, $event->VEVENT->DTSTART->getValue());
143
-		$this->assertEquals($end, $event->VEVENT->DTEND->getValue());
144
-
145
-		$this->assertEquals('Busy', $event->VEVENT->SUMMARY->getValue());
146
-		$this->assertArrayNotHasKey('ATTENDEE', $event->VEVENT);
147
-		$this->assertArrayNotHasKey('LOCATION', $event->VEVENT);
148
-		$this->assertArrayNotHasKey('DESCRIPTION', $event->VEVENT);
149
-		$this->assertArrayNotHasKey('ORGANIZER', $event->VEVENT);
150
-	}
105
+        $calObject0 = ['uri' => 'event-0', 'classification' => CalDavBackend::CLASSIFICATION_PUBLIC];
106
+        $calObject1 = ['uri' => 'event-1', 'classification' => CalDavBackend::CLASSIFICATION_CONFIDENTIAL, 'calendardata' => $calData];
107
+        $calObject2 = ['uri' => 'event-2', 'classification' => CalDavBackend::CLASSIFICATION_PRIVATE];
108
+
109
+        /** @var CalDavBackend&MockObject $backend */
110
+        $backend = $this->getMockBuilder(CalDavBackend::class)->disableOriginalConstructor()->getMock();
111
+        $backend->expects($this->any())->method('getCalendarObjects')->willReturn([
112
+            $calObject0, $calObject1, $calObject2
113
+        ]);
114
+        $backend->expects($this->any())->method('getMultipleCalendarObjects')
115
+            ->with(666, ['event-0', 'event-1', 'event-2'])
116
+            ->willReturn([
117
+                $calObject0, $calObject1, $calObject2
118
+            ]);
119
+        $backend->expects($this->any())->method('getCalendarObject')
120
+            ->willReturn($calObject1)->with(666, 'event-1');
121
+        $backend->expects($this->any())->method('applyShareAcl')->willReturnArgument(1);
122
+
123
+        $calendarInfo = [
124
+            '{http://owncloud.org/ns}owner-principal' => 'user1',
125
+            'principaluri' => 'user2',
126
+            'id' => 666,
127
+            'uri' => 'cal',
128
+        ];
129
+        /** @var IConfig&MockObject $config */
130
+        $config = $this->createMock(IConfig::class);
131
+        /** @var LoggerInterface&MockObject $logger */
132
+        $logger = $this->createMock(LoggerInterface::class);
133
+        $c = new PublicCalendar($backend, $calendarInfo, $this->l10n, $config, $logger);
134
+
135
+        $this->assertEquals(count($c->getChildren()), 2);
136
+
137
+        // test private event
138
+        $privateEvent = $c->getChild('event-1');
139
+        $calData = $privateEvent->get();
140
+        $event = Reader::read($calData);
141
+
142
+        $this->assertEquals($start, $event->VEVENT->DTSTART->getValue());
143
+        $this->assertEquals($end, $event->VEVENT->DTEND->getValue());
144
+
145
+        $this->assertEquals('Busy', $event->VEVENT->SUMMARY->getValue());
146
+        $this->assertArrayNotHasKey('ATTENDEE', $event->VEVENT);
147
+        $this->assertArrayNotHasKey('LOCATION', $event->VEVENT);
148
+        $this->assertArrayNotHasKey('DESCRIPTION', $event->VEVENT);
149
+        $this->assertArrayNotHasKey('ORGANIZER', $event->VEVENT);
150
+    }
151 151
 }
Please login to merge, or discard this patch.
apps/dav/tests/unit/CalDAV/Integration/ExternalCalendarTest.php 1 patch
Indentation   +86 added lines, -86 removed lines patch added patch discarded remove patch
@@ -12,90 +12,90 @@
 block discarded – undo
12 12
 use Test\TestCase;
13 13
 
14 14
 class ExternalCalendarTest extends TestCase {
15
-	private ExternalCalendar&MockObject $abstractExternalCalendar;
16
-
17
-	protected function setUp(): void {
18
-		parent::setUp();
19
-
20
-		$this->abstractExternalCalendar
21
-			= $this->getMockForAbstractClass(ExternalCalendar::class, ['example-app-id', 'calendar-uri-in-backend']);
22
-	}
23
-
24
-	public function testGetName():void {
25
-		// Check that the correct name is returned
26
-		$this->assertEquals('app-generated--example-app-id--calendar-uri-in-backend',
27
-			$this->abstractExternalCalendar->getName());
28
-
29
-		// Check that the method is final and can't be overridden by other classes
30
-		$reflectionMethod = new \ReflectionMethod(ExternalCalendar::class, 'getName');
31
-		$this->assertTrue($reflectionMethod->isFinal());
32
-	}
33
-
34
-	public function testSetName():void {
35
-		// Check that the method is final and can't be overridden by other classes
36
-		$reflectionMethod = new \ReflectionMethod(ExternalCalendar::class, 'setName');
37
-		$this->assertTrue($reflectionMethod->isFinal());
38
-
39
-		$this->expectException(\Sabre\DAV\Exception\MethodNotAllowed::class);
40
-		$this->expectExceptionMessage('Renaming calendars is not yet supported');
41
-
42
-		$this->abstractExternalCalendar->setName('other-name');
43
-	}
44
-
45
-	public function createDirectory(): void {
46
-		// Check that the method is final and can't be overridden by other classes
47
-		$reflectionMethod = new \ReflectionMethod(ExternalCalendar::class, 'createDirectory');
48
-		$this->assertTrue($reflectionMethod->isFinal());
49
-
50
-		$this->expectException(\Sabre\DAV\Exception\MethodNotAllowed::class);
51
-		$this->expectExceptionMessage('Creating collections in calendar objects is not allowed');
52
-
53
-		$this->abstractExternalCalendar->createDirectory('other-name');
54
-	}
55
-
56
-	public function testIsAppGeneratedCalendar():void {
57
-		$this->assertFalse(ExternalCalendar::isAppGeneratedCalendar('personal'));
58
-		$this->assertFalse(ExternalCalendar::isAppGeneratedCalendar('work'));
59
-		$this->assertFalse(ExternalCalendar::isAppGeneratedCalendar('contact_birthdays'));
60
-		$this->assertFalse(ExternalCalendar::isAppGeneratedCalendar('company'));
61
-		$this->assertFalse(ExternalCalendar::isAppGeneratedCalendar('app-generated'));
62
-		$this->assertFalse(ExternalCalendar::isAppGeneratedCalendar('app-generated--example'));
63
-
64
-		$this->assertTrue(ExternalCalendar::isAppGeneratedCalendar('app-generated--deck--board-1'));
65
-		$this->assertTrue(ExternalCalendar::isAppGeneratedCalendar('app-generated--example--foo-2'));
66
-		$this->assertTrue(ExternalCalendar::isAppGeneratedCalendar('app-generated--example--foo--2'));
67
-	}
68
-
69
-	#[\PHPUnit\Framework\Attributes\DataProvider('splitAppGeneratedCalendarUriDataProvider')]
70
-	public function testSplitAppGeneratedCalendarUriInvalid(string $name):void {
71
-		$this->expectException(\InvalidArgumentException::class);
72
-		$this->expectExceptionMessage('Provided calendar uri was not app-generated');
73
-
74
-		ExternalCalendar::splitAppGeneratedCalendarUri($name);
75
-	}
76
-
77
-	public static function splitAppGeneratedCalendarUriDataProvider():array {
78
-		return [
79
-			['personal'],
80
-			['foo_shared_by_admin'],
81
-			['contact_birthdays'],
82
-		];
83
-	}
84
-
85
-	public function testSplitAppGeneratedCalendarUri():void {
86
-		$this->assertEquals(['deck', 'board-1'], ExternalCalendar::splitAppGeneratedCalendarUri('app-generated--deck--board-1'));
87
-		$this->assertEquals(['example', 'foo-2'], ExternalCalendar::splitAppGeneratedCalendarUri('app-generated--example--foo-2'));
88
-		$this->assertEquals(['example', 'foo--2'], ExternalCalendar::splitAppGeneratedCalendarUri('app-generated--example--foo--2'));
89
-	}
90
-
91
-	public function testDoesViolateReservedName():void {
92
-		$this->assertFalse(ExternalCalendar::doesViolateReservedName('personal'));
93
-		$this->assertFalse(ExternalCalendar::doesViolateReservedName('work'));
94
-		$this->assertFalse(ExternalCalendar::doesViolateReservedName('contact_birthdays'));
95
-		$this->assertFalse(ExternalCalendar::doesViolateReservedName('company'));
96
-
97
-		$this->assertTrue(ExternalCalendar::doesViolateReservedName('app-generated'));
98
-		$this->assertTrue(ExternalCalendar::doesViolateReservedName('app-generated-calendar'));
99
-		$this->assertTrue(ExternalCalendar::doesViolateReservedName('app-generated--deck-123'));
100
-	}
15
+    private ExternalCalendar&MockObject $abstractExternalCalendar;
16
+
17
+    protected function setUp(): void {
18
+        parent::setUp();
19
+
20
+        $this->abstractExternalCalendar
21
+            = $this->getMockForAbstractClass(ExternalCalendar::class, ['example-app-id', 'calendar-uri-in-backend']);
22
+    }
23
+
24
+    public function testGetName():void {
25
+        // Check that the correct name is returned
26
+        $this->assertEquals('app-generated--example-app-id--calendar-uri-in-backend',
27
+            $this->abstractExternalCalendar->getName());
28
+
29
+        // Check that the method is final and can't be overridden by other classes
30
+        $reflectionMethod = new \ReflectionMethod(ExternalCalendar::class, 'getName');
31
+        $this->assertTrue($reflectionMethod->isFinal());
32
+    }
33
+
34
+    public function testSetName():void {
35
+        // Check that the method is final and can't be overridden by other classes
36
+        $reflectionMethod = new \ReflectionMethod(ExternalCalendar::class, 'setName');
37
+        $this->assertTrue($reflectionMethod->isFinal());
38
+
39
+        $this->expectException(\Sabre\DAV\Exception\MethodNotAllowed::class);
40
+        $this->expectExceptionMessage('Renaming calendars is not yet supported');
41
+
42
+        $this->abstractExternalCalendar->setName('other-name');
43
+    }
44
+
45
+    public function createDirectory(): void {
46
+        // Check that the method is final and can't be overridden by other classes
47
+        $reflectionMethod = new \ReflectionMethod(ExternalCalendar::class, 'createDirectory');
48
+        $this->assertTrue($reflectionMethod->isFinal());
49
+
50
+        $this->expectException(\Sabre\DAV\Exception\MethodNotAllowed::class);
51
+        $this->expectExceptionMessage('Creating collections in calendar objects is not allowed');
52
+
53
+        $this->abstractExternalCalendar->createDirectory('other-name');
54
+    }
55
+
56
+    public function testIsAppGeneratedCalendar():void {
57
+        $this->assertFalse(ExternalCalendar::isAppGeneratedCalendar('personal'));
58
+        $this->assertFalse(ExternalCalendar::isAppGeneratedCalendar('work'));
59
+        $this->assertFalse(ExternalCalendar::isAppGeneratedCalendar('contact_birthdays'));
60
+        $this->assertFalse(ExternalCalendar::isAppGeneratedCalendar('company'));
61
+        $this->assertFalse(ExternalCalendar::isAppGeneratedCalendar('app-generated'));
62
+        $this->assertFalse(ExternalCalendar::isAppGeneratedCalendar('app-generated--example'));
63
+
64
+        $this->assertTrue(ExternalCalendar::isAppGeneratedCalendar('app-generated--deck--board-1'));
65
+        $this->assertTrue(ExternalCalendar::isAppGeneratedCalendar('app-generated--example--foo-2'));
66
+        $this->assertTrue(ExternalCalendar::isAppGeneratedCalendar('app-generated--example--foo--2'));
67
+    }
68
+
69
+    #[\PHPUnit\Framework\Attributes\DataProvider('splitAppGeneratedCalendarUriDataProvider')]
70
+    public function testSplitAppGeneratedCalendarUriInvalid(string $name):void {
71
+        $this->expectException(\InvalidArgumentException::class);
72
+        $this->expectExceptionMessage('Provided calendar uri was not app-generated');
73
+
74
+        ExternalCalendar::splitAppGeneratedCalendarUri($name);
75
+    }
76
+
77
+    public static function splitAppGeneratedCalendarUriDataProvider():array {
78
+        return [
79
+            ['personal'],
80
+            ['foo_shared_by_admin'],
81
+            ['contact_birthdays'],
82
+        ];
83
+    }
84
+
85
+    public function testSplitAppGeneratedCalendarUri():void {
86
+        $this->assertEquals(['deck', 'board-1'], ExternalCalendar::splitAppGeneratedCalendarUri('app-generated--deck--board-1'));
87
+        $this->assertEquals(['example', 'foo-2'], ExternalCalendar::splitAppGeneratedCalendarUri('app-generated--example--foo-2'));
88
+        $this->assertEquals(['example', 'foo--2'], ExternalCalendar::splitAppGeneratedCalendarUri('app-generated--example--foo--2'));
89
+    }
90
+
91
+    public function testDoesViolateReservedName():void {
92
+        $this->assertFalse(ExternalCalendar::doesViolateReservedName('personal'));
93
+        $this->assertFalse(ExternalCalendar::doesViolateReservedName('work'));
94
+        $this->assertFalse(ExternalCalendar::doesViolateReservedName('contact_birthdays'));
95
+        $this->assertFalse(ExternalCalendar::doesViolateReservedName('company'));
96
+
97
+        $this->assertTrue(ExternalCalendar::doesViolateReservedName('app-generated'));
98
+        $this->assertTrue(ExternalCalendar::doesViolateReservedName('app-generated-calendar'));
99
+        $this->assertTrue(ExternalCalendar::doesViolateReservedName('app-generated--deck-123'));
100
+    }
101 101
 }
Please login to merge, or discard this patch.
apps/dav/tests/unit/CalDAV/CalendarTest.php 1 patch
Indentation   +461 added lines, -461 removed lines patch added patch discarded remove patch
@@ -20,296 +20,296 @@  discard block
 block discarded – undo
20 20
 use Test\TestCase;
21 21
 
22 22
 class CalendarTest extends TestCase {
23
-	protected IL10N&MockObject $l10n;
24
-	protected IConfig&MockObject $config;
25
-	protected LoggerInterface&MockObject $logger;
26
-
27
-	protected function setUp(): void {
28
-		parent::setUp();
29
-		$this->l10n = $this->createMock(IL10N::class);
30
-		$this->config = $this->createMock(IConfig::class);
31
-		$this->logger = $this->createMock(LoggerInterface::class);
32
-		$this->l10n
33
-			->expects($this->any())
34
-			->method('t')
35
-			->willReturnCallback(function ($text, $parameters = []) {
36
-				return vsprintf($text, $parameters);
37
-			});
38
-	}
39
-
40
-	public function testDelete(): void {
41
-		/** @var CalDavBackend&MockObject $backend */
42
-		$backend = $this->createMock(CalDavBackend::class);
43
-		$backend->expects($this->never())
44
-			->method('updateShares');
45
-		$backend->expects($this->once())
46
-			->method('unshare');
47
-
48
-		$calendarInfo = [
49
-			'{http://owncloud.org/ns}owner-principal' => 'user1',
50
-			'principaluri' => 'user2',
51
-			'id' => 666,
52
-			'uri' => 'cal',
53
-		];
54
-		$c = new Calendar($backend, $calendarInfo, $this->l10n, $this->config, $this->logger);
55
-		$c->delete();
56
-	}
57
-
58
-
59
-	public function testDeleteFromGroup(): void {
60
-		/** @var CalDavBackend&MockObject $backend */
61
-		$backend = $this->createMock(CalDavBackend::class);
62
-		$backend->expects($this->never())
63
-			->method('updateShares');
64
-		$backend->expects($this->once())
65
-			->method('unshare');
66
-
67
-		$calendarInfo = [
68
-			'{http://owncloud.org/ns}owner-principal' => 'user1',
69
-			'principaluri' => 'user2',
70
-			'id' => 666,
71
-			'uri' => 'cal',
72
-		];
73
-		$c = new Calendar($backend, $calendarInfo, $this->l10n, $this->config, $this->logger);
74
-		$c->delete();
75
-	}
76
-
77
-	public function testDeleteOwn(): void {
78
-		/** @var CalDavBackend&MockObject $backend */
79
-		$backend = $this->createMock(CalDavBackend::class);
80
-		$backend->expects($this->never())->method('updateShares');
81
-		$backend->expects($this->never())->method('getShares');
82
-
83
-		$this->config->expects($this->never())->method('setUserValue');
84
-
85
-		$backend->expects($this->once())->method('deleteCalendar')
86
-			->with(666);
87
-
88
-		$calendarInfo = [
89
-			'{http://owncloud.org/ns}owner-principal' => 'user1',
90
-			'principaluri' => 'user1',
91
-			'id' => 666,
92
-			'uri' => 'cal',
93
-		];
94
-		$c = new Calendar($backend, $calendarInfo, $this->l10n, $this->config, $this->logger);
95
-		$c->delete();
96
-	}
97
-
98
-	public function testDeleteBirthdayCalendar(): void {
99
-		/** @var CalDavBackend&MockObject $backend */
100
-		$backend = $this->createMock(CalDavBackend::class);
101
-		$backend->expects($this->once())->method('deleteCalendar')
102
-			->with(666);
103
-
104
-		$this->config->expects($this->once())
105
-			->method('setUserValue')
106
-			->with('user1', 'dav', 'generateBirthdayCalendar', 'no');
107
-
108
-		$calendarInfo = [
109
-			'{http://owncloud.org/ns}owner-principal' => 'principals/users/user1',
110
-			'principaluri' => 'principals/users/user1',
111
-			'id' => 666,
112
-			'uri' => 'contact_birthdays',
113
-			'{DAV:}displayname' => 'Test',
114
-		];
115
-
116
-		$c = new Calendar($backend, $calendarInfo, $this->l10n, $this->config, $this->logger);
117
-		$c->delete();
118
-	}
119
-
120
-	public static function dataPropPatch(): array {
121
-		return [
122
-			['user1', 'user2', [], true],
123
-			['user1', 'user2', [
124
-				'{http://owncloud.org/ns}calendar-enabled' => true,
125
-			], true],
126
-			['user1', 'user2', [
127
-				'{DAV:}displayname' => true,
128
-			], true],
129
-			['user1', 'user2', [
130
-				'{DAV:}displayname' => true,
131
-				'{http://owncloud.org/ns}calendar-enabled' => true,
132
-			], true],
133
-			['user1', 'user1', [], false],
134
-			['user1', 'user1', [
135
-				'{http://owncloud.org/ns}calendar-enabled' => true,
136
-			], false],
137
-			['user1', 'user1', [
138
-				'{DAV:}displayname' => true,
139
-			], false],
140
-			['user1', 'user1', [
141
-				'{DAV:}displayname' => true,
142
-				'{http://owncloud.org/ns}calendar-enabled' => true,
143
-			], false],
144
-		];
145
-	}
146
-
147
-	#[\PHPUnit\Framework\Attributes\DataProvider('dataPropPatch')]
148
-	public function testPropPatch(string $ownerPrincipal, string $principalUri, array $mutations, bool $shared): void {
149
-		/** @var CalDavBackend&MockObject $backend */
150
-		$backend = $this->createMock(CalDavBackend::class);
151
-		$calendarInfo = [
152
-			'{http://owncloud.org/ns}owner-principal' => $ownerPrincipal,
153
-			'principaluri' => $principalUri,
154
-			'id' => 666,
155
-			'uri' => 'default'
156
-		];
157
-		$c = new Calendar($backend, $calendarInfo, $this->l10n, $this->config, $this->logger);
158
-		$propPatch = new PropPatch($mutations);
159
-
160
-		if (!$shared) {
161
-			$backend->expects($this->once())
162
-				->method('updateCalendar')
163
-				->with(666, $propPatch);
164
-		}
165
-		$c->propPatch($propPatch);
166
-		$this->addToAssertionCount(1);
167
-	}
168
-
169
-	#[\PHPUnit\Framework\Attributes\DataProvider('providesReadOnlyInfo')]
170
-	public function testAcl($expectsWrite, $readOnlyValue, $hasOwnerSet, $uri = 'default'): void {
171
-		/** @var CalDavBackend&MockObject $backend */
172
-		$backend = $this->createMock(CalDavBackend::class);
173
-		$backend->expects($this->any())->method('applyShareAcl')->willReturnArgument(1);
174
-		$calendarInfo = [
175
-			'principaluri' => 'user2',
176
-			'id' => 666,
177
-			'uri' => $uri
178
-		];
179
-		$calendarInfo['{DAV:}displayname'] = 'Test';
180
-		if (!is_null($readOnlyValue)) {
181
-			$calendarInfo['{http://owncloud.org/ns}read-only'] = $readOnlyValue;
182
-		}
183
-		if ($hasOwnerSet) {
184
-			$calendarInfo['{http://owncloud.org/ns}owner-principal'] = 'user1';
185
-		}
186
-		$c = new Calendar($backend, $calendarInfo, $this->l10n, $this->config, $this->logger);
187
-		$acl = $c->getACL();
188
-		$childAcl = $c->getChildACL();
189
-
190
-		$expectedAcl = [[
191
-			'privilege' => '{DAV:}read',
192
-			'principal' => $hasOwnerSet ? 'user1' : 'user2',
193
-			'protected' => true
194
-		], [
195
-			'privilege' => '{DAV:}read',
196
-			'principal' => ($hasOwnerSet ? 'user1' : 'user2') . '/calendar-proxy-write',
197
-			'protected' => true,
198
-		], [
199
-			'privilege' => '{DAV:}read',
200
-			'principal' => ($hasOwnerSet ? 'user1' : 'user2') . '/calendar-proxy-read',
201
-			'protected' => true,
202
-		]];
203
-		if ($uri === BirthdayService::BIRTHDAY_CALENDAR_URI) {
204
-			$expectedAcl[] = [
205
-				'privilege' => '{DAV:}write-properties',
206
-				'principal' => $hasOwnerSet ? 'user1' : 'user2',
207
-				'protected' => true
208
-			];
209
-			$expectedAcl[] = [
210
-				'privilege' => '{DAV:}write-properties',
211
-				'principal' => ($hasOwnerSet ? 'user1' : 'user2') . '/calendar-proxy-write',
212
-				'protected' => true
213
-			];
214
-		} else {
215
-			$expectedAcl[] = [
216
-				'privilege' => '{DAV:}write',
217
-				'principal' => $hasOwnerSet ? 'user1' : 'user2',
218
-				'protected' => true
219
-			];
220
-			$expectedAcl[] = [
221
-				'privilege' => '{DAV:}write',
222
-				'principal' => ($hasOwnerSet ? 'user1' : 'user2') . '/calendar-proxy-write',
223
-				'protected' => true
224
-			];
225
-		}
226
-
227
-		$expectedAcl[] = [
228
-			'privilege' => '{DAV:}write-properties',
229
-			'principal' => ($hasOwnerSet ? 'user1' : 'user2') . '/calendar-proxy-read',
230
-			'protected' => true
231
-		];
232
-
233
-		if ($hasOwnerSet) {
234
-			$expectedAcl[] = [
235
-				'privilege' => '{DAV:}read',
236
-				'principal' => 'user2',
237
-				'protected' => true
238
-			];
239
-			if ($expectsWrite) {
240
-				$expectedAcl[] = [
241
-					'privilege' => '{DAV:}write',
242
-					'principal' => 'user2',
243
-					'protected' => true
244
-				];
245
-			} else {
246
-				$expectedAcl[] = [
247
-					'privilege' => '{DAV:}write-properties',
248
-					'principal' => 'user2',
249
-					'protected' => true
250
-				];
251
-			}
252
-		}
253
-		$this->assertEquals($expectedAcl, $acl);
254
-		$this->assertEquals($expectedAcl, $childAcl);
255
-	}
256
-
257
-	public static function providesReadOnlyInfo(): array {
258
-		return [
259
-			'read-only property not set' => [true, null, true],
260
-			'read-only property is false' => [true, false, true],
261
-			'read-only property is true' => [false, true, true],
262
-			'read-only property not set and no owner' => [true, null, false],
263
-			'read-only property is false and no owner' => [true, false, false],
264
-			'read-only property is true and no owner' => [false, true, false],
265
-			'birthday calendar' => [false, false, false, BirthdayService::BIRTHDAY_CALENDAR_URI]
266
-		];
267
-	}
268
-
269
-	#[\PHPUnit\Framework\Attributes\DataProvider('providesConfidentialClassificationData')]
270
-	public function testPrivateClassification(int $expectedChildren, bool $isShared): void {
271
-		$calObject0 = ['uri' => 'event-0', 'classification' => CalDavBackend::CLASSIFICATION_PUBLIC];
272
-		$calObject1 = ['uri' => 'event-1', 'classification' => CalDavBackend::CLASSIFICATION_CONFIDENTIAL];
273
-		$calObject2 = ['uri' => 'event-2', 'classification' => CalDavBackend::CLASSIFICATION_PRIVATE];
274
-
275
-		/** @var CalDavBackend&MockObject $backend */
276
-		$backend = $this->createMock(CalDavBackend::class);
277
-		$backend->expects($this->any())->method('getCalendarObjects')->willReturn([
278
-			$calObject0, $calObject1, $calObject2
279
-		]);
280
-		$backend->expects($this->any())->method('getMultipleCalendarObjects')
281
-			->with(666, ['event-0', 'event-1', 'event-2'])
282
-			->willReturn([
283
-				$calObject0, $calObject1, $calObject2
284
-			]);
285
-		$backend->expects($this->any())->method('getCalendarObject')
286
-			->willReturn($calObject2)->with(666, 'event-2');
287
-		$backend->expects($this->any())->method('applyShareAcl')->willReturnArgument(1);
288
-
289
-		$calendarInfo = [
290
-			'principaluri' => 'user2',
291
-			'id' => 666,
292
-			'uri' => 'cal',
293
-		];
294
-
295
-		if ($isShared) {
296
-			$calendarInfo['{http://owncloud.org/ns}owner-principal'] = 'user1';
297
-		}
298
-		$c = new Calendar($backend, $calendarInfo, $this->l10n, $this->config, $this->logger);
299
-		$children = $c->getChildren();
300
-		$this->assertEquals($expectedChildren, count($children));
301
-		$children = $c->getMultipleChildren(['event-0', 'event-1', 'event-2']);
302
-		$this->assertEquals($expectedChildren, count($children));
303
-
304
-		$this->assertEquals(!$isShared, $c->childExists('event-2'));
305
-	}
306
-
307
-	#[\PHPUnit\Framework\Attributes\DataProvider('providesConfidentialClassificationData')]
308
-	public function testConfidentialClassification(int $expectedChildren, bool $isShared): void {
309
-		$start = '20160609';
310
-		$end = '20160610';
311
-
312
-		$calData = <<<EOD
23
+    protected IL10N&MockObject $l10n;
24
+    protected IConfig&MockObject $config;
25
+    protected LoggerInterface&MockObject $logger;
26
+
27
+    protected function setUp(): void {
28
+        parent::setUp();
29
+        $this->l10n = $this->createMock(IL10N::class);
30
+        $this->config = $this->createMock(IConfig::class);
31
+        $this->logger = $this->createMock(LoggerInterface::class);
32
+        $this->l10n
33
+            ->expects($this->any())
34
+            ->method('t')
35
+            ->willReturnCallback(function ($text, $parameters = []) {
36
+                return vsprintf($text, $parameters);
37
+            });
38
+    }
39
+
40
+    public function testDelete(): void {
41
+        /** @var CalDavBackend&MockObject $backend */
42
+        $backend = $this->createMock(CalDavBackend::class);
43
+        $backend->expects($this->never())
44
+            ->method('updateShares');
45
+        $backend->expects($this->once())
46
+            ->method('unshare');
47
+
48
+        $calendarInfo = [
49
+            '{http://owncloud.org/ns}owner-principal' => 'user1',
50
+            'principaluri' => 'user2',
51
+            'id' => 666,
52
+            'uri' => 'cal',
53
+        ];
54
+        $c = new Calendar($backend, $calendarInfo, $this->l10n, $this->config, $this->logger);
55
+        $c->delete();
56
+    }
57
+
58
+
59
+    public function testDeleteFromGroup(): void {
60
+        /** @var CalDavBackend&MockObject $backend */
61
+        $backend = $this->createMock(CalDavBackend::class);
62
+        $backend->expects($this->never())
63
+            ->method('updateShares');
64
+        $backend->expects($this->once())
65
+            ->method('unshare');
66
+
67
+        $calendarInfo = [
68
+            '{http://owncloud.org/ns}owner-principal' => 'user1',
69
+            'principaluri' => 'user2',
70
+            'id' => 666,
71
+            'uri' => 'cal',
72
+        ];
73
+        $c = new Calendar($backend, $calendarInfo, $this->l10n, $this->config, $this->logger);
74
+        $c->delete();
75
+    }
76
+
77
+    public function testDeleteOwn(): void {
78
+        /** @var CalDavBackend&MockObject $backend */
79
+        $backend = $this->createMock(CalDavBackend::class);
80
+        $backend->expects($this->never())->method('updateShares');
81
+        $backend->expects($this->never())->method('getShares');
82
+
83
+        $this->config->expects($this->never())->method('setUserValue');
84
+
85
+        $backend->expects($this->once())->method('deleteCalendar')
86
+            ->with(666);
87
+
88
+        $calendarInfo = [
89
+            '{http://owncloud.org/ns}owner-principal' => 'user1',
90
+            'principaluri' => 'user1',
91
+            'id' => 666,
92
+            'uri' => 'cal',
93
+        ];
94
+        $c = new Calendar($backend, $calendarInfo, $this->l10n, $this->config, $this->logger);
95
+        $c->delete();
96
+    }
97
+
98
+    public function testDeleteBirthdayCalendar(): void {
99
+        /** @var CalDavBackend&MockObject $backend */
100
+        $backend = $this->createMock(CalDavBackend::class);
101
+        $backend->expects($this->once())->method('deleteCalendar')
102
+            ->with(666);
103
+
104
+        $this->config->expects($this->once())
105
+            ->method('setUserValue')
106
+            ->with('user1', 'dav', 'generateBirthdayCalendar', 'no');
107
+
108
+        $calendarInfo = [
109
+            '{http://owncloud.org/ns}owner-principal' => 'principals/users/user1',
110
+            'principaluri' => 'principals/users/user1',
111
+            'id' => 666,
112
+            'uri' => 'contact_birthdays',
113
+            '{DAV:}displayname' => 'Test',
114
+        ];
115
+
116
+        $c = new Calendar($backend, $calendarInfo, $this->l10n, $this->config, $this->logger);
117
+        $c->delete();
118
+    }
119
+
120
+    public static function dataPropPatch(): array {
121
+        return [
122
+            ['user1', 'user2', [], true],
123
+            ['user1', 'user2', [
124
+                '{http://owncloud.org/ns}calendar-enabled' => true,
125
+            ], true],
126
+            ['user1', 'user2', [
127
+                '{DAV:}displayname' => true,
128
+            ], true],
129
+            ['user1', 'user2', [
130
+                '{DAV:}displayname' => true,
131
+                '{http://owncloud.org/ns}calendar-enabled' => true,
132
+            ], true],
133
+            ['user1', 'user1', [], false],
134
+            ['user1', 'user1', [
135
+                '{http://owncloud.org/ns}calendar-enabled' => true,
136
+            ], false],
137
+            ['user1', 'user1', [
138
+                '{DAV:}displayname' => true,
139
+            ], false],
140
+            ['user1', 'user1', [
141
+                '{DAV:}displayname' => true,
142
+                '{http://owncloud.org/ns}calendar-enabled' => true,
143
+            ], false],
144
+        ];
145
+    }
146
+
147
+    #[\PHPUnit\Framework\Attributes\DataProvider('dataPropPatch')]
148
+    public function testPropPatch(string $ownerPrincipal, string $principalUri, array $mutations, bool $shared): void {
149
+        /** @var CalDavBackend&MockObject $backend */
150
+        $backend = $this->createMock(CalDavBackend::class);
151
+        $calendarInfo = [
152
+            '{http://owncloud.org/ns}owner-principal' => $ownerPrincipal,
153
+            'principaluri' => $principalUri,
154
+            'id' => 666,
155
+            'uri' => 'default'
156
+        ];
157
+        $c = new Calendar($backend, $calendarInfo, $this->l10n, $this->config, $this->logger);
158
+        $propPatch = new PropPatch($mutations);
159
+
160
+        if (!$shared) {
161
+            $backend->expects($this->once())
162
+                ->method('updateCalendar')
163
+                ->with(666, $propPatch);
164
+        }
165
+        $c->propPatch($propPatch);
166
+        $this->addToAssertionCount(1);
167
+    }
168
+
169
+    #[\PHPUnit\Framework\Attributes\DataProvider('providesReadOnlyInfo')]
170
+    public function testAcl($expectsWrite, $readOnlyValue, $hasOwnerSet, $uri = 'default'): void {
171
+        /** @var CalDavBackend&MockObject $backend */
172
+        $backend = $this->createMock(CalDavBackend::class);
173
+        $backend->expects($this->any())->method('applyShareAcl')->willReturnArgument(1);
174
+        $calendarInfo = [
175
+            'principaluri' => 'user2',
176
+            'id' => 666,
177
+            'uri' => $uri
178
+        ];
179
+        $calendarInfo['{DAV:}displayname'] = 'Test';
180
+        if (!is_null($readOnlyValue)) {
181
+            $calendarInfo['{http://owncloud.org/ns}read-only'] = $readOnlyValue;
182
+        }
183
+        if ($hasOwnerSet) {
184
+            $calendarInfo['{http://owncloud.org/ns}owner-principal'] = 'user1';
185
+        }
186
+        $c = new Calendar($backend, $calendarInfo, $this->l10n, $this->config, $this->logger);
187
+        $acl = $c->getACL();
188
+        $childAcl = $c->getChildACL();
189
+
190
+        $expectedAcl = [[
191
+            'privilege' => '{DAV:}read',
192
+            'principal' => $hasOwnerSet ? 'user1' : 'user2',
193
+            'protected' => true
194
+        ], [
195
+            'privilege' => '{DAV:}read',
196
+            'principal' => ($hasOwnerSet ? 'user1' : 'user2') . '/calendar-proxy-write',
197
+            'protected' => true,
198
+        ], [
199
+            'privilege' => '{DAV:}read',
200
+            'principal' => ($hasOwnerSet ? 'user1' : 'user2') . '/calendar-proxy-read',
201
+            'protected' => true,
202
+        ]];
203
+        if ($uri === BirthdayService::BIRTHDAY_CALENDAR_URI) {
204
+            $expectedAcl[] = [
205
+                'privilege' => '{DAV:}write-properties',
206
+                'principal' => $hasOwnerSet ? 'user1' : 'user2',
207
+                'protected' => true
208
+            ];
209
+            $expectedAcl[] = [
210
+                'privilege' => '{DAV:}write-properties',
211
+                'principal' => ($hasOwnerSet ? 'user1' : 'user2') . '/calendar-proxy-write',
212
+                'protected' => true
213
+            ];
214
+        } else {
215
+            $expectedAcl[] = [
216
+                'privilege' => '{DAV:}write',
217
+                'principal' => $hasOwnerSet ? 'user1' : 'user2',
218
+                'protected' => true
219
+            ];
220
+            $expectedAcl[] = [
221
+                'privilege' => '{DAV:}write',
222
+                'principal' => ($hasOwnerSet ? 'user1' : 'user2') . '/calendar-proxy-write',
223
+                'protected' => true
224
+            ];
225
+        }
226
+
227
+        $expectedAcl[] = [
228
+            'privilege' => '{DAV:}write-properties',
229
+            'principal' => ($hasOwnerSet ? 'user1' : 'user2') . '/calendar-proxy-read',
230
+            'protected' => true
231
+        ];
232
+
233
+        if ($hasOwnerSet) {
234
+            $expectedAcl[] = [
235
+                'privilege' => '{DAV:}read',
236
+                'principal' => 'user2',
237
+                'protected' => true
238
+            ];
239
+            if ($expectsWrite) {
240
+                $expectedAcl[] = [
241
+                    'privilege' => '{DAV:}write',
242
+                    'principal' => 'user2',
243
+                    'protected' => true
244
+                ];
245
+            } else {
246
+                $expectedAcl[] = [
247
+                    'privilege' => '{DAV:}write-properties',
248
+                    'principal' => 'user2',
249
+                    'protected' => true
250
+                ];
251
+            }
252
+        }
253
+        $this->assertEquals($expectedAcl, $acl);
254
+        $this->assertEquals($expectedAcl, $childAcl);
255
+    }
256
+
257
+    public static function providesReadOnlyInfo(): array {
258
+        return [
259
+            'read-only property not set' => [true, null, true],
260
+            'read-only property is false' => [true, false, true],
261
+            'read-only property is true' => [false, true, true],
262
+            'read-only property not set and no owner' => [true, null, false],
263
+            'read-only property is false and no owner' => [true, false, false],
264
+            'read-only property is true and no owner' => [false, true, false],
265
+            'birthday calendar' => [false, false, false, BirthdayService::BIRTHDAY_CALENDAR_URI]
266
+        ];
267
+    }
268
+
269
+    #[\PHPUnit\Framework\Attributes\DataProvider('providesConfidentialClassificationData')]
270
+    public function testPrivateClassification(int $expectedChildren, bool $isShared): void {
271
+        $calObject0 = ['uri' => 'event-0', 'classification' => CalDavBackend::CLASSIFICATION_PUBLIC];
272
+        $calObject1 = ['uri' => 'event-1', 'classification' => CalDavBackend::CLASSIFICATION_CONFIDENTIAL];
273
+        $calObject2 = ['uri' => 'event-2', 'classification' => CalDavBackend::CLASSIFICATION_PRIVATE];
274
+
275
+        /** @var CalDavBackend&MockObject $backend */
276
+        $backend = $this->createMock(CalDavBackend::class);
277
+        $backend->expects($this->any())->method('getCalendarObjects')->willReturn([
278
+            $calObject0, $calObject1, $calObject2
279
+        ]);
280
+        $backend->expects($this->any())->method('getMultipleCalendarObjects')
281
+            ->with(666, ['event-0', 'event-1', 'event-2'])
282
+            ->willReturn([
283
+                $calObject0, $calObject1, $calObject2
284
+            ]);
285
+        $backend->expects($this->any())->method('getCalendarObject')
286
+            ->willReturn($calObject2)->with(666, 'event-2');
287
+        $backend->expects($this->any())->method('applyShareAcl')->willReturnArgument(1);
288
+
289
+        $calendarInfo = [
290
+            'principaluri' => 'user2',
291
+            'id' => 666,
292
+            'uri' => 'cal',
293
+        ];
294
+
295
+        if ($isShared) {
296
+            $calendarInfo['{http://owncloud.org/ns}owner-principal'] = 'user1';
297
+        }
298
+        $c = new Calendar($backend, $calendarInfo, $this->l10n, $this->config, $this->logger);
299
+        $children = $c->getChildren();
300
+        $this->assertEquals($expectedChildren, count($children));
301
+        $children = $c->getMultipleChildren(['event-0', 'event-1', 'event-2']);
302
+        $this->assertEquals($expectedChildren, count($children));
303
+
304
+        $this->assertEquals(!$isShared, $c->childExists('event-2'));
305
+    }
306
+
307
+    #[\PHPUnit\Framework\Attributes\DataProvider('providesConfidentialClassificationData')]
308
+    public function testConfidentialClassification(int $expectedChildren, bool $isShared): void {
309
+        $start = '20160609';
310
+        $end = '20160610';
311
+
312
+        $calData = <<<EOD
313 313
 BEGIN:VCALENDAR
314 314
 PRODID:-//ownCloud calendar v1.2.2
315 315
 BEGIN:VEVENT
@@ -351,84 +351,84 @@  discard block
 block discarded – undo
351 351
 END:VCALENDAR
352 352
 EOD;
353 353
 
354
-		$calObject0 = ['uri' => 'event-0', 'classification' => CalDavBackend::CLASSIFICATION_PUBLIC];
355
-		$calObject1 = ['uri' => 'event-1', 'classification' => CalDavBackend::CLASSIFICATION_CONFIDENTIAL, 'calendardata' => $calData];
356
-		$calObject2 = ['uri' => 'event-2', 'classification' => CalDavBackend::CLASSIFICATION_PRIVATE];
357
-
358
-		/** @var CalDavBackend&MockObject $backend */
359
-		$backend = $this->createMock(CalDavBackend::class);
360
-		$backend->expects($this->any())->method('getCalendarObjects')->willReturn([
361
-			$calObject0, $calObject1, $calObject2
362
-		]);
363
-		$backend->expects($this->any())->method('getMultipleCalendarObjects')
364
-			->with(666, ['event-0', 'event-1', 'event-2'])
365
-			->willReturn([
366
-				$calObject0, $calObject1, $calObject2
367
-			]);
368
-		$backend->expects($this->any())->method('getCalendarObject')
369
-			->willReturn($calObject1)->with(666, 'event-1');
370
-		$backend->expects($this->any())->method('applyShareAcl')->willReturnArgument(1);
371
-
372
-		$calendarInfo = [
373
-			'{http://owncloud.org/ns}owner-principal' => $isShared ? 'user1' : 'user2',
374
-			'principaluri' => 'user2',
375
-			'id' => 666,
376
-			'uri' => 'cal',
377
-		];
378
-		$c = new Calendar($backend, $calendarInfo, $this->l10n, $this->config, $this->logger);
379
-
380
-		$this->assertEquals(count($c->getChildren()), $expectedChildren);
381
-
382
-		// test private event
383
-		$privateEvent = $c->getChild('event-1');
384
-		$calData = $privateEvent->get();
385
-		$event = Reader::read($calData);
386
-
387
-		$this->assertEquals($start, $event->VEVENT->DTSTART->getValue());
388
-		$this->assertEquals($end, $event->VEVENT->DTEND->getValue());
389
-
390
-		if ($isShared) {
391
-			$this->assertEquals('Busy', $event->VEVENT->SUMMARY->getValue());
392
-			$this->assertArrayNotHasKey('ATTENDEE', $event->VEVENT);
393
-			$this->assertArrayNotHasKey('LOCATION', $event->VEVENT);
394
-			$this->assertArrayNotHasKey('DESCRIPTION', $event->VEVENT);
395
-			$this->assertArrayNotHasKey('ORGANIZER', $event->VEVENT);
396
-		} else {
397
-			$this->assertEquals('Test Event', $event->VEVENT->SUMMARY->getValue());
398
-		}
399
-
400
-		// Test l10n
401
-		$l10n = $this->createMock(IL10N::class);
402
-		if ($isShared) {
403
-			$l10n->expects($this->once())
404
-				->method('t')
405
-				->with('Busy')
406
-				->willReturn('Translated busy');
407
-		} else {
408
-			$l10n->expects($this->never())
409
-				->method('t');
410
-		}
411
-		$c = new Calendar($backend, $calendarInfo, $l10n, $this->config, $this->logger);
412
-
413
-		$calData = $c->getChild('event-1')->get();
414
-		$event = Reader::read($calData);
415
-
416
-		if ($isShared) {
417
-			$this->assertEquals('Translated busy', $event->VEVENT->SUMMARY->getValue());
418
-		} else {
419
-			$this->assertEquals('Test Event', $event->VEVENT->SUMMARY->getValue());
420
-		}
421
-	}
422
-
423
-	public static function providesConfidentialClassificationData(): array {
424
-		return [
425
-			[3, false],
426
-			[2, true]
427
-		];
428
-	}
429
-
430
-	public function testRemoveVAlarms(): void {
431
-		$publicObjectData = <<<EOD
354
+        $calObject0 = ['uri' => 'event-0', 'classification' => CalDavBackend::CLASSIFICATION_PUBLIC];
355
+        $calObject1 = ['uri' => 'event-1', 'classification' => CalDavBackend::CLASSIFICATION_CONFIDENTIAL, 'calendardata' => $calData];
356
+        $calObject2 = ['uri' => 'event-2', 'classification' => CalDavBackend::CLASSIFICATION_PRIVATE];
357
+
358
+        /** @var CalDavBackend&MockObject $backend */
359
+        $backend = $this->createMock(CalDavBackend::class);
360
+        $backend->expects($this->any())->method('getCalendarObjects')->willReturn([
361
+            $calObject0, $calObject1, $calObject2
362
+        ]);
363
+        $backend->expects($this->any())->method('getMultipleCalendarObjects')
364
+            ->with(666, ['event-0', 'event-1', 'event-2'])
365
+            ->willReturn([
366
+                $calObject0, $calObject1, $calObject2
367
+            ]);
368
+        $backend->expects($this->any())->method('getCalendarObject')
369
+            ->willReturn($calObject1)->with(666, 'event-1');
370
+        $backend->expects($this->any())->method('applyShareAcl')->willReturnArgument(1);
371
+
372
+        $calendarInfo = [
373
+            '{http://owncloud.org/ns}owner-principal' => $isShared ? 'user1' : 'user2',
374
+            'principaluri' => 'user2',
375
+            'id' => 666,
376
+            'uri' => 'cal',
377
+        ];
378
+        $c = new Calendar($backend, $calendarInfo, $this->l10n, $this->config, $this->logger);
379
+
380
+        $this->assertEquals(count($c->getChildren()), $expectedChildren);
381
+
382
+        // test private event
383
+        $privateEvent = $c->getChild('event-1');
384
+        $calData = $privateEvent->get();
385
+        $event = Reader::read($calData);
386
+
387
+        $this->assertEquals($start, $event->VEVENT->DTSTART->getValue());
388
+        $this->assertEquals($end, $event->VEVENT->DTEND->getValue());
389
+
390
+        if ($isShared) {
391
+            $this->assertEquals('Busy', $event->VEVENT->SUMMARY->getValue());
392
+            $this->assertArrayNotHasKey('ATTENDEE', $event->VEVENT);
393
+            $this->assertArrayNotHasKey('LOCATION', $event->VEVENT);
394
+            $this->assertArrayNotHasKey('DESCRIPTION', $event->VEVENT);
395
+            $this->assertArrayNotHasKey('ORGANIZER', $event->VEVENT);
396
+        } else {
397
+            $this->assertEquals('Test Event', $event->VEVENT->SUMMARY->getValue());
398
+        }
399
+
400
+        // Test l10n
401
+        $l10n = $this->createMock(IL10N::class);
402
+        if ($isShared) {
403
+            $l10n->expects($this->once())
404
+                ->method('t')
405
+                ->with('Busy')
406
+                ->willReturn('Translated busy');
407
+        } else {
408
+            $l10n->expects($this->never())
409
+                ->method('t');
410
+        }
411
+        $c = new Calendar($backend, $calendarInfo, $l10n, $this->config, $this->logger);
412
+
413
+        $calData = $c->getChild('event-1')->get();
414
+        $event = Reader::read($calData);
415
+
416
+        if ($isShared) {
417
+            $this->assertEquals('Translated busy', $event->VEVENT->SUMMARY->getValue());
418
+        } else {
419
+            $this->assertEquals('Test Event', $event->VEVENT->SUMMARY->getValue());
420
+        }
421
+    }
422
+
423
+    public static function providesConfidentialClassificationData(): array {
424
+        return [
425
+            [3, false],
426
+            [2, true]
427
+        ];
428
+    }
429
+
430
+    public function testRemoveVAlarms(): void {
431
+        $publicObjectData = <<<EOD
432 432
 BEGIN:VCALENDAR
433 433
 VERSION:2.0
434 434
 PRODID:-//Nextcloud calendar v1.5.6
@@ -452,7 +452,7 @@  discard block
 block discarded – undo
452 452
 
453 453
 EOD;
454 454
 
455
-		$confidentialObjectData = <<<EOD
455
+        $confidentialObjectData = <<<EOD
456 456
 BEGIN:VCALENDAR
457 457
 VERSION:2.0
458 458
 PRODID:-//Nextcloud calendar v1.5.6
@@ -476,7 +476,7 @@  discard block
 block discarded – undo
476 476
 
477 477
 EOD;
478 478
 
479
-		$publicObjectDataWithoutVAlarm = <<<EOD
479
+        $publicObjectDataWithoutVAlarm = <<<EOD
480 480
 BEGIN:VCALENDAR
481 481
 VERSION:2.0
482 482
 PRODID:-//Nextcloud calendar v1.5.6
@@ -496,7 +496,7 @@  discard block
 block discarded – undo
496 496
 
497 497
 EOD;
498 498
 
499
-		$confidentialObjectCleaned = <<<EOD
499
+        $confidentialObjectCleaned = <<<EOD
500 500
 BEGIN:VCALENDAR
501 501
 VERSION:2.0
502 502
 PRODID:-//Nextcloud calendar v1.5.6
@@ -515,94 +515,94 @@  discard block
 block discarded – undo
515 515
 
516 516
 
517 517
 
518
-		$publicObject = ['uri' => 'event-0',
519
-			'classification' => CalDavBackend::CLASSIFICATION_PUBLIC,
520
-			'calendardata' => $publicObjectData];
521
-
522
-		$confidentialObject = ['uri' => 'event-1',
523
-			'classification' => CalDavBackend::CLASSIFICATION_CONFIDENTIAL,
524
-			'calendardata' => $confidentialObjectData];
525
-
526
-		/** @var CalDavBackend&MockObject $backend */
527
-		$backend = $this->createMock(CalDavBackend::class);
528
-		$backend->expects($this->any())
529
-			->method('getCalendarObjects')
530
-			->willReturn([$publicObject, $confidentialObject]);
531
-
532
-		$backend->expects($this->any())
533
-			->method('getMultipleCalendarObjects')
534
-			->with(666, ['event-0', 'event-1'])
535
-			->willReturn([$publicObject, $confidentialObject]);
536
-
537
-		$backend->expects($this->any())
538
-			->method('getCalendarObject')
539
-			->willReturnCallback(function ($cId, $uri) use ($publicObject, $confidentialObject) {
540
-				switch ($uri) {
541
-					case 'event-0':
542
-						return $publicObject;
543
-
544
-					case 'event-1':
545
-						return $confidentialObject;
546
-
547
-					default:
548
-						throw new \Exception('unexpected uri');
549
-				}
550
-			});
551
-
552
-		$backend->expects($this->any())
553
-			->method('applyShareAcl')
554
-			->willReturnArgument(1);
555
-
556
-		$calendarInfoOwner = [
557
-			'{http://owncloud.org/ns}owner-principal' => 'user1',
558
-			'principaluri' => 'user1',
559
-			'id' => 666,
560
-			'uri' => 'cal',
561
-		];
562
-		$calendarInfoSharedRW = [
563
-			'{http://owncloud.org/ns}owner-principal' => 'user1',
564
-			'principaluri' => 'user2',
565
-			'id' => 666,
566
-			'uri' => 'cal',
567
-		];
568
-		$calendarInfoSharedRO = [
569
-			'{http://owncloud.org/ns}owner-principal' => 'user1',
570
-			'{http://owncloud.org/ns}read-only' => true,
571
-			'principaluri' => 'user2',
572
-			'id' => 666,
573
-			'uri' => 'cal',
574
-		];
575
-
576
-		$ownerCalendar = new Calendar($backend, $calendarInfoOwner, $this->l10n, $this->config, $this->logger);
577
-		$rwCalendar = new Calendar($backend, $calendarInfoSharedRW, $this->l10n, $this->config, $this->logger);
578
-		$roCalendar = new Calendar($backend, $calendarInfoSharedRO, $this->l10n, $this->config, $this->logger);
579
-
580
-		$this->assertCount(2, $ownerCalendar->getChildren());
581
-		$this->assertCount(2, $rwCalendar->getChildren());
582
-		$this->assertCount(2, $roCalendar->getChildren());
583
-
584
-		// calendar data shall not be altered for the owner
585
-		$this->assertEquals($ownerCalendar->getChild('event-0')->get(), $publicObjectData);
586
-		$this->assertEquals($ownerCalendar->getChild('event-1')->get(), $confidentialObjectData);
587
-
588
-		// valarms shall not be removed for read-write shares
589
-		$this->assertEquals(
590
-			$this->fixLinebreak($rwCalendar->getChild('event-0')->get()),
591
-			$this->fixLinebreak($publicObjectData));
592
-		$this->assertEquals(
593
-			$this->fixLinebreak($rwCalendar->getChild('event-1')->get()),
594
-			$this->fixLinebreak($confidentialObjectCleaned));
595
-
596
-		// valarms shall be removed for read-only shares
597
-		$this->assertEquals(
598
-			$this->fixLinebreak($roCalendar->getChild('event-0')->get()),
599
-			$this->fixLinebreak($publicObjectDataWithoutVAlarm));
600
-		$this->assertEquals(
601
-			$this->fixLinebreak($roCalendar->getChild('event-1')->get()),
602
-			$this->fixLinebreak($confidentialObjectCleaned));
603
-	}
604
-
605
-	private function fixLinebreak(string $str): string {
606
-		return preg_replace('~(*BSR_ANYCRLF)\R~', "\r\n", $str);
607
-	}
518
+        $publicObject = ['uri' => 'event-0',
519
+            'classification' => CalDavBackend::CLASSIFICATION_PUBLIC,
520
+            'calendardata' => $publicObjectData];
521
+
522
+        $confidentialObject = ['uri' => 'event-1',
523
+            'classification' => CalDavBackend::CLASSIFICATION_CONFIDENTIAL,
524
+            'calendardata' => $confidentialObjectData];
525
+
526
+        /** @var CalDavBackend&MockObject $backend */
527
+        $backend = $this->createMock(CalDavBackend::class);
528
+        $backend->expects($this->any())
529
+            ->method('getCalendarObjects')
530
+            ->willReturn([$publicObject, $confidentialObject]);
531
+
532
+        $backend->expects($this->any())
533
+            ->method('getMultipleCalendarObjects')
534
+            ->with(666, ['event-0', 'event-1'])
535
+            ->willReturn([$publicObject, $confidentialObject]);
536
+
537
+        $backend->expects($this->any())
538
+            ->method('getCalendarObject')
539
+            ->willReturnCallback(function ($cId, $uri) use ($publicObject, $confidentialObject) {
540
+                switch ($uri) {
541
+                    case 'event-0':
542
+                        return $publicObject;
543
+
544
+                    case 'event-1':
545
+                        return $confidentialObject;
546
+
547
+                    default:
548
+                        throw new \Exception('unexpected uri');
549
+                }
550
+            });
551
+
552
+        $backend->expects($this->any())
553
+            ->method('applyShareAcl')
554
+            ->willReturnArgument(1);
555
+
556
+        $calendarInfoOwner = [
557
+            '{http://owncloud.org/ns}owner-principal' => 'user1',
558
+            'principaluri' => 'user1',
559
+            'id' => 666,
560
+            'uri' => 'cal',
561
+        ];
562
+        $calendarInfoSharedRW = [
563
+            '{http://owncloud.org/ns}owner-principal' => 'user1',
564
+            'principaluri' => 'user2',
565
+            'id' => 666,
566
+            'uri' => 'cal',
567
+        ];
568
+        $calendarInfoSharedRO = [
569
+            '{http://owncloud.org/ns}owner-principal' => 'user1',
570
+            '{http://owncloud.org/ns}read-only' => true,
571
+            'principaluri' => 'user2',
572
+            'id' => 666,
573
+            'uri' => 'cal',
574
+        ];
575
+
576
+        $ownerCalendar = new Calendar($backend, $calendarInfoOwner, $this->l10n, $this->config, $this->logger);
577
+        $rwCalendar = new Calendar($backend, $calendarInfoSharedRW, $this->l10n, $this->config, $this->logger);
578
+        $roCalendar = new Calendar($backend, $calendarInfoSharedRO, $this->l10n, $this->config, $this->logger);
579
+
580
+        $this->assertCount(2, $ownerCalendar->getChildren());
581
+        $this->assertCount(2, $rwCalendar->getChildren());
582
+        $this->assertCount(2, $roCalendar->getChildren());
583
+
584
+        // calendar data shall not be altered for the owner
585
+        $this->assertEquals($ownerCalendar->getChild('event-0')->get(), $publicObjectData);
586
+        $this->assertEquals($ownerCalendar->getChild('event-1')->get(), $confidentialObjectData);
587
+
588
+        // valarms shall not be removed for read-write shares
589
+        $this->assertEquals(
590
+            $this->fixLinebreak($rwCalendar->getChild('event-0')->get()),
591
+            $this->fixLinebreak($publicObjectData));
592
+        $this->assertEquals(
593
+            $this->fixLinebreak($rwCalendar->getChild('event-1')->get()),
594
+            $this->fixLinebreak($confidentialObjectCleaned));
595
+
596
+        // valarms shall be removed for read-only shares
597
+        $this->assertEquals(
598
+            $this->fixLinebreak($roCalendar->getChild('event-0')->get()),
599
+            $this->fixLinebreak($publicObjectDataWithoutVAlarm));
600
+        $this->assertEquals(
601
+            $this->fixLinebreak($roCalendar->getChild('event-1')->get()),
602
+            $this->fixLinebreak($confidentialObjectCleaned));
603
+    }
604
+
605
+    private function fixLinebreak(string $str): string {
606
+        return preg_replace('~(*BSR_ANYCRLF)\R~', "\r\n", $str);
607
+    }
608 608
 }
Please login to merge, or discard this patch.
apps/dav/tests/unit/CalDAV/WebcalCaching/RefreshWebcalServiceTest.php 2 patches
Indentation   +302 added lines, -302 removed lines patch added patch discarded remove patch
@@ -20,306 +20,306 @@
 block discarded – undo
20 20
 use Test\TestCase;
21 21
 
22 22
 class RefreshWebcalServiceTest extends TestCase {
23
-	private CalDavBackend&MockObject $caldavBackend;
24
-	private Connection&MockObject $connection;
25
-	private LoggerInterface&MockObject $logger;
26
-	private ITimeFactory&MockObject $time;
27
-
28
-	protected function setUp(): void {
29
-		parent::setUp();
30
-
31
-		$this->caldavBackend = $this->createMock(CalDavBackend::class);
32
-		$this->connection = $this->createMock(Connection::class);
33
-		$this->logger = $this->createMock(LoggerInterface::class);
34
-		$this->time = $this->createMock(ITimeFactory::class);
35
-	}
36
-
37
-	#[\PHPUnit\Framework\Attributes\DataProvider('runDataProvider')]
38
-	public function testRun(string $body, string $contentType, string $result): void {
39
-		$refreshWebcalService = $this->getMockBuilder(RefreshWebcalService::class)
40
-			->onlyMethods(['getRandomCalendarObjectUri'])
41
-			->setConstructorArgs([$this->caldavBackend, $this->logger, $this->connection, $this->time])
42
-			->getMock();
43
-
44
-		$refreshWebcalService
45
-			->method('getRandomCalendarObjectUri')
46
-			->willReturn('uri-1.ics');
47
-
48
-		$this->caldavBackend->expects(self::once())
49
-			->method('getSubscriptionsForUser')
50
-			->with('principals/users/testuser')
51
-			->willReturn([
52
-				[
53
-					'id' => '99',
54
-					'uri' => 'sub456',
55
-					RefreshWebcalService::REFRESH_RATE => 'P1D',
56
-					RefreshWebcalService::STRIP_TODOS => '1',
57
-					RefreshWebcalService::STRIP_ALARMS => '1',
58
-					RefreshWebcalService::STRIP_ATTACHMENTS => '1',
59
-					'source' => 'webcal://foo.bar/bla',
60
-					'lastmodified' => 0,
61
-				],
62
-				[
63
-					'id' => '42',
64
-					'uri' => 'sub123',
65
-					RefreshWebcalService::REFRESH_RATE => 'PT1H',
66
-					RefreshWebcalService::STRIP_TODOS => '1',
67
-					RefreshWebcalService::STRIP_ALARMS => '1',
68
-					RefreshWebcalService::STRIP_ATTACHMENTS => '1',
69
-					'source' => 'webcal://foo.bar/bla2',
70
-					'lastmodified' => 0,
71
-				],
72
-			]);
73
-
74
-		$this->connection->expects(self::once())
75
-			->method('queryWebcalFeed')
76
-			->willReturn($result);
77
-		$this->caldavBackend->expects(self::once())
78
-			->method('createCalendarObject')
79
-			->with(42, 'uri-1.ics', $result, 1);
80
-
81
-		$refreshWebcalService->refreshSubscription('principals/users/testuser', 'sub123');
82
-	}
83
-
84
-	#[\PHPUnit\Framework\Attributes\DataProvider('identicalDataProvider')]
85
-	public function testRunIdentical(string $uid, array $calendarObject, string $body, string $contentType, string $result): void {
86
-		$refreshWebcalService = $this->getMockBuilder(RefreshWebcalService::class)
87
-			->onlyMethods(['getRandomCalendarObjectUri'])
88
-			->setConstructorArgs([$this->caldavBackend, $this->logger, $this->connection, $this->time])
89
-			->getMock();
90
-
91
-		$refreshWebcalService
92
-			->method('getRandomCalendarObjectUri')
93
-			->willReturn('uri-1.ics');
94
-
95
-		$this->caldavBackend->expects(self::once())
96
-			->method('getSubscriptionsForUser')
97
-			->with('principals/users/testuser')
98
-			->willReturn([
99
-				[
100
-					'id' => '99',
101
-					'uri' => 'sub456',
102
-					RefreshWebcalService::REFRESH_RATE => 'P1D',
103
-					RefreshWebcalService::STRIP_TODOS => '1',
104
-					RefreshWebcalService::STRIP_ALARMS => '1',
105
-					RefreshWebcalService::STRIP_ATTACHMENTS => '1',
106
-					'source' => 'webcal://foo.bar/bla',
107
-					'lastmodified' => 0,
108
-				],
109
-				[
110
-					'id' => '42',
111
-					'uri' => 'sub123',
112
-					RefreshWebcalService::REFRESH_RATE => 'PT1H',
113
-					RefreshWebcalService::STRIP_TODOS => '1',
114
-					RefreshWebcalService::STRIP_ALARMS => '1',
115
-					RefreshWebcalService::STRIP_ATTACHMENTS => '1',
116
-					'source' => 'webcal://foo.bar/bla2',
117
-					'lastmodified' => 0,
118
-				],
119
-			]);
120
-
121
-		$this->connection->expects(self::once())
122
-			->method('queryWebcalFeed')
123
-			->willReturn($result);
124
-
125
-		$this->caldavBackend->expects(self::once())
126
-			->method('getLimitedCalendarObjects')
127
-			->willReturn($calendarObject);
128
-
129
-		$denormalised = [
130
-			'etag' => 100,
131
-			'size' => strlen($calendarObject[$uid]['calendardata']),
132
-			'uid' => 'sub456'
133
-		];
134
-
135
-		$this->caldavBackend->expects(self::once())
136
-			->method('getDenormalizedData')
137
-			->willReturn($denormalised);
138
-
139
-		$this->caldavBackend->expects(self::never())
140
-			->method('createCalendarObject');
141
-
142
-		$refreshWebcalService->refreshSubscription('principals/users/testuser', 'sub456');
143
-	}
144
-
145
-	public function testRunJustUpdated(): void {
146
-		$refreshWebcalService = $this->getMockBuilder(RefreshWebcalService::class)
147
-			->onlyMethods(['getRandomCalendarObjectUri'])
148
-			->setConstructorArgs([$this->caldavBackend, $this->logger, $this->connection, $this->time])
149
-			->getMock();
150
-
151
-		$refreshWebcalService
152
-			->method('getRandomCalendarObjectUri')
153
-			->willReturn('uri-1.ics');
154
-
155
-		$this->caldavBackend->expects(self::once())
156
-			->method('getSubscriptionsForUser')
157
-			->with('principals/users/testuser')
158
-			->willReturn([
159
-				[
160
-					'id' => '99',
161
-					'uri' => 'sub456',
162
-					RefreshWebcalService::REFRESH_RATE => 'P1D',
163
-					RefreshWebcalService::STRIP_TODOS => '1',
164
-					RefreshWebcalService::STRIP_ALARMS => '1',
165
-					RefreshWebcalService::STRIP_ATTACHMENTS => '1',
166
-					'source' => 'webcal://foo.bar/bla',
167
-					'lastmodified' => time(),
168
-				],
169
-				[
170
-					'id' => '42',
171
-					'uri' => 'sub123',
172
-					RefreshWebcalService::REFRESH_RATE => 'PT1H',
173
-					RefreshWebcalService::STRIP_TODOS => '1',
174
-					RefreshWebcalService::STRIP_ALARMS => '1',
175
-					RefreshWebcalService::STRIP_ATTACHMENTS => '1',
176
-					'source' => 'webcal://foo.bar/bla2',
177
-					'lastmodified' => time(),
178
-				],
179
-			]);
180
-
181
-		$timeMock = $this->createMock(\DateTime::class);
182
-		$this->time->expects(self::once())
183
-			->method('getDateTime')
184
-			->willReturn($timeMock);
185
-		$timeMock->expects(self::once())
186
-			->method('getTimestamp')
187
-			->willReturn(2101724667);
188
-		$this->time->expects(self::once())
189
-			->method('getTime')
190
-			->willReturn(time());
191
-		$this->connection->expects(self::never())
192
-			->method('queryWebcalFeed');
193
-		$this->caldavBackend->expects(self::never())
194
-			->method('createCalendarObject');
195
-
196
-		$refreshWebcalService->refreshSubscription('principals/users/testuser', 'sub123');
197
-	}
198
-
199
-	#[\PHPUnit\Framework\Attributes\DataProvider('runDataProvider')]
200
-	public function testRunCreateCalendarNoException(string $body, string $contentType, string $result): void {
201
-		$refreshWebcalService = $this->getMockBuilder(RefreshWebcalService::class)
202
-			->onlyMethods(['getRandomCalendarObjectUri', 'getSubscription',])
203
-			->setConstructorArgs([$this->caldavBackend, $this->logger, $this->connection, $this->time])
204
-			->getMock();
205
-
206
-		$refreshWebcalService
207
-			->method('getRandomCalendarObjectUri')
208
-			->willReturn('uri-1.ics');
209
-
210
-		$refreshWebcalService
211
-			->method('getSubscription')
212
-			->willReturn([
213
-				'id' => '42',
214
-				'uri' => 'sub123',
215
-				RefreshWebcalService::REFRESH_RATE => 'PT1H',
216
-				RefreshWebcalService::STRIP_TODOS => '1',
217
-				RefreshWebcalService::STRIP_ALARMS => '1',
218
-				RefreshWebcalService::STRIP_ATTACHMENTS => '1',
219
-				'source' => 'webcal://foo.bar/bla2',
220
-				'lastmodified' => 0,
221
-			]);
222
-
223
-		$this->connection->expects(self::once())
224
-			->method('queryWebcalFeed')
225
-			->willReturn($result);
226
-
227
-		$this->caldavBackend->expects(self::once())
228
-			->method('createCalendarObject')
229
-			->with(42, 'uri-1.ics', $result, 1);
230
-
231
-		$noInstanceException = new NoInstancesException("can't add calendar object");
232
-		$this->caldavBackend->expects(self::once())
233
-			->method('createCalendarObject')
234
-			->willThrowException($noInstanceException);
235
-
236
-		$this->logger->expects(self::once())
237
-			->method('warning')
238
-			->with('Unable to create calendar object from subscription {subscriptionId}', ['exception' => $noInstanceException, 'subscriptionId' => '42', 'source' => 'webcal://foo.bar/bla2']);
239
-
240
-		$refreshWebcalService->refreshSubscription('principals/users/testuser', 'sub123');
241
-	}
242
-
243
-	#[\PHPUnit\Framework\Attributes\DataProvider('runDataProvider')]
244
-	public function testRunCreateCalendarBadRequest(string $body, string $contentType, string $result): void {
245
-		$refreshWebcalService = $this->getMockBuilder(RefreshWebcalService::class)
246
-			->onlyMethods(['getRandomCalendarObjectUri', 'getSubscription'])
247
-			->setConstructorArgs([$this->caldavBackend, $this->logger, $this->connection, $this->time])
248
-			->getMock();
249
-
250
-		$refreshWebcalService
251
-			->method('getRandomCalendarObjectUri')
252
-			->willReturn('uri-1.ics');
253
-
254
-		$refreshWebcalService
255
-			->method('getSubscription')
256
-			->willReturn([
257
-				'id' => '42',
258
-				'uri' => 'sub123',
259
-				RefreshWebcalService::REFRESH_RATE => 'PT1H',
260
-				RefreshWebcalService::STRIP_TODOS => '1',
261
-				RefreshWebcalService::STRIP_ALARMS => '1',
262
-				RefreshWebcalService::STRIP_ATTACHMENTS => '1',
263
-				'source' => 'webcal://foo.bar/bla2',
264
-				'lastmodified' => 0,
265
-			]);
266
-
267
-		$this->connection->expects(self::once())
268
-			->method('queryWebcalFeed')
269
-			->willReturn($result);
270
-
271
-		$this->caldavBackend->expects(self::once())
272
-			->method('createCalendarObject')
273
-			->with(42, 'uri-1.ics', $result, 1);
274
-
275
-		$badRequestException = new BadRequest("can't add reach calendar url");
276
-		$this->caldavBackend->expects(self::once())
277
-			->method('createCalendarObject')
278
-			->willThrowException($badRequestException);
279
-
280
-		$this->logger->expects(self::once())
281
-			->method('warning')
282
-			->with('Unable to create calendar object from subscription {subscriptionId}', ['exception' => $badRequestException, 'subscriptionId' => '42', 'source' => 'webcal://foo.bar/bla2']);
283
-
284
-		$refreshWebcalService->refreshSubscription('principals/users/testuser', 'sub123');
285
-	}
286
-
287
-	public static function identicalDataProvider(): array {
288
-		return [
289
-			[
290
-				'12345',
291
-				[
292
-					'12345' => [
293
-						'id' => 42,
294
-						'etag' => 100,
295
-						'uri' => 'sub456',
296
-						'calendardata' => "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Sabre//Sabre VObject 4.1.1//EN\r\nCALSCALE:GREGORIAN\r\nBEGIN:VEVENT\r\nUID:12345\r\nDTSTAMP:20160218T133704Z\r\nDTSTART;VALUE=DATE:19000101\r\nDTEND;VALUE=DATE:19000102\r\nRRULE:FREQ=YEARLY\r\nSUMMARY:12345's Birthday (1900)\r\nTRANSP:TRANSPARENT\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n",
297
-					],
298
-				],
299
-				"BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Sabre//Sabre VObject 4.1.1//EN\r\nCALSCALE:GREGORIAN\r\nBEGIN:VEVENT\r\nUID:12345\r\nDTSTAMP:20160218T133704Z\r\nDTSTART;VALUE=DATE:19000101\r\nDTEND;VALUE=DATE:19000102\r\nRRULE:FREQ=YEARLY\r\nSUMMARY:12345's Birthday (1900)\r\nTRANSP:TRANSPARENT\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n",
300
-				'text/calendar;charset=utf8',
301
-				"BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Sabre//Sabre VObject 4.1.1//EN\r\nCALSCALE:GREGORIAN\r\nBEGIN:VEVENT\r\nUID:12345\r\nDTSTAMP:20180218T133704Z\r\nDTSTART;VALUE=DATE:19000101\r\nDTEND;VALUE=DATE:19000102\r\nRRULE:FREQ=YEARLY\r\nSUMMARY:12345's Birthday (1900)\r\nTRANSP:TRANSPARENT\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n",
302
-			],
303
-		];
304
-	}
305
-
306
-	public static function runDataProvider(): array {
307
-		return [
308
-			[
309
-				"BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Sabre//Sabre VObject 4.1.1//EN\r\nCALSCALE:GREGORIAN\r\nBEGIN:VEVENT\r\nUID:12345\r\nDTSTAMP:20160218T133704Z\r\nDTSTART;VALUE=DATE:19000101\r\nDTEND;VALUE=DATE:19000102\r\nRRULE:FREQ=YEARLY\r\nSUMMARY:12345's Birthday (1900)\r\nTRANSP:TRANSPARENT\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n",
310
-				'text/calendar;charset=utf8',
311
-				"BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Sabre//Sabre VObject " . VObject\Version::VERSION . "//EN\r\nCALSCALE:GREGORIAN\r\nBEGIN:VEVENT\r\nUID:12345\r\nDTSTAMP:20160218T133704Z\r\nDTSTART;VALUE=DATE:19000101\r\nDTEND;VALUE=DATE:19000102\r\nRRULE:FREQ=YEARLY\r\nSUMMARY:12345's Birthday (1900)\r\nTRANSP:TRANSPARENT\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n",
312
-			],
313
-			[
314
-				'["vcalendar",[["prodid",{},"text","-//Example Corp.//Example Client//EN"],["version",{},"text","2.0"]],[["vtimezone",[["last-modified",{},"date-time","2004-01-10T03:28:45Z"],["tzid",{},"text","US/Eastern"]],[["daylight",[["dtstart",{},"date-time","2000-04-04T02:00:00"],["rrule",{},"recur",{"freq":"YEARLY","byday":"1SU","bymonth":4}],["tzname",{},"text","EDT"],["tzoffsetfrom",{},"utc-offset","-05:00"],["tzoffsetto",{},"utc-offset","-04:00"]],[]],["standard",[["dtstart",{},"date-time","2000-10-26T02:00:00"],["rrule",{},"recur",{"freq":"YEARLY","byday":"1SU","bymonth":10}],["tzname",{},"text","EST"],["tzoffsetfrom",{},"utc-offset","-04:00"],["tzoffsetto",{},"utc-offset","-05:00"]],[]]]],["vevent",[["dtstamp",{},"date-time","2006-02-06T00:11:21Z"],["dtstart",{"tzid":"US/Eastern"},"date-time","2006-01-02T14:00:00"],["duration",{},"duration","PT1H"],["recurrence-id",{"tzid":"US/Eastern"},"date-time","2006-01-04T12:00:00"],["summary",{},"text","Event #2"],["uid",{},"text","12345"]],[]]]]',
315
-				'application/calendar+json',
316
-				"BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Sabre//Sabre VObject " . VObject\Version::VERSION . "//EN\r\nCALSCALE:GREGORIAN\r\nBEGIN:VTIMEZONE\r\nLAST-MODIFIED:20040110T032845Z\r\nTZID:US/Eastern\r\nBEGIN:DAYLIGHT\r\nDTSTART:20000404T020000\r\nRRULE:FREQ=YEARLY;BYDAY=1SU;BYMONTH=4\r\nTZNAME:EDT\r\nTZOFFSETFROM:-0500\r\nTZOFFSETTO:-0400\r\nEND:DAYLIGHT\r\nBEGIN:STANDARD\r\nDTSTART:20001026T020000\r\nRRULE:FREQ=YEARLY;BYDAY=1SU;BYMONTH=10\r\nTZNAME:EST\r\nTZOFFSETFROM:-0400\r\nTZOFFSETTO:-0500\r\nEND:STANDARD\r\nEND:VTIMEZONE\r\nBEGIN:VEVENT\r\nDTSTAMP:20060206T001121Z\r\nDTSTART;TZID=US/Eastern:20060102T140000\r\nDURATION:PT1H\r\nRECURRENCE-ID;TZID=US/Eastern:20060104T120000\r\nSUMMARY:Event #2\r\nUID:12345\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n"
317
-			],
318
-			[
319
-				'<?xml version="1.0" encoding="utf-8" ?><icalendar xmlns="urn:ietf:params:xml:ns:icalendar-2.0"><vcalendar><properties><prodid><text>-//Example Inc.//Example Client//EN</text></prodid><version><text>2.0</text></version></properties><components><vevent><properties><dtstamp><date-time>2006-02-06T00:11:21Z</date-time></dtstamp><dtstart><parameters><tzid><text>US/Eastern</text></tzid></parameters><date-time>2006-01-04T14:00:00</date-time></dtstart><duration><duration>PT1H</duration></duration><recurrence-id><parameters><tzid><text>US/Eastern</text></tzid></parameters><date-time>2006-01-04T12:00:00</date-time></recurrence-id><summary><text>Event #2 bis</text></summary><uid><text>12345</text></uid></properties></vevent></components></vcalendar></icalendar>',
320
-				'application/calendar+xml',
321
-				"BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Sabre//Sabre VObject " . VObject\Version::VERSION . "//EN\r\nCALSCALE:GREGORIAN\r\nBEGIN:VEVENT\r\nDTSTAMP:20060206T001121Z\r\nDTSTART;TZID=US/Eastern:20060104T140000\r\nDURATION:PT1H\r\nRECURRENCE-ID;TZID=US/Eastern:20060104T120000\r\nSUMMARY:Event #2 bis\r\nUID:12345\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n"
322
-			]
323
-		];
324
-	}
23
+    private CalDavBackend&MockObject $caldavBackend;
24
+    private Connection&MockObject $connection;
25
+    private LoggerInterface&MockObject $logger;
26
+    private ITimeFactory&MockObject $time;
27
+
28
+    protected function setUp(): void {
29
+        parent::setUp();
30
+
31
+        $this->caldavBackend = $this->createMock(CalDavBackend::class);
32
+        $this->connection = $this->createMock(Connection::class);
33
+        $this->logger = $this->createMock(LoggerInterface::class);
34
+        $this->time = $this->createMock(ITimeFactory::class);
35
+    }
36
+
37
+    #[\PHPUnit\Framework\Attributes\DataProvider('runDataProvider')]
38
+    public function testRun(string $body, string $contentType, string $result): void {
39
+        $refreshWebcalService = $this->getMockBuilder(RefreshWebcalService::class)
40
+            ->onlyMethods(['getRandomCalendarObjectUri'])
41
+            ->setConstructorArgs([$this->caldavBackend, $this->logger, $this->connection, $this->time])
42
+            ->getMock();
43
+
44
+        $refreshWebcalService
45
+            ->method('getRandomCalendarObjectUri')
46
+            ->willReturn('uri-1.ics');
47
+
48
+        $this->caldavBackend->expects(self::once())
49
+            ->method('getSubscriptionsForUser')
50
+            ->with('principals/users/testuser')
51
+            ->willReturn([
52
+                [
53
+                    'id' => '99',
54
+                    'uri' => 'sub456',
55
+                    RefreshWebcalService::REFRESH_RATE => 'P1D',
56
+                    RefreshWebcalService::STRIP_TODOS => '1',
57
+                    RefreshWebcalService::STRIP_ALARMS => '1',
58
+                    RefreshWebcalService::STRIP_ATTACHMENTS => '1',
59
+                    'source' => 'webcal://foo.bar/bla',
60
+                    'lastmodified' => 0,
61
+                ],
62
+                [
63
+                    'id' => '42',
64
+                    'uri' => 'sub123',
65
+                    RefreshWebcalService::REFRESH_RATE => 'PT1H',
66
+                    RefreshWebcalService::STRIP_TODOS => '1',
67
+                    RefreshWebcalService::STRIP_ALARMS => '1',
68
+                    RefreshWebcalService::STRIP_ATTACHMENTS => '1',
69
+                    'source' => 'webcal://foo.bar/bla2',
70
+                    'lastmodified' => 0,
71
+                ],
72
+            ]);
73
+
74
+        $this->connection->expects(self::once())
75
+            ->method('queryWebcalFeed')
76
+            ->willReturn($result);
77
+        $this->caldavBackend->expects(self::once())
78
+            ->method('createCalendarObject')
79
+            ->with(42, 'uri-1.ics', $result, 1);
80
+
81
+        $refreshWebcalService->refreshSubscription('principals/users/testuser', 'sub123');
82
+    }
83
+
84
+    #[\PHPUnit\Framework\Attributes\DataProvider('identicalDataProvider')]
85
+    public function testRunIdentical(string $uid, array $calendarObject, string $body, string $contentType, string $result): void {
86
+        $refreshWebcalService = $this->getMockBuilder(RefreshWebcalService::class)
87
+            ->onlyMethods(['getRandomCalendarObjectUri'])
88
+            ->setConstructorArgs([$this->caldavBackend, $this->logger, $this->connection, $this->time])
89
+            ->getMock();
90
+
91
+        $refreshWebcalService
92
+            ->method('getRandomCalendarObjectUri')
93
+            ->willReturn('uri-1.ics');
94
+
95
+        $this->caldavBackend->expects(self::once())
96
+            ->method('getSubscriptionsForUser')
97
+            ->with('principals/users/testuser')
98
+            ->willReturn([
99
+                [
100
+                    'id' => '99',
101
+                    'uri' => 'sub456',
102
+                    RefreshWebcalService::REFRESH_RATE => 'P1D',
103
+                    RefreshWebcalService::STRIP_TODOS => '1',
104
+                    RefreshWebcalService::STRIP_ALARMS => '1',
105
+                    RefreshWebcalService::STRIP_ATTACHMENTS => '1',
106
+                    'source' => 'webcal://foo.bar/bla',
107
+                    'lastmodified' => 0,
108
+                ],
109
+                [
110
+                    'id' => '42',
111
+                    'uri' => 'sub123',
112
+                    RefreshWebcalService::REFRESH_RATE => 'PT1H',
113
+                    RefreshWebcalService::STRIP_TODOS => '1',
114
+                    RefreshWebcalService::STRIP_ALARMS => '1',
115
+                    RefreshWebcalService::STRIP_ATTACHMENTS => '1',
116
+                    'source' => 'webcal://foo.bar/bla2',
117
+                    'lastmodified' => 0,
118
+                ],
119
+            ]);
120
+
121
+        $this->connection->expects(self::once())
122
+            ->method('queryWebcalFeed')
123
+            ->willReturn($result);
124
+
125
+        $this->caldavBackend->expects(self::once())
126
+            ->method('getLimitedCalendarObjects')
127
+            ->willReturn($calendarObject);
128
+
129
+        $denormalised = [
130
+            'etag' => 100,
131
+            'size' => strlen($calendarObject[$uid]['calendardata']),
132
+            'uid' => 'sub456'
133
+        ];
134
+
135
+        $this->caldavBackend->expects(self::once())
136
+            ->method('getDenormalizedData')
137
+            ->willReturn($denormalised);
138
+
139
+        $this->caldavBackend->expects(self::never())
140
+            ->method('createCalendarObject');
141
+
142
+        $refreshWebcalService->refreshSubscription('principals/users/testuser', 'sub456');
143
+    }
144
+
145
+    public function testRunJustUpdated(): void {
146
+        $refreshWebcalService = $this->getMockBuilder(RefreshWebcalService::class)
147
+            ->onlyMethods(['getRandomCalendarObjectUri'])
148
+            ->setConstructorArgs([$this->caldavBackend, $this->logger, $this->connection, $this->time])
149
+            ->getMock();
150
+
151
+        $refreshWebcalService
152
+            ->method('getRandomCalendarObjectUri')
153
+            ->willReturn('uri-1.ics');
154
+
155
+        $this->caldavBackend->expects(self::once())
156
+            ->method('getSubscriptionsForUser')
157
+            ->with('principals/users/testuser')
158
+            ->willReturn([
159
+                [
160
+                    'id' => '99',
161
+                    'uri' => 'sub456',
162
+                    RefreshWebcalService::REFRESH_RATE => 'P1D',
163
+                    RefreshWebcalService::STRIP_TODOS => '1',
164
+                    RefreshWebcalService::STRIP_ALARMS => '1',
165
+                    RefreshWebcalService::STRIP_ATTACHMENTS => '1',
166
+                    'source' => 'webcal://foo.bar/bla',
167
+                    'lastmodified' => time(),
168
+                ],
169
+                [
170
+                    'id' => '42',
171
+                    'uri' => 'sub123',
172
+                    RefreshWebcalService::REFRESH_RATE => 'PT1H',
173
+                    RefreshWebcalService::STRIP_TODOS => '1',
174
+                    RefreshWebcalService::STRIP_ALARMS => '1',
175
+                    RefreshWebcalService::STRIP_ATTACHMENTS => '1',
176
+                    'source' => 'webcal://foo.bar/bla2',
177
+                    'lastmodified' => time(),
178
+                ],
179
+            ]);
180
+
181
+        $timeMock = $this->createMock(\DateTime::class);
182
+        $this->time->expects(self::once())
183
+            ->method('getDateTime')
184
+            ->willReturn($timeMock);
185
+        $timeMock->expects(self::once())
186
+            ->method('getTimestamp')
187
+            ->willReturn(2101724667);
188
+        $this->time->expects(self::once())
189
+            ->method('getTime')
190
+            ->willReturn(time());
191
+        $this->connection->expects(self::never())
192
+            ->method('queryWebcalFeed');
193
+        $this->caldavBackend->expects(self::never())
194
+            ->method('createCalendarObject');
195
+
196
+        $refreshWebcalService->refreshSubscription('principals/users/testuser', 'sub123');
197
+    }
198
+
199
+    #[\PHPUnit\Framework\Attributes\DataProvider('runDataProvider')]
200
+    public function testRunCreateCalendarNoException(string $body, string $contentType, string $result): void {
201
+        $refreshWebcalService = $this->getMockBuilder(RefreshWebcalService::class)
202
+            ->onlyMethods(['getRandomCalendarObjectUri', 'getSubscription',])
203
+            ->setConstructorArgs([$this->caldavBackend, $this->logger, $this->connection, $this->time])
204
+            ->getMock();
205
+
206
+        $refreshWebcalService
207
+            ->method('getRandomCalendarObjectUri')
208
+            ->willReturn('uri-1.ics');
209
+
210
+        $refreshWebcalService
211
+            ->method('getSubscription')
212
+            ->willReturn([
213
+                'id' => '42',
214
+                'uri' => 'sub123',
215
+                RefreshWebcalService::REFRESH_RATE => 'PT1H',
216
+                RefreshWebcalService::STRIP_TODOS => '1',
217
+                RefreshWebcalService::STRIP_ALARMS => '1',
218
+                RefreshWebcalService::STRIP_ATTACHMENTS => '1',
219
+                'source' => 'webcal://foo.bar/bla2',
220
+                'lastmodified' => 0,
221
+            ]);
222
+
223
+        $this->connection->expects(self::once())
224
+            ->method('queryWebcalFeed')
225
+            ->willReturn($result);
226
+
227
+        $this->caldavBackend->expects(self::once())
228
+            ->method('createCalendarObject')
229
+            ->with(42, 'uri-1.ics', $result, 1);
230
+
231
+        $noInstanceException = new NoInstancesException("can't add calendar object");
232
+        $this->caldavBackend->expects(self::once())
233
+            ->method('createCalendarObject')
234
+            ->willThrowException($noInstanceException);
235
+
236
+        $this->logger->expects(self::once())
237
+            ->method('warning')
238
+            ->with('Unable to create calendar object from subscription {subscriptionId}', ['exception' => $noInstanceException, 'subscriptionId' => '42', 'source' => 'webcal://foo.bar/bla2']);
239
+
240
+        $refreshWebcalService->refreshSubscription('principals/users/testuser', 'sub123');
241
+    }
242
+
243
+    #[\PHPUnit\Framework\Attributes\DataProvider('runDataProvider')]
244
+    public function testRunCreateCalendarBadRequest(string $body, string $contentType, string $result): void {
245
+        $refreshWebcalService = $this->getMockBuilder(RefreshWebcalService::class)
246
+            ->onlyMethods(['getRandomCalendarObjectUri', 'getSubscription'])
247
+            ->setConstructorArgs([$this->caldavBackend, $this->logger, $this->connection, $this->time])
248
+            ->getMock();
249
+
250
+        $refreshWebcalService
251
+            ->method('getRandomCalendarObjectUri')
252
+            ->willReturn('uri-1.ics');
253
+
254
+        $refreshWebcalService
255
+            ->method('getSubscription')
256
+            ->willReturn([
257
+                'id' => '42',
258
+                'uri' => 'sub123',
259
+                RefreshWebcalService::REFRESH_RATE => 'PT1H',
260
+                RefreshWebcalService::STRIP_TODOS => '1',
261
+                RefreshWebcalService::STRIP_ALARMS => '1',
262
+                RefreshWebcalService::STRIP_ATTACHMENTS => '1',
263
+                'source' => 'webcal://foo.bar/bla2',
264
+                'lastmodified' => 0,
265
+            ]);
266
+
267
+        $this->connection->expects(self::once())
268
+            ->method('queryWebcalFeed')
269
+            ->willReturn($result);
270
+
271
+        $this->caldavBackend->expects(self::once())
272
+            ->method('createCalendarObject')
273
+            ->with(42, 'uri-1.ics', $result, 1);
274
+
275
+        $badRequestException = new BadRequest("can't add reach calendar url");
276
+        $this->caldavBackend->expects(self::once())
277
+            ->method('createCalendarObject')
278
+            ->willThrowException($badRequestException);
279
+
280
+        $this->logger->expects(self::once())
281
+            ->method('warning')
282
+            ->with('Unable to create calendar object from subscription {subscriptionId}', ['exception' => $badRequestException, 'subscriptionId' => '42', 'source' => 'webcal://foo.bar/bla2']);
283
+
284
+        $refreshWebcalService->refreshSubscription('principals/users/testuser', 'sub123');
285
+    }
286
+
287
+    public static function identicalDataProvider(): array {
288
+        return [
289
+            [
290
+                '12345',
291
+                [
292
+                    '12345' => [
293
+                        'id' => 42,
294
+                        'etag' => 100,
295
+                        'uri' => 'sub456',
296
+                        'calendardata' => "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Sabre//Sabre VObject 4.1.1//EN\r\nCALSCALE:GREGORIAN\r\nBEGIN:VEVENT\r\nUID:12345\r\nDTSTAMP:20160218T133704Z\r\nDTSTART;VALUE=DATE:19000101\r\nDTEND;VALUE=DATE:19000102\r\nRRULE:FREQ=YEARLY\r\nSUMMARY:12345's Birthday (1900)\r\nTRANSP:TRANSPARENT\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n",
297
+                    ],
298
+                ],
299
+                "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Sabre//Sabre VObject 4.1.1//EN\r\nCALSCALE:GREGORIAN\r\nBEGIN:VEVENT\r\nUID:12345\r\nDTSTAMP:20160218T133704Z\r\nDTSTART;VALUE=DATE:19000101\r\nDTEND;VALUE=DATE:19000102\r\nRRULE:FREQ=YEARLY\r\nSUMMARY:12345's Birthday (1900)\r\nTRANSP:TRANSPARENT\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n",
300
+                'text/calendar;charset=utf8',
301
+                "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Sabre//Sabre VObject 4.1.1//EN\r\nCALSCALE:GREGORIAN\r\nBEGIN:VEVENT\r\nUID:12345\r\nDTSTAMP:20180218T133704Z\r\nDTSTART;VALUE=DATE:19000101\r\nDTEND;VALUE=DATE:19000102\r\nRRULE:FREQ=YEARLY\r\nSUMMARY:12345's Birthday (1900)\r\nTRANSP:TRANSPARENT\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n",
302
+            ],
303
+        ];
304
+    }
305
+
306
+    public static function runDataProvider(): array {
307
+        return [
308
+            [
309
+                "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Sabre//Sabre VObject 4.1.1//EN\r\nCALSCALE:GREGORIAN\r\nBEGIN:VEVENT\r\nUID:12345\r\nDTSTAMP:20160218T133704Z\r\nDTSTART;VALUE=DATE:19000101\r\nDTEND;VALUE=DATE:19000102\r\nRRULE:FREQ=YEARLY\r\nSUMMARY:12345's Birthday (1900)\r\nTRANSP:TRANSPARENT\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n",
310
+                'text/calendar;charset=utf8',
311
+                "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Sabre//Sabre VObject " . VObject\Version::VERSION . "//EN\r\nCALSCALE:GREGORIAN\r\nBEGIN:VEVENT\r\nUID:12345\r\nDTSTAMP:20160218T133704Z\r\nDTSTART;VALUE=DATE:19000101\r\nDTEND;VALUE=DATE:19000102\r\nRRULE:FREQ=YEARLY\r\nSUMMARY:12345's Birthday (1900)\r\nTRANSP:TRANSPARENT\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n",
312
+            ],
313
+            [
314
+                '["vcalendar",[["prodid",{},"text","-//Example Corp.//Example Client//EN"],["version",{},"text","2.0"]],[["vtimezone",[["last-modified",{},"date-time","2004-01-10T03:28:45Z"],["tzid",{},"text","US/Eastern"]],[["daylight",[["dtstart",{},"date-time","2000-04-04T02:00:00"],["rrule",{},"recur",{"freq":"YEARLY","byday":"1SU","bymonth":4}],["tzname",{},"text","EDT"],["tzoffsetfrom",{},"utc-offset","-05:00"],["tzoffsetto",{},"utc-offset","-04:00"]],[]],["standard",[["dtstart",{},"date-time","2000-10-26T02:00:00"],["rrule",{},"recur",{"freq":"YEARLY","byday":"1SU","bymonth":10}],["tzname",{},"text","EST"],["tzoffsetfrom",{},"utc-offset","-04:00"],["tzoffsetto",{},"utc-offset","-05:00"]],[]]]],["vevent",[["dtstamp",{},"date-time","2006-02-06T00:11:21Z"],["dtstart",{"tzid":"US/Eastern"},"date-time","2006-01-02T14:00:00"],["duration",{},"duration","PT1H"],["recurrence-id",{"tzid":"US/Eastern"},"date-time","2006-01-04T12:00:00"],["summary",{},"text","Event #2"],["uid",{},"text","12345"]],[]]]]',
315
+                'application/calendar+json',
316
+                "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Sabre//Sabre VObject " . VObject\Version::VERSION . "//EN\r\nCALSCALE:GREGORIAN\r\nBEGIN:VTIMEZONE\r\nLAST-MODIFIED:20040110T032845Z\r\nTZID:US/Eastern\r\nBEGIN:DAYLIGHT\r\nDTSTART:20000404T020000\r\nRRULE:FREQ=YEARLY;BYDAY=1SU;BYMONTH=4\r\nTZNAME:EDT\r\nTZOFFSETFROM:-0500\r\nTZOFFSETTO:-0400\r\nEND:DAYLIGHT\r\nBEGIN:STANDARD\r\nDTSTART:20001026T020000\r\nRRULE:FREQ=YEARLY;BYDAY=1SU;BYMONTH=10\r\nTZNAME:EST\r\nTZOFFSETFROM:-0400\r\nTZOFFSETTO:-0500\r\nEND:STANDARD\r\nEND:VTIMEZONE\r\nBEGIN:VEVENT\r\nDTSTAMP:20060206T001121Z\r\nDTSTART;TZID=US/Eastern:20060102T140000\r\nDURATION:PT1H\r\nRECURRENCE-ID;TZID=US/Eastern:20060104T120000\r\nSUMMARY:Event #2\r\nUID:12345\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n"
317
+            ],
318
+            [
319
+                '<?xml version="1.0" encoding="utf-8" ?><icalendar xmlns="urn:ietf:params:xml:ns:icalendar-2.0"><vcalendar><properties><prodid><text>-//Example Inc.//Example Client//EN</text></prodid><version><text>2.0</text></version></properties><components><vevent><properties><dtstamp><date-time>2006-02-06T00:11:21Z</date-time></dtstamp><dtstart><parameters><tzid><text>US/Eastern</text></tzid></parameters><date-time>2006-01-04T14:00:00</date-time></dtstart><duration><duration>PT1H</duration></duration><recurrence-id><parameters><tzid><text>US/Eastern</text></tzid></parameters><date-time>2006-01-04T12:00:00</date-time></recurrence-id><summary><text>Event #2 bis</text></summary><uid><text>12345</text></uid></properties></vevent></components></vcalendar></icalendar>',
320
+                'application/calendar+xml',
321
+                "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Sabre//Sabre VObject " . VObject\Version::VERSION . "//EN\r\nCALSCALE:GREGORIAN\r\nBEGIN:VEVENT\r\nDTSTAMP:20060206T001121Z\r\nDTSTART;TZID=US/Eastern:20060104T140000\r\nDURATION:PT1H\r\nRECURRENCE-ID;TZID=US/Eastern:20060104T120000\r\nSUMMARY:Event #2 bis\r\nUID:12345\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n"
322
+            ]
323
+        ];
324
+    }
325 325
 }
Please login to merge, or discard this patch.
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -199,7 +199,7 @@  discard block
 block discarded – undo
199 199
 	#[\PHPUnit\Framework\Attributes\DataProvider('runDataProvider')]
200 200
 	public function testRunCreateCalendarNoException(string $body, string $contentType, string $result): void {
201 201
 		$refreshWebcalService = $this->getMockBuilder(RefreshWebcalService::class)
202
-			->onlyMethods(['getRandomCalendarObjectUri', 'getSubscription',])
202
+			->onlyMethods(['getRandomCalendarObjectUri', 'getSubscription', ])
203 203
 			->setConstructorArgs([$this->caldavBackend, $this->logger, $this->connection, $this->time])
204 204
 			->getMock();
205 205
 
@@ -308,17 +308,17 @@  discard block
 block discarded – undo
308 308
 			[
309 309
 				"BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Sabre//Sabre VObject 4.1.1//EN\r\nCALSCALE:GREGORIAN\r\nBEGIN:VEVENT\r\nUID:12345\r\nDTSTAMP:20160218T133704Z\r\nDTSTART;VALUE=DATE:19000101\r\nDTEND;VALUE=DATE:19000102\r\nRRULE:FREQ=YEARLY\r\nSUMMARY:12345's Birthday (1900)\r\nTRANSP:TRANSPARENT\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n",
310 310
 				'text/calendar;charset=utf8',
311
-				"BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Sabre//Sabre VObject " . VObject\Version::VERSION . "//EN\r\nCALSCALE:GREGORIAN\r\nBEGIN:VEVENT\r\nUID:12345\r\nDTSTAMP:20160218T133704Z\r\nDTSTART;VALUE=DATE:19000101\r\nDTEND;VALUE=DATE:19000102\r\nRRULE:FREQ=YEARLY\r\nSUMMARY:12345's Birthday (1900)\r\nTRANSP:TRANSPARENT\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n",
311
+				"BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Sabre//Sabre VObject ".VObject\Version::VERSION."//EN\r\nCALSCALE:GREGORIAN\r\nBEGIN:VEVENT\r\nUID:12345\r\nDTSTAMP:20160218T133704Z\r\nDTSTART;VALUE=DATE:19000101\r\nDTEND;VALUE=DATE:19000102\r\nRRULE:FREQ=YEARLY\r\nSUMMARY:12345's Birthday (1900)\r\nTRANSP:TRANSPARENT\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n",
312 312
 			],
313 313
 			[
314 314
 				'["vcalendar",[["prodid",{},"text","-//Example Corp.//Example Client//EN"],["version",{},"text","2.0"]],[["vtimezone",[["last-modified",{},"date-time","2004-01-10T03:28:45Z"],["tzid",{},"text","US/Eastern"]],[["daylight",[["dtstart",{},"date-time","2000-04-04T02:00:00"],["rrule",{},"recur",{"freq":"YEARLY","byday":"1SU","bymonth":4}],["tzname",{},"text","EDT"],["tzoffsetfrom",{},"utc-offset","-05:00"],["tzoffsetto",{},"utc-offset","-04:00"]],[]],["standard",[["dtstart",{},"date-time","2000-10-26T02:00:00"],["rrule",{},"recur",{"freq":"YEARLY","byday":"1SU","bymonth":10}],["tzname",{},"text","EST"],["tzoffsetfrom",{},"utc-offset","-04:00"],["tzoffsetto",{},"utc-offset","-05:00"]],[]]]],["vevent",[["dtstamp",{},"date-time","2006-02-06T00:11:21Z"],["dtstart",{"tzid":"US/Eastern"},"date-time","2006-01-02T14:00:00"],["duration",{},"duration","PT1H"],["recurrence-id",{"tzid":"US/Eastern"},"date-time","2006-01-04T12:00:00"],["summary",{},"text","Event #2"],["uid",{},"text","12345"]],[]]]]',
315 315
 				'application/calendar+json',
316
-				"BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Sabre//Sabre VObject " . VObject\Version::VERSION . "//EN\r\nCALSCALE:GREGORIAN\r\nBEGIN:VTIMEZONE\r\nLAST-MODIFIED:20040110T032845Z\r\nTZID:US/Eastern\r\nBEGIN:DAYLIGHT\r\nDTSTART:20000404T020000\r\nRRULE:FREQ=YEARLY;BYDAY=1SU;BYMONTH=4\r\nTZNAME:EDT\r\nTZOFFSETFROM:-0500\r\nTZOFFSETTO:-0400\r\nEND:DAYLIGHT\r\nBEGIN:STANDARD\r\nDTSTART:20001026T020000\r\nRRULE:FREQ=YEARLY;BYDAY=1SU;BYMONTH=10\r\nTZNAME:EST\r\nTZOFFSETFROM:-0400\r\nTZOFFSETTO:-0500\r\nEND:STANDARD\r\nEND:VTIMEZONE\r\nBEGIN:VEVENT\r\nDTSTAMP:20060206T001121Z\r\nDTSTART;TZID=US/Eastern:20060102T140000\r\nDURATION:PT1H\r\nRECURRENCE-ID;TZID=US/Eastern:20060104T120000\r\nSUMMARY:Event #2\r\nUID:12345\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n"
316
+				"BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Sabre//Sabre VObject ".VObject\Version::VERSION."//EN\r\nCALSCALE:GREGORIAN\r\nBEGIN:VTIMEZONE\r\nLAST-MODIFIED:20040110T032845Z\r\nTZID:US/Eastern\r\nBEGIN:DAYLIGHT\r\nDTSTART:20000404T020000\r\nRRULE:FREQ=YEARLY;BYDAY=1SU;BYMONTH=4\r\nTZNAME:EDT\r\nTZOFFSETFROM:-0500\r\nTZOFFSETTO:-0400\r\nEND:DAYLIGHT\r\nBEGIN:STANDARD\r\nDTSTART:20001026T020000\r\nRRULE:FREQ=YEARLY;BYDAY=1SU;BYMONTH=10\r\nTZNAME:EST\r\nTZOFFSETFROM:-0400\r\nTZOFFSETTO:-0500\r\nEND:STANDARD\r\nEND:VTIMEZONE\r\nBEGIN:VEVENT\r\nDTSTAMP:20060206T001121Z\r\nDTSTART;TZID=US/Eastern:20060102T140000\r\nDURATION:PT1H\r\nRECURRENCE-ID;TZID=US/Eastern:20060104T120000\r\nSUMMARY:Event #2\r\nUID:12345\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n"
317 317
 			],
318 318
 			[
319 319
 				'<?xml version="1.0" encoding="utf-8" ?><icalendar xmlns="urn:ietf:params:xml:ns:icalendar-2.0"><vcalendar><properties><prodid><text>-//Example Inc.//Example Client//EN</text></prodid><version><text>2.0</text></version></properties><components><vevent><properties><dtstamp><date-time>2006-02-06T00:11:21Z</date-time></dtstamp><dtstart><parameters><tzid><text>US/Eastern</text></tzid></parameters><date-time>2006-01-04T14:00:00</date-time></dtstart><duration><duration>PT1H</duration></duration><recurrence-id><parameters><tzid><text>US/Eastern</text></tzid></parameters><date-time>2006-01-04T12:00:00</date-time></recurrence-id><summary><text>Event #2 bis</text></summary><uid><text>12345</text></uid></properties></vevent></components></vcalendar></icalendar>',
320 320
 				'application/calendar+xml',
321
-				"BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Sabre//Sabre VObject " . VObject\Version::VERSION . "//EN\r\nCALSCALE:GREGORIAN\r\nBEGIN:VEVENT\r\nDTSTAMP:20060206T001121Z\r\nDTSTART;TZID=US/Eastern:20060104T140000\r\nDURATION:PT1H\r\nRECURRENCE-ID;TZID=US/Eastern:20060104T120000\r\nSUMMARY:Event #2 bis\r\nUID:12345\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n"
321
+				"BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Sabre//Sabre VObject ".VObject\Version::VERSION."//EN\r\nCALSCALE:GREGORIAN\r\nBEGIN:VEVENT\r\nDTSTAMP:20060206T001121Z\r\nDTSTART;TZID=US/Eastern:20060104T140000\r\nDURATION:PT1H\r\nRECURRENCE-ID;TZID=US/Eastern:20060104T120000\r\nSUMMARY:Event #2 bis\r\nUID:12345\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n"
322 322
 			]
323 323
 		];
324 324
 	}
Please login to merge, or discard this patch.
apps/dav/tests/unit/CalDAV/WebcalCaching/ConnectionTest.php 1 patch
Indentation   +153 added lines, -153 removed lines patch added patch discarded remove patch
@@ -20,157 +20,157 @@
 block discarded – undo
20 20
 
21 21
 class ConnectionTest extends TestCase {
22 22
 
23
-	private IClientService&MockObject $clientService;
24
-	private IAppConfig&MockObject $config;
25
-	private LoggerInterface&MockObject $logger;
26
-	private Connection $connection;
27
-
28
-	public function setUp(): void {
29
-		$this->clientService = $this->createMock(IClientService::class);
30
-		$this->config = $this->createMock(IAppConfig::class);
31
-		$this->logger = $this->createMock(LoggerInterface::class);
32
-		$this->connection = new Connection($this->clientService, $this->config, $this->logger);
33
-	}
34
-
35
-	#[\PHPUnit\Framework\Attributes\DataProvider('runLocalURLDataProvider')]
36
-	public function testLocalUrl($source): void {
37
-		$subscription = [
38
-			'id' => 42,
39
-			'uri' => 'sub123',
40
-			'refreshreate' => 'P1H',
41
-			'striptodos' => 1,
42
-			'stripalarms' => 1,
43
-			'stripattachments' => 1,
44
-			'source' => $source,
45
-			'lastmodified' => 0,
46
-		];
47
-
48
-		$client = $this->createMock(IClient::class);
49
-		$this->clientService->expects(self::once())
50
-			->method('newClient')
51
-			->with()
52
-			->willReturn($client);
53
-
54
-		$this->config->expects(self::once())
55
-			->method('getValueString')
56
-			->with('dav', 'webcalAllowLocalAccess', 'no')
57
-			->willReturn('no');
58
-
59
-		$localServerException = new LocalServerException();
60
-		$client->expects(self::once())
61
-			->method('get')
62
-			->willThrowException($localServerException);
63
-		$this->logger->expects(self::once())
64
-			->method('warning')
65
-			->with('Subscription 42 was not refreshed because it violates local access rules', ['exception' => $localServerException]);
66
-
67
-		$this->connection->queryWebcalFeed($subscription);
68
-	}
69
-
70
-	public function testInvalidUrl(): void {
71
-		$subscription = [
72
-			'id' => 42,
73
-			'uri' => 'sub123',
74
-			'refreshreate' => 'P1H',
75
-			'striptodos' => 1,
76
-			'stripalarms' => 1,
77
-			'stripattachments' => 1,
78
-			'source' => '!@#$',
79
-			'lastmodified' => 0,
80
-		];
81
-
82
-		$client = $this->createMock(IClient::class);
83
-		$this->config->expects(self::never())
84
-			->method('getValueString');
85
-		$client->expects(self::never())
86
-			->method('get');
87
-
88
-		$this->connection->queryWebcalFeed($subscription);
89
-
90
-	}
91
-
92
-	/**
93
-	 * @param string $result
94
-	 * @param string $contentType
95
-	 */
96
-	#[\PHPUnit\Framework\Attributes\DataProvider('urlDataProvider')]
97
-	public function testConnection(string $url, string $result, string $contentType): void {
98
-		$client = $this->createMock(IClient::class);
99
-		$response = $this->createMock(IResponse::class);
100
-		$subscription = [
101
-			'id' => 42,
102
-			'uri' => 'sub123',
103
-			'refreshreate' => 'P1H',
104
-			'striptodos' => 1,
105
-			'stripalarms' => 1,
106
-			'stripattachments' => 1,
107
-			'source' => $url,
108
-			'lastmodified' => 0,
109
-		];
110
-
111
-		$this->clientService->expects($this->once())
112
-			->method('newClient')
113
-			->with()
114
-			->willReturn($client);
115
-
116
-		$this->config->expects($this->once())
117
-			->method('getValueString')
118
-			->with('dav', 'webcalAllowLocalAccess', 'no')
119
-			->willReturn('no');
120
-
121
-		$client->expects($this->once())
122
-			->method('get')
123
-			->with('https://foo.bar/bla2')
124
-			->willReturn($response);
125
-
126
-		$response->expects($this->once())
127
-			->method('getBody')
128
-			->with()
129
-			->willReturn($result);
130
-		$response->expects($this->once())
131
-			->method('getHeader')
132
-			->with('Content-Type')
133
-			->willReturn($contentType);
134
-
135
-		$this->connection->queryWebcalFeed($subscription);
136
-	}
137
-
138
-	public static function runLocalURLDataProvider(): array {
139
-		return [
140
-			['localhost/foo.bar'],
141
-			['localHost/foo.bar'],
142
-			['random-host/foo.bar'],
143
-			['[::1]/bla.blub'],
144
-			['[::]/bla.blub'],
145
-			['192.168.0.1'],
146
-			['172.16.42.1'],
147
-			['[fdf8:f53b:82e4::53]/secret.ics'],
148
-			['[fe80::200:5aee:feaa:20a2]/secret.ics'],
149
-			['[0:0:0:0:0:0:10.0.0.1]/secret.ics'],
150
-			['[0:0:0:0:0:ffff:127.0.0.0]/secret.ics'],
151
-			['10.0.0.1'],
152
-			['another-host.local'],
153
-			['service.localhost'],
154
-		];
155
-	}
156
-
157
-	public static function urlDataProvider(): array {
158
-		return [
159
-			[
160
-				'https://foo.bar/bla2',
161
-				"BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Sabre//Sabre VObject 4.1.1//EN\r\nCALSCALE:GREGORIAN\r\nBEGIN:VEVENT\r\nUID:12345\r\nDTSTAMP:20160218T133704Z\r\nDTSTART;VALUE=DATE:19000101\r\nDTEND;VALUE=DATE:19000102\r\nRRULE:FREQ=YEARLY\r\nSUMMARY:12345's Birthday (1900)\r\nTRANSP:TRANSPARENT\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n",
162
-				'text/calendar;charset=utf8',
163
-			],
164
-			[
165
-				'https://foo.bar/bla2',
166
-				'["vcalendar",[["prodid",{},"text","-//Example Corp.//Example Client//EN"],["version",{},"text","2.0"]],[["vtimezone",[["last-modified",{},"date-time","2004-01-10T03:28:45Z"],["tzid",{},"text","US/Eastern"]],[["daylight",[["dtstart",{},"date-time","2000-04-04T02:00:00"],["rrule",{},"recur",{"freq":"YEARLY","byday":"1SU","bymonth":4}],["tzname",{},"text","EDT"],["tzoffsetfrom",{},"utc-offset","-05:00"],["tzoffsetto",{},"utc-offset","-04:00"]],[]],["standard",[["dtstart",{},"date-time","2000-10-26T02:00:00"],["rrule",{},"recur",{"freq":"YEARLY","byday":"1SU","bymonth":10}],["tzname",{},"text","EST"],["tzoffsetfrom",{},"utc-offset","-04:00"],["tzoffsetto",{},"utc-offset","-05:00"]],[]]]],["vevent",[["dtstamp",{},"date-time","2006-02-06T00:11:21Z"],["dtstart",{"tzid":"US/Eastern"},"date-time","2006-01-02T14:00:00"],["duration",{},"duration","PT1H"],["recurrence-id",{"tzid":"US/Eastern"},"date-time","2006-01-04T12:00:00"],["summary",{},"text","Event #2"],["uid",{},"text","12345"]],[]]]]',
167
-				'application/calendar+json',
168
-			],
169
-			[
170
-				'https://foo.bar/bla2',
171
-				'<?xml version="1.0" encoding="utf-8" ?><icalendar xmlns="urn:ietf:params:xml:ns:icalendar-2.0"><vcalendar><properties><prodid><text>-//Example Inc.//Example Client//EN</text></prodid><version><text>2.0</text></version></properties><components><vevent><properties><dtstamp><date-time>2006-02-06T00:11:21Z</date-time></dtstamp><dtstart><parameters><tzid><text>US/Eastern</text></tzid></parameters><date-time>2006-01-04T14:00:00</date-time></dtstart><duration><duration>PT1H</duration></duration><recurrence-id><parameters><tzid><text>US/Eastern</text></tzid></parameters><date-time>2006-01-04T12:00:00</date-time></recurrence-id><summary><text>Event #2 bis</text></summary><uid><text>12345</text></uid></properties></vevent></components></vcalendar></icalendar>',
172
-				'application/calendar+xml',
173
-			],
174
-		];
175
-	}
23
+    private IClientService&MockObject $clientService;
24
+    private IAppConfig&MockObject $config;
25
+    private LoggerInterface&MockObject $logger;
26
+    private Connection $connection;
27
+
28
+    public function setUp(): void {
29
+        $this->clientService = $this->createMock(IClientService::class);
30
+        $this->config = $this->createMock(IAppConfig::class);
31
+        $this->logger = $this->createMock(LoggerInterface::class);
32
+        $this->connection = new Connection($this->clientService, $this->config, $this->logger);
33
+    }
34
+
35
+    #[\PHPUnit\Framework\Attributes\DataProvider('runLocalURLDataProvider')]
36
+    public function testLocalUrl($source): void {
37
+        $subscription = [
38
+            'id' => 42,
39
+            'uri' => 'sub123',
40
+            'refreshreate' => 'P1H',
41
+            'striptodos' => 1,
42
+            'stripalarms' => 1,
43
+            'stripattachments' => 1,
44
+            'source' => $source,
45
+            'lastmodified' => 0,
46
+        ];
47
+
48
+        $client = $this->createMock(IClient::class);
49
+        $this->clientService->expects(self::once())
50
+            ->method('newClient')
51
+            ->with()
52
+            ->willReturn($client);
53
+
54
+        $this->config->expects(self::once())
55
+            ->method('getValueString')
56
+            ->with('dav', 'webcalAllowLocalAccess', 'no')
57
+            ->willReturn('no');
58
+
59
+        $localServerException = new LocalServerException();
60
+        $client->expects(self::once())
61
+            ->method('get')
62
+            ->willThrowException($localServerException);
63
+        $this->logger->expects(self::once())
64
+            ->method('warning')
65
+            ->with('Subscription 42 was not refreshed because it violates local access rules', ['exception' => $localServerException]);
66
+
67
+        $this->connection->queryWebcalFeed($subscription);
68
+    }
69
+
70
+    public function testInvalidUrl(): void {
71
+        $subscription = [
72
+            'id' => 42,
73
+            'uri' => 'sub123',
74
+            'refreshreate' => 'P1H',
75
+            'striptodos' => 1,
76
+            'stripalarms' => 1,
77
+            'stripattachments' => 1,
78
+            'source' => '!@#$',
79
+            'lastmodified' => 0,
80
+        ];
81
+
82
+        $client = $this->createMock(IClient::class);
83
+        $this->config->expects(self::never())
84
+            ->method('getValueString');
85
+        $client->expects(self::never())
86
+            ->method('get');
87
+
88
+        $this->connection->queryWebcalFeed($subscription);
89
+
90
+    }
91
+
92
+    /**
93
+     * @param string $result
94
+     * @param string $contentType
95
+     */
96
+    #[\PHPUnit\Framework\Attributes\DataProvider('urlDataProvider')]
97
+    public function testConnection(string $url, string $result, string $contentType): void {
98
+        $client = $this->createMock(IClient::class);
99
+        $response = $this->createMock(IResponse::class);
100
+        $subscription = [
101
+            'id' => 42,
102
+            'uri' => 'sub123',
103
+            'refreshreate' => 'P1H',
104
+            'striptodos' => 1,
105
+            'stripalarms' => 1,
106
+            'stripattachments' => 1,
107
+            'source' => $url,
108
+            'lastmodified' => 0,
109
+        ];
110
+
111
+        $this->clientService->expects($this->once())
112
+            ->method('newClient')
113
+            ->with()
114
+            ->willReturn($client);
115
+
116
+        $this->config->expects($this->once())
117
+            ->method('getValueString')
118
+            ->with('dav', 'webcalAllowLocalAccess', 'no')
119
+            ->willReturn('no');
120
+
121
+        $client->expects($this->once())
122
+            ->method('get')
123
+            ->with('https://foo.bar/bla2')
124
+            ->willReturn($response);
125
+
126
+        $response->expects($this->once())
127
+            ->method('getBody')
128
+            ->with()
129
+            ->willReturn($result);
130
+        $response->expects($this->once())
131
+            ->method('getHeader')
132
+            ->with('Content-Type')
133
+            ->willReturn($contentType);
134
+
135
+        $this->connection->queryWebcalFeed($subscription);
136
+    }
137
+
138
+    public static function runLocalURLDataProvider(): array {
139
+        return [
140
+            ['localhost/foo.bar'],
141
+            ['localHost/foo.bar'],
142
+            ['random-host/foo.bar'],
143
+            ['[::1]/bla.blub'],
144
+            ['[::]/bla.blub'],
145
+            ['192.168.0.1'],
146
+            ['172.16.42.1'],
147
+            ['[fdf8:f53b:82e4::53]/secret.ics'],
148
+            ['[fe80::200:5aee:feaa:20a2]/secret.ics'],
149
+            ['[0:0:0:0:0:0:10.0.0.1]/secret.ics'],
150
+            ['[0:0:0:0:0:ffff:127.0.0.0]/secret.ics'],
151
+            ['10.0.0.1'],
152
+            ['another-host.local'],
153
+            ['service.localhost'],
154
+        ];
155
+    }
156
+
157
+    public static function urlDataProvider(): array {
158
+        return [
159
+            [
160
+                'https://foo.bar/bla2',
161
+                "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Sabre//Sabre VObject 4.1.1//EN\r\nCALSCALE:GREGORIAN\r\nBEGIN:VEVENT\r\nUID:12345\r\nDTSTAMP:20160218T133704Z\r\nDTSTART;VALUE=DATE:19000101\r\nDTEND;VALUE=DATE:19000102\r\nRRULE:FREQ=YEARLY\r\nSUMMARY:12345's Birthday (1900)\r\nTRANSP:TRANSPARENT\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n",
162
+                'text/calendar;charset=utf8',
163
+            ],
164
+            [
165
+                'https://foo.bar/bla2',
166
+                '["vcalendar",[["prodid",{},"text","-//Example Corp.//Example Client//EN"],["version",{},"text","2.0"]],[["vtimezone",[["last-modified",{},"date-time","2004-01-10T03:28:45Z"],["tzid",{},"text","US/Eastern"]],[["daylight",[["dtstart",{},"date-time","2000-04-04T02:00:00"],["rrule",{},"recur",{"freq":"YEARLY","byday":"1SU","bymonth":4}],["tzname",{},"text","EDT"],["tzoffsetfrom",{},"utc-offset","-05:00"],["tzoffsetto",{},"utc-offset","-04:00"]],[]],["standard",[["dtstart",{},"date-time","2000-10-26T02:00:00"],["rrule",{},"recur",{"freq":"YEARLY","byday":"1SU","bymonth":10}],["tzname",{},"text","EST"],["tzoffsetfrom",{},"utc-offset","-04:00"],["tzoffsetto",{},"utc-offset","-05:00"]],[]]]],["vevent",[["dtstamp",{},"date-time","2006-02-06T00:11:21Z"],["dtstart",{"tzid":"US/Eastern"},"date-time","2006-01-02T14:00:00"],["duration",{},"duration","PT1H"],["recurrence-id",{"tzid":"US/Eastern"},"date-time","2006-01-04T12:00:00"],["summary",{},"text","Event #2"],["uid",{},"text","12345"]],[]]]]',
167
+                'application/calendar+json',
168
+            ],
169
+            [
170
+                'https://foo.bar/bla2',
171
+                '<?xml version="1.0" encoding="utf-8" ?><icalendar xmlns="urn:ietf:params:xml:ns:icalendar-2.0"><vcalendar><properties><prodid><text>-//Example Inc.//Example Client//EN</text></prodid><version><text>2.0</text></version></properties><components><vevent><properties><dtstamp><date-time>2006-02-06T00:11:21Z</date-time></dtstamp><dtstart><parameters><tzid><text>US/Eastern</text></tzid></parameters><date-time>2006-01-04T14:00:00</date-time></dtstart><duration><duration>PT1H</duration></duration><recurrence-id><parameters><tzid><text>US/Eastern</text></tzid></parameters><date-time>2006-01-04T12:00:00</date-time></recurrence-id><summary><text>Event #2 bis</text></summary><uid><text>12345</text></uid></properties></vevent></components></vcalendar></icalendar>',
172
+                'application/calendar+xml',
173
+            ],
174
+        ];
175
+    }
176 176
 }
Please login to merge, or discard this patch.
dav/tests/unit/CalDAV/ResourceBooking/AbstractPrincipalBackendTestCase.php 1 patch
Indentation   +533 added lines, -533 removed lines patch added patch discarded remove patch
@@ -20,537 +20,537 @@
 block discarded – undo
20 20
 use Test\TestCase;
21 21
 
22 22
 abstract class AbstractPrincipalBackendTestCase extends TestCase {
23
-	protected ResourcePrincipalBackend|RoomPrincipalBackend $principalBackend;
24
-	protected IUserSession&MockObject $userSession;
25
-	protected IGroupManager&MockObject $groupManager;
26
-	protected LoggerInterface&MockObject $logger;
27
-	protected ProxyMapper&MockObject $proxyMapper;
28
-	protected string $mainDbTable;
29
-	protected string $metadataDbTable;
30
-	protected string $foreignKey;
31
-	protected string $principalPrefix;
32
-	protected string $expectedCUType;
33
-
34
-	protected function setUp(): void {
35
-		parent::setUp();
36
-
37
-		$this->userSession = $this->createMock(IUserSession::class);
38
-		$this->groupManager = $this->createMock(IGroupManager::class);
39
-		$this->logger = $this->createMock(LoggerInterface::class);
40
-		$this->proxyMapper = $this->createMock(ProxyMapper::class);
41
-	}
42
-
43
-	protected function tearDown(): void {
44
-		$query = self::$realDatabase->getQueryBuilder();
45
-
46
-		$query->delete('calendar_resources')->executeStatement();
47
-		$query->delete('calendar_resources_md')->executeStatement();
48
-		$query->delete('calendar_rooms')->executeStatement();
49
-		$query->delete('calendar_rooms_md')->executeStatement();
50
-	}
51
-
52
-	public function testGetPrincipalsByPrefix(): void {
53
-		$actual = $this->principalBackend->getPrincipalsByPrefix($this->principalPrefix);
54
-
55
-		$this->assertEquals([
56
-			[
57
-				'uri' => $this->principalPrefix . '/backend1-res1',
58
-				'{DAV:}displayname' => 'Beamer1',
59
-				'{http://sabredav.org/ns}email-address' => '[email protected]',
60
-				'{urn:ietf:params:xml:ns:caldav}calendar-user-type' => $this->expectedCUType,
61
-			],
62
-			[
63
-				'uri' => $this->principalPrefix . '/backend1-res2',
64
-				'{DAV:}displayname' => 'TV1',
65
-				'{http://sabredav.org/ns}email-address' => '[email protected]',
66
-				'{urn:ietf:params:xml:ns:caldav}calendar-user-type' => $this->expectedCUType,
67
-			],
68
-			[
69
-				'uri' => $this->principalPrefix . '/backend2-res3',
70
-				'{DAV:}displayname' => 'Beamer2',
71
-				'{http://sabredav.org/ns}email-address' => '[email protected]',
72
-				'{urn:ietf:params:xml:ns:caldav}calendar-user-type' => $this->expectedCUType,
73
-				'{http://nextcloud.com/ns}foo' => 'value1',
74
-				'{http://nextcloud.com/ns}meta2' => 'value2',
75
-			],
76
-			[
77
-				'uri' => $this->principalPrefix . '/backend2-res4',
78
-				'{DAV:}displayname' => 'TV2',
79
-				'{http://sabredav.org/ns}email-address' => '[email protected]',
80
-				'{urn:ietf:params:xml:ns:caldav}calendar-user-type' => $this->expectedCUType,
81
-				'{http://nextcloud.com/ns}meta1' => 'value1',
82
-				'{http://nextcloud.com/ns}meta3' => 'value3-old',
83
-			],
84
-			[
85
-				'uri' => $this->principalPrefix . '/backend3-res5',
86
-				'{DAV:}displayname' => 'Beamer3',
87
-				'{http://sabredav.org/ns}email-address' => '[email protected]',
88
-				'{urn:ietf:params:xml:ns:caldav}calendar-user-type' => $this->expectedCUType,
89
-			],
90
-			[
91
-				'uri' => $this->principalPrefix . '/backend3-res6',
92
-				'{DAV:}displayname' => 'Pointer',
93
-				'{http://sabredav.org/ns}email-address' => '[email protected]',
94
-				'{urn:ietf:params:xml:ns:caldav}calendar-user-type' => $this->expectedCUType,
95
-				'{http://nextcloud.com/ns}meta99' => 'value99'
96
-			]
97
-		], $actual);
98
-	}
99
-
100
-	public function testGetNoPrincipalsByPrefixForWrongPrincipalPrefix(): void {
101
-		$actual = $this->principalBackend->getPrincipalsByPrefix('principals/users');
102
-		$this->assertEquals([], $actual);
103
-	}
104
-
105
-	public function testGetPrincipalByPath(): void {
106
-		$actual = $this->principalBackend->getPrincipalByPath($this->principalPrefix . '/backend2-res3');
107
-		$this->assertEquals([
108
-			'uri' => $this->principalPrefix . '/backend2-res3',
109
-			'{DAV:}displayname' => 'Beamer2',
110
-			'{http://sabredav.org/ns}email-address' => '[email protected]',
111
-			'{urn:ietf:params:xml:ns:caldav}calendar-user-type' => $this->expectedCUType,
112
-			'{http://nextcloud.com/ns}foo' => 'value1',
113
-			'{http://nextcloud.com/ns}meta2' => 'value2',
114
-		], $actual);
115
-	}
116
-
117
-	public function testGetPrincipalByPathNotFound(): void {
118
-		$actual = $this->principalBackend->getPrincipalByPath($this->principalPrefix . '/db-123');
119
-		$this->assertEquals(null, $actual);
120
-	}
121
-
122
-	public function testGetPrincipalByPathWrongPrefix(): void {
123
-		$actual = $this->principalBackend->getPrincipalByPath('principals/users/foo-bar');
124
-		$this->assertEquals(null, $actual);
125
-	}
126
-
127
-	public function testGetGroupMemberSet(): void {
128
-		$actual = $this->principalBackend->getGroupMemberSet($this->principalPrefix . '/backend1-res1');
129
-		$this->assertEquals([], $actual);
130
-	}
131
-
132
-	public function testGetGroupMemberSetProxyRead(): void {
133
-		$proxy1 = new Proxy();
134
-		$proxy1->setProxyId('proxyId1');
135
-		$proxy1->setPermissions(1);
136
-
137
-		$proxy2 = new Proxy();
138
-		$proxy2->setProxyId('proxyId2');
139
-		$proxy2->setPermissions(3);
140
-
141
-		$proxy3 = new Proxy();
142
-		$proxy3->setProxyId('proxyId3');
143
-		$proxy3->setPermissions(3);
144
-
145
-		$this->proxyMapper->expects($this->once())
146
-			->method('getProxiesOf')
147
-			->with($this->principalPrefix . '/backend1-res1')
148
-			->willReturn([$proxy1, $proxy2, $proxy3]);
149
-
150
-		$actual = $this->principalBackend->getGroupMemberSet($this->principalPrefix . '/backend1-res1/calendar-proxy-read');
151
-		$this->assertEquals(['proxyId1'], $actual);
152
-	}
153
-
154
-	public function testGetGroupMemberSetProxyWrite(): void {
155
-		$proxy1 = new Proxy();
156
-		$proxy1->setProxyId('proxyId1');
157
-		$proxy1->setPermissions(1);
158
-
159
-		$proxy2 = new Proxy();
160
-		$proxy2->setProxyId('proxyId2');
161
-		$proxy2->setPermissions(3);
162
-
163
-		$proxy3 = new Proxy();
164
-		$proxy3->setProxyId('proxyId3');
165
-		$proxy3->setPermissions(3);
166
-
167
-		$this->proxyMapper->expects($this->once())
168
-			->method('getProxiesOf')
169
-			->with($this->principalPrefix . '/backend1-res1')
170
-			->willReturn([$proxy1, $proxy2, $proxy3]);
171
-
172
-		$actual = $this->principalBackend->getGroupMemberSet($this->principalPrefix . '/backend1-res1/calendar-proxy-write');
173
-		$this->assertEquals(['proxyId2', 'proxyId3'], $actual);
174
-	}
175
-
176
-	public function testGetGroupMembership(): void {
177
-		$proxy1 = new Proxy();
178
-		$proxy1->setOwnerId('proxyId1');
179
-		$proxy1->setPermissions(1);
180
-
181
-		$proxy2 = new Proxy();
182
-		$proxy2->setOwnerId('proxyId2');
183
-		$proxy2->setPermissions(3);
184
-
185
-		$this->proxyMapper->expects($this->once())
186
-			->method('getProxiesFor')
187
-			->with($this->principalPrefix . '/backend1-res1')
188
-			->willReturn([$proxy1, $proxy2]);
189
-
190
-		$actual = $this->principalBackend->getGroupMembership($this->principalPrefix . '/backend1-res1');
191
-
192
-		$this->assertEquals(['proxyId1/calendar-proxy-read', 'proxyId2/calendar-proxy-write'], $actual);
193
-	}
194
-
195
-	public function testSetGroupMemberSet(): void {
196
-		$this->proxyMapper->expects($this->once())
197
-			->method('getProxiesOf')
198
-			->with($this->principalPrefix . '/backend1-res1')
199
-			->willReturn([]);
200
-
201
-		$calls = [
202
-			function ($proxy) {
203
-				/** @var Proxy $proxy */
204
-				if ($proxy->getOwnerId() !== $this->principalPrefix . '/backend1-res1') {
205
-					return false;
206
-				}
207
-				if ($proxy->getProxyId() !== $this->principalPrefix . '/backend1-res2') {
208
-					return false;
209
-				}
210
-				if ($proxy->getPermissions() !== 3) {
211
-					return false;
212
-				}
213
-
214
-				return true;
215
-			},
216
-			function ($proxy) {
217
-				/** @var Proxy $proxy */
218
-				if ($proxy->getOwnerId() !== $this->principalPrefix . '/backend1-res1') {
219
-					return false;
220
-				}
221
-				if ($proxy->getProxyId() !== $this->principalPrefix . '/backend2-res3') {
222
-					return false;
223
-				}
224
-				if ($proxy->getPermissions() !== 3) {
225
-					return false;
226
-				}
227
-
228
-				return true;
229
-			}
230
-		];
231
-		$this->proxyMapper->expects($this->exactly(2))
232
-			->method('insert')
233
-			->willReturnCallback(function ($proxy) use (&$calls) {
234
-				$expected = array_shift($calls);
235
-				$this->assertTrue($expected($proxy));
236
-				return $proxy;
237
-			});
238
-
239
-		$this->principalBackend->setGroupMemberSet($this->principalPrefix . '/backend1-res1/calendar-proxy-write', [$this->principalPrefix . '/backend1-res2', $this->principalPrefix . '/backend2-res3']);
240
-	}
241
-
242
-	public function testUpdatePrincipal(): void {
243
-		$propPatch = $this->createMock(PropPatch::class);
244
-		$actual = $this->principalBackend->updatePrincipal($this->principalPrefix . '/foo-bar', $propPatch);
245
-
246
-		$this->assertEquals(0, $actual);
247
-	}
248
-
249
-	#[\PHPUnit\Framework\Attributes\DataProvider('dataSearchPrincipals')]
250
-	public function testSearchPrincipals($expected, $test): void {
251
-		$user = $this->createMock(IUser::class);
252
-		$this->userSession->expects($this->once())
253
-			->method('getUser')
254
-			->with()
255
-			->willReturn($user);
256
-		$this->groupManager->expects($this->once())
257
-			->method('getUserGroupIds')
258
-			->with($user)
259
-			->willReturn(['group1', 'group2']);
260
-
261
-		$actual = $this->principalBackend->searchPrincipals($this->principalPrefix, [
262
-			'{http://sabredav.org/ns}email-address' => 'foo',
263
-			'{DAV:}displayname' => 'Beamer',
264
-		], $test);
265
-
266
-		$this->assertEquals(
267
-			str_replace('%prefix%', $this->principalPrefix, $expected),
268
-			$actual);
269
-	}
270
-
271
-	public static function dataSearchPrincipals(): array {
272
-		// data providers are called before we subclass
273
-		// this class, $this->principalPrefix is null
274
-		// at that point, so we need this hack
275
-		return [
276
-			[[
277
-				'%prefix%/backend1-res1',
278
-				'%prefix%/backend2-res3',
279
-			], 'allof'],
280
-			[[
281
-				'%prefix%/backend1-res1',
282
-				'%prefix%/backend1-res2',
283
-				'%prefix%/backend2-res3',
284
-				'%prefix%/backend2-res4',
285
-				'%prefix%/backend3-res6',
286
-			], 'anyof'],
287
-		];
288
-	}
289
-
290
-	public function testSearchPrincipalsByMetadataKey(): void {
291
-		$user = $this->createMock(IUser::class);
292
-		$this->userSession->expects($this->once())
293
-			->method('getUser')
294
-			->with()
295
-			->willReturn($user);
296
-		$this->groupManager->expects($this->once())
297
-			->method('getUserGroupIds')
298
-			->with($user)
299
-			->willReturn(['group1', 'group2']);
300
-
301
-		$actual = $this->principalBackend->searchPrincipals($this->principalPrefix, [
302
-			'{http://nextcloud.com/ns}meta3' => 'value',
303
-		]);
304
-
305
-		$this->assertEquals([
306
-			$this->principalPrefix . '/backend2-res4',
307
-		], $actual);
308
-	}
309
-
310
-	public function testSearchPrincipalsByCalendarUserAddressSet(): void {
311
-		$user = $this->createMock(IUser::class);
312
-		$this->userSession->method('getUser')
313
-			->with()
314
-			->willReturn($user);
315
-		$this->groupManager->method('getUserGroupIds')
316
-			->with($user)
317
-			->willReturn(['group1', 'group2']);
318
-
319
-		$actual = $this->principalBackend->searchPrincipals($this->principalPrefix, [
320
-			'{urn:ietf:params:xml:ns:caldav}calendar-user-address-set' => '[email protected]',
321
-		]);
322
-
323
-		$this->assertEquals(
324
-			str_replace('%prefix%', $this->principalPrefix, [
325
-				'%prefix%/backend1-res2',
326
-			]),
327
-			$actual);
328
-	}
329
-
330
-	public function testSearchPrincipalsEmptySearchProperties(): void {
331
-		$this->userSession->expects($this->never())
332
-			->method('getUser');
333
-		$this->groupManager->expects($this->never())
334
-			->method('getUserGroupIds');
335
-
336
-		$this->principalBackend->searchPrincipals($this->principalPrefix, []);
337
-	}
338
-
339
-	public function testSearchPrincipalsWrongPrincipalPrefix(): void {
340
-		$this->userSession->expects($this->never())
341
-			->method('getUser');
342
-		$this->groupManager->expects($this->never())
343
-			->method('getUserGroupIds');
344
-
345
-		$this->principalBackend->searchPrincipals('principals/users', [
346
-			'{http://sabredav.org/ns}email-address' => 'foo'
347
-		]);
348
-	}
349
-
350
-	public function testFindByUriByEmail(): void {
351
-		$user = $this->createMock(IUser::class);
352
-		$this->userSession->expects($this->once())
353
-			->method('getUser')
354
-			->with()
355
-			->willReturn($user);
356
-		$this->groupManager->expects($this->once())
357
-			->method('getUserGroupIds')
358
-			->with($user)
359
-			->willReturn(['group1', 'group2']);
360
-
361
-		$actual = $this->principalBackend->findByUri('mailto:[email protected]', $this->principalPrefix);
362
-		$this->assertEquals($this->principalPrefix . '/backend1-res1', $actual);
363
-	}
364
-
365
-	public function testFindByUriByEmailForbiddenResource(): void {
366
-		$user = $this->createMock(IUser::class);
367
-		$this->userSession->expects($this->once())
368
-			->method('getUser')
369
-			->with()
370
-			->willReturn($user);
371
-		$this->groupManager->expects($this->once())
372
-			->method('getUserGroupIds')
373
-			->with($user)
374
-			->willReturn(['group1', 'group2']);
375
-
376
-		$actual = $this->principalBackend->findByUri('mailto:[email protected]', $this->principalPrefix);
377
-		$this->assertEquals(null, $actual);
378
-	}
379
-
380
-	public function testFindByUriByEmailNotFound(): void {
381
-		$user = $this->createMock(IUser::class);
382
-		$this->userSession->expects($this->once())
383
-			->method('getUser')
384
-			->with()
385
-			->willReturn($user);
386
-		$this->groupManager->expects($this->once())
387
-			->method('getUserGroupIds')
388
-			->with($user)
389
-			->willReturn(['group1', 'group2']);
390
-
391
-		$actual = $this->principalBackend->findByUri('mailto:[email protected]', $this->principalPrefix);
392
-		$this->assertEquals(null, $actual);
393
-	}
394
-
395
-	public function testFindByUriByPrincipal(): void {
396
-		$user = $this->createMock(IUser::class);
397
-		$this->userSession->expects($this->once())
398
-			->method('getUser')
399
-			->with()
400
-			->willReturn($user);
401
-		$this->groupManager->expects($this->once())
402
-			->method('getUserGroupIds')
403
-			->with($user)
404
-			->willReturn(['group1', 'group2']);
405
-
406
-		$actual = $this->principalBackend->findByUri('mailto:[email protected]', $this->principalPrefix);
407
-		$this->assertEquals($this->principalPrefix . '/backend3-res6', $actual);
408
-	}
409
-
410
-	public function testFindByUriByPrincipalForbiddenResource(): void {
411
-		$user = $this->createMock(IUser::class);
412
-		$this->userSession->expects($this->once())
413
-			->method('getUser')
414
-			->with()
415
-			->willReturn($user);
416
-		$this->groupManager->expects($this->once())
417
-			->method('getUserGroupIds')
418
-			->with($user)
419
-			->willReturn(['group1', 'group2']);
420
-
421
-		$actual = $this->principalBackend->findByUri('principal:' . $this->principalPrefix . '/backend3-res5', $this->principalPrefix);
422
-		$this->assertEquals(null, $actual);
423
-	}
424
-
425
-	public function testFindByUriByPrincipalNotFound(): void {
426
-		$user = $this->createMock(IUser::class);
427
-		$this->userSession->expects($this->once())
428
-			->method('getUser')
429
-			->with()
430
-			->willReturn($user);
431
-		$this->groupManager->expects($this->once())
432
-			->method('getUserGroupIds')
433
-			->with($user)
434
-			->willReturn(['group1', 'group2']);
435
-
436
-		$actual = $this->principalBackend->findByUri('principal:' . $this->principalPrefix . '/db-123', $this->principalPrefix);
437
-		$this->assertEquals(null, $actual);
438
-	}
439
-
440
-	public function testFindByUriByUnknownUri(): void {
441
-		$user = $this->createMock(IUser::class);
442
-		$this->userSession->expects($this->once())
443
-			->method('getUser')
444
-			->with()
445
-			->willReturn($user);
446
-		$this->groupManager->expects($this->once())
447
-			->method('getUserGroupIds')
448
-			->with($user)
449
-			->willReturn(['group1', 'group2']);
450
-
451
-		$actual = $this->principalBackend->findByUri('foobar:blub', $this->principalPrefix);
452
-		$this->assertEquals(null, $actual);
453
-	}
454
-
455
-	protected function createTestDatasetInDb() {
456
-		$query = self::$realDatabase->getQueryBuilder();
457
-		$query->insert($this->mainDbTable)
458
-			->values([
459
-				'backend_id' => $query->createNamedParameter('backend1'),
460
-				'resource_id' => $query->createNamedParameter('res1'),
461
-				'email' => $query->createNamedParameter('[email protected]'),
462
-				'displayname' => $query->createNamedParameter('Beamer1'),
463
-				'group_restrictions' => $query->createNamedParameter('[]'),
464
-			])
465
-			->execute();
466
-
467
-		$query->insert($this->mainDbTable)
468
-			->values([
469
-				'backend_id' => $query->createNamedParameter('backend1'),
470
-				'resource_id' => $query->createNamedParameter('res2'),
471
-				'email' => $query->createNamedParameter('[email protected]'),
472
-				'displayname' => $query->createNamedParameter('TV1'),
473
-				'group_restrictions' => $query->createNamedParameter('[]'),
474
-			])
475
-			->execute();
476
-
477
-		$query->insert($this->mainDbTable)
478
-			->values([
479
-				'backend_id' => $query->createNamedParameter('backend2'),
480
-				'resource_id' => $query->createNamedParameter('res3'),
481
-				'email' => $query->createNamedParameter('[email protected]'),
482
-				'displayname' => $query->createNamedParameter('Beamer2'),
483
-				'group_restrictions' => $query->createNamedParameter('[]'),
484
-			])
485
-			->execute();
486
-		$id3 = $query->getLastInsertId();
487
-
488
-		$query->insert($this->mainDbTable)
489
-			->values([
490
-				'backend_id' => $query->createNamedParameter('backend2'),
491
-				'resource_id' => $query->createNamedParameter('res4'),
492
-				'email' => $query->createNamedParameter('[email protected]'),
493
-				'displayname' => $query->createNamedParameter('TV2'),
494
-				'group_restrictions' => $query->createNamedParameter('[]'),
495
-			])
496
-			->execute();
497
-		$id4 = $query->getLastInsertId();
498
-
499
-		$query->insert($this->mainDbTable)
500
-			->values([
501
-				'backend_id' => $query->createNamedParameter('backend3'),
502
-				'resource_id' => $query->createNamedParameter('res5'),
503
-				'email' => $query->createNamedParameter('[email protected]'),
504
-				'displayname' => $query->createNamedParameter('Beamer3'),
505
-				'group_restrictions' => $query->createNamedParameter('["foo", "bar"]'),
506
-			])
507
-			->execute();
508
-
509
-		$query->insert($this->mainDbTable)
510
-			->values([
511
-				'backend_id' => $query->createNamedParameter('backend3'),
512
-				'resource_id' => $query->createNamedParameter('res6'),
513
-				'email' => $query->createNamedParameter('[email protected]'),
514
-				'displayname' => $query->createNamedParameter('Pointer'),
515
-				'group_restrictions' => $query->createNamedParameter('["group1", "bar"]'),
516
-			])
517
-			->execute();
518
-		$id6 = $query->getLastInsertId();
519
-
520
-		$query->insert($this->metadataDbTable)
521
-			->values([
522
-				$this->foreignKey => $query->createNamedParameter($id3),
523
-				'key' => $query->createNamedParameter('{http://nextcloud.com/ns}foo'),
524
-				'value' => $query->createNamedParameter('value1')
525
-			])
526
-			->execute();
527
-		$query->insert($this->metadataDbTable)
528
-			->values([
529
-				$this->foreignKey => $query->createNamedParameter($id3),
530
-				'key' => $query->createNamedParameter('{http://nextcloud.com/ns}meta2'),
531
-				'value' => $query->createNamedParameter('value2')
532
-			])
533
-			->execute();
534
-		$query->insert($this->metadataDbTable)
535
-			->values([
536
-				$this->foreignKey => $query->createNamedParameter($id4),
537
-				'key' => $query->createNamedParameter('{http://nextcloud.com/ns}meta1'),
538
-				'value' => $query->createNamedParameter('value1')
539
-			])
540
-			->execute();
541
-		$query->insert($this->metadataDbTable)
542
-			->values([
543
-				$this->foreignKey => $query->createNamedParameter($id4),
544
-				'key' => $query->createNamedParameter('{http://nextcloud.com/ns}meta3'),
545
-				'value' => $query->createNamedParameter('value3-old')
546
-			])
547
-			->execute();
548
-		$query->insert($this->metadataDbTable)
549
-			->values([
550
-				$this->foreignKey => $query->createNamedParameter($id6),
551
-				'key' => $query->createNamedParameter('{http://nextcloud.com/ns}meta99'),
552
-				'value' => $query->createNamedParameter('value99')
553
-			])
554
-			->execute();
555
-	}
23
+    protected ResourcePrincipalBackend|RoomPrincipalBackend $principalBackend;
24
+    protected IUserSession&MockObject $userSession;
25
+    protected IGroupManager&MockObject $groupManager;
26
+    protected LoggerInterface&MockObject $logger;
27
+    protected ProxyMapper&MockObject $proxyMapper;
28
+    protected string $mainDbTable;
29
+    protected string $metadataDbTable;
30
+    protected string $foreignKey;
31
+    protected string $principalPrefix;
32
+    protected string $expectedCUType;
33
+
34
+    protected function setUp(): void {
35
+        parent::setUp();
36
+
37
+        $this->userSession = $this->createMock(IUserSession::class);
38
+        $this->groupManager = $this->createMock(IGroupManager::class);
39
+        $this->logger = $this->createMock(LoggerInterface::class);
40
+        $this->proxyMapper = $this->createMock(ProxyMapper::class);
41
+    }
42
+
43
+    protected function tearDown(): void {
44
+        $query = self::$realDatabase->getQueryBuilder();
45
+
46
+        $query->delete('calendar_resources')->executeStatement();
47
+        $query->delete('calendar_resources_md')->executeStatement();
48
+        $query->delete('calendar_rooms')->executeStatement();
49
+        $query->delete('calendar_rooms_md')->executeStatement();
50
+    }
51
+
52
+    public function testGetPrincipalsByPrefix(): void {
53
+        $actual = $this->principalBackend->getPrincipalsByPrefix($this->principalPrefix);
54
+
55
+        $this->assertEquals([
56
+            [
57
+                'uri' => $this->principalPrefix . '/backend1-res1',
58
+                '{DAV:}displayname' => 'Beamer1',
59
+                '{http://sabredav.org/ns}email-address' => '[email protected]',
60
+                '{urn:ietf:params:xml:ns:caldav}calendar-user-type' => $this->expectedCUType,
61
+            ],
62
+            [
63
+                'uri' => $this->principalPrefix . '/backend1-res2',
64
+                '{DAV:}displayname' => 'TV1',
65
+                '{http://sabredav.org/ns}email-address' => '[email protected]',
66
+                '{urn:ietf:params:xml:ns:caldav}calendar-user-type' => $this->expectedCUType,
67
+            ],
68
+            [
69
+                'uri' => $this->principalPrefix . '/backend2-res3',
70
+                '{DAV:}displayname' => 'Beamer2',
71
+                '{http://sabredav.org/ns}email-address' => '[email protected]',
72
+                '{urn:ietf:params:xml:ns:caldav}calendar-user-type' => $this->expectedCUType,
73
+                '{http://nextcloud.com/ns}foo' => 'value1',
74
+                '{http://nextcloud.com/ns}meta2' => 'value2',
75
+            ],
76
+            [
77
+                'uri' => $this->principalPrefix . '/backend2-res4',
78
+                '{DAV:}displayname' => 'TV2',
79
+                '{http://sabredav.org/ns}email-address' => '[email protected]',
80
+                '{urn:ietf:params:xml:ns:caldav}calendar-user-type' => $this->expectedCUType,
81
+                '{http://nextcloud.com/ns}meta1' => 'value1',
82
+                '{http://nextcloud.com/ns}meta3' => 'value3-old',
83
+            ],
84
+            [
85
+                'uri' => $this->principalPrefix . '/backend3-res5',
86
+                '{DAV:}displayname' => 'Beamer3',
87
+                '{http://sabredav.org/ns}email-address' => '[email protected]',
88
+                '{urn:ietf:params:xml:ns:caldav}calendar-user-type' => $this->expectedCUType,
89
+            ],
90
+            [
91
+                'uri' => $this->principalPrefix . '/backend3-res6',
92
+                '{DAV:}displayname' => 'Pointer',
93
+                '{http://sabredav.org/ns}email-address' => '[email protected]',
94
+                '{urn:ietf:params:xml:ns:caldav}calendar-user-type' => $this->expectedCUType,
95
+                '{http://nextcloud.com/ns}meta99' => 'value99'
96
+            ]
97
+        ], $actual);
98
+    }
99
+
100
+    public function testGetNoPrincipalsByPrefixForWrongPrincipalPrefix(): void {
101
+        $actual = $this->principalBackend->getPrincipalsByPrefix('principals/users');
102
+        $this->assertEquals([], $actual);
103
+    }
104
+
105
+    public function testGetPrincipalByPath(): void {
106
+        $actual = $this->principalBackend->getPrincipalByPath($this->principalPrefix . '/backend2-res3');
107
+        $this->assertEquals([
108
+            'uri' => $this->principalPrefix . '/backend2-res3',
109
+            '{DAV:}displayname' => 'Beamer2',
110
+            '{http://sabredav.org/ns}email-address' => '[email protected]',
111
+            '{urn:ietf:params:xml:ns:caldav}calendar-user-type' => $this->expectedCUType,
112
+            '{http://nextcloud.com/ns}foo' => 'value1',
113
+            '{http://nextcloud.com/ns}meta2' => 'value2',
114
+        ], $actual);
115
+    }
116
+
117
+    public function testGetPrincipalByPathNotFound(): void {
118
+        $actual = $this->principalBackend->getPrincipalByPath($this->principalPrefix . '/db-123');
119
+        $this->assertEquals(null, $actual);
120
+    }
121
+
122
+    public function testGetPrincipalByPathWrongPrefix(): void {
123
+        $actual = $this->principalBackend->getPrincipalByPath('principals/users/foo-bar');
124
+        $this->assertEquals(null, $actual);
125
+    }
126
+
127
+    public function testGetGroupMemberSet(): void {
128
+        $actual = $this->principalBackend->getGroupMemberSet($this->principalPrefix . '/backend1-res1');
129
+        $this->assertEquals([], $actual);
130
+    }
131
+
132
+    public function testGetGroupMemberSetProxyRead(): void {
133
+        $proxy1 = new Proxy();
134
+        $proxy1->setProxyId('proxyId1');
135
+        $proxy1->setPermissions(1);
136
+
137
+        $proxy2 = new Proxy();
138
+        $proxy2->setProxyId('proxyId2');
139
+        $proxy2->setPermissions(3);
140
+
141
+        $proxy3 = new Proxy();
142
+        $proxy3->setProxyId('proxyId3');
143
+        $proxy3->setPermissions(3);
144
+
145
+        $this->proxyMapper->expects($this->once())
146
+            ->method('getProxiesOf')
147
+            ->with($this->principalPrefix . '/backend1-res1')
148
+            ->willReturn([$proxy1, $proxy2, $proxy3]);
149
+
150
+        $actual = $this->principalBackend->getGroupMemberSet($this->principalPrefix . '/backend1-res1/calendar-proxy-read');
151
+        $this->assertEquals(['proxyId1'], $actual);
152
+    }
153
+
154
+    public function testGetGroupMemberSetProxyWrite(): void {
155
+        $proxy1 = new Proxy();
156
+        $proxy1->setProxyId('proxyId1');
157
+        $proxy1->setPermissions(1);
158
+
159
+        $proxy2 = new Proxy();
160
+        $proxy2->setProxyId('proxyId2');
161
+        $proxy2->setPermissions(3);
162
+
163
+        $proxy3 = new Proxy();
164
+        $proxy3->setProxyId('proxyId3');
165
+        $proxy3->setPermissions(3);
166
+
167
+        $this->proxyMapper->expects($this->once())
168
+            ->method('getProxiesOf')
169
+            ->with($this->principalPrefix . '/backend1-res1')
170
+            ->willReturn([$proxy1, $proxy2, $proxy3]);
171
+
172
+        $actual = $this->principalBackend->getGroupMemberSet($this->principalPrefix . '/backend1-res1/calendar-proxy-write');
173
+        $this->assertEquals(['proxyId2', 'proxyId3'], $actual);
174
+    }
175
+
176
+    public function testGetGroupMembership(): void {
177
+        $proxy1 = new Proxy();
178
+        $proxy1->setOwnerId('proxyId1');
179
+        $proxy1->setPermissions(1);
180
+
181
+        $proxy2 = new Proxy();
182
+        $proxy2->setOwnerId('proxyId2');
183
+        $proxy2->setPermissions(3);
184
+
185
+        $this->proxyMapper->expects($this->once())
186
+            ->method('getProxiesFor')
187
+            ->with($this->principalPrefix . '/backend1-res1')
188
+            ->willReturn([$proxy1, $proxy2]);
189
+
190
+        $actual = $this->principalBackend->getGroupMembership($this->principalPrefix . '/backend1-res1');
191
+
192
+        $this->assertEquals(['proxyId1/calendar-proxy-read', 'proxyId2/calendar-proxy-write'], $actual);
193
+    }
194
+
195
+    public function testSetGroupMemberSet(): void {
196
+        $this->proxyMapper->expects($this->once())
197
+            ->method('getProxiesOf')
198
+            ->with($this->principalPrefix . '/backend1-res1')
199
+            ->willReturn([]);
200
+
201
+        $calls = [
202
+            function ($proxy) {
203
+                /** @var Proxy $proxy */
204
+                if ($proxy->getOwnerId() !== $this->principalPrefix . '/backend1-res1') {
205
+                    return false;
206
+                }
207
+                if ($proxy->getProxyId() !== $this->principalPrefix . '/backend1-res2') {
208
+                    return false;
209
+                }
210
+                if ($proxy->getPermissions() !== 3) {
211
+                    return false;
212
+                }
213
+
214
+                return true;
215
+            },
216
+            function ($proxy) {
217
+                /** @var Proxy $proxy */
218
+                if ($proxy->getOwnerId() !== $this->principalPrefix . '/backend1-res1') {
219
+                    return false;
220
+                }
221
+                if ($proxy->getProxyId() !== $this->principalPrefix . '/backend2-res3') {
222
+                    return false;
223
+                }
224
+                if ($proxy->getPermissions() !== 3) {
225
+                    return false;
226
+                }
227
+
228
+                return true;
229
+            }
230
+        ];
231
+        $this->proxyMapper->expects($this->exactly(2))
232
+            ->method('insert')
233
+            ->willReturnCallback(function ($proxy) use (&$calls) {
234
+                $expected = array_shift($calls);
235
+                $this->assertTrue($expected($proxy));
236
+                return $proxy;
237
+            });
238
+
239
+        $this->principalBackend->setGroupMemberSet($this->principalPrefix . '/backend1-res1/calendar-proxy-write', [$this->principalPrefix . '/backend1-res2', $this->principalPrefix . '/backend2-res3']);
240
+    }
241
+
242
+    public function testUpdatePrincipal(): void {
243
+        $propPatch = $this->createMock(PropPatch::class);
244
+        $actual = $this->principalBackend->updatePrincipal($this->principalPrefix . '/foo-bar', $propPatch);
245
+
246
+        $this->assertEquals(0, $actual);
247
+    }
248
+
249
+    #[\PHPUnit\Framework\Attributes\DataProvider('dataSearchPrincipals')]
250
+    public function testSearchPrincipals($expected, $test): void {
251
+        $user = $this->createMock(IUser::class);
252
+        $this->userSession->expects($this->once())
253
+            ->method('getUser')
254
+            ->with()
255
+            ->willReturn($user);
256
+        $this->groupManager->expects($this->once())
257
+            ->method('getUserGroupIds')
258
+            ->with($user)
259
+            ->willReturn(['group1', 'group2']);
260
+
261
+        $actual = $this->principalBackend->searchPrincipals($this->principalPrefix, [
262
+            '{http://sabredav.org/ns}email-address' => 'foo',
263
+            '{DAV:}displayname' => 'Beamer',
264
+        ], $test);
265
+
266
+        $this->assertEquals(
267
+            str_replace('%prefix%', $this->principalPrefix, $expected),
268
+            $actual);
269
+    }
270
+
271
+    public static function dataSearchPrincipals(): array {
272
+        // data providers are called before we subclass
273
+        // this class, $this->principalPrefix is null
274
+        // at that point, so we need this hack
275
+        return [
276
+            [[
277
+                '%prefix%/backend1-res1',
278
+                '%prefix%/backend2-res3',
279
+            ], 'allof'],
280
+            [[
281
+                '%prefix%/backend1-res1',
282
+                '%prefix%/backend1-res2',
283
+                '%prefix%/backend2-res3',
284
+                '%prefix%/backend2-res4',
285
+                '%prefix%/backend3-res6',
286
+            ], 'anyof'],
287
+        ];
288
+    }
289
+
290
+    public function testSearchPrincipalsByMetadataKey(): void {
291
+        $user = $this->createMock(IUser::class);
292
+        $this->userSession->expects($this->once())
293
+            ->method('getUser')
294
+            ->with()
295
+            ->willReturn($user);
296
+        $this->groupManager->expects($this->once())
297
+            ->method('getUserGroupIds')
298
+            ->with($user)
299
+            ->willReturn(['group1', 'group2']);
300
+
301
+        $actual = $this->principalBackend->searchPrincipals($this->principalPrefix, [
302
+            '{http://nextcloud.com/ns}meta3' => 'value',
303
+        ]);
304
+
305
+        $this->assertEquals([
306
+            $this->principalPrefix . '/backend2-res4',
307
+        ], $actual);
308
+    }
309
+
310
+    public function testSearchPrincipalsByCalendarUserAddressSet(): void {
311
+        $user = $this->createMock(IUser::class);
312
+        $this->userSession->method('getUser')
313
+            ->with()
314
+            ->willReturn($user);
315
+        $this->groupManager->method('getUserGroupIds')
316
+            ->with($user)
317
+            ->willReturn(['group1', 'group2']);
318
+
319
+        $actual = $this->principalBackend->searchPrincipals($this->principalPrefix, [
320
+            '{urn:ietf:params:xml:ns:caldav}calendar-user-address-set' => '[email protected]',
321
+        ]);
322
+
323
+        $this->assertEquals(
324
+            str_replace('%prefix%', $this->principalPrefix, [
325
+                '%prefix%/backend1-res2',
326
+            ]),
327
+            $actual);
328
+    }
329
+
330
+    public function testSearchPrincipalsEmptySearchProperties(): void {
331
+        $this->userSession->expects($this->never())
332
+            ->method('getUser');
333
+        $this->groupManager->expects($this->never())
334
+            ->method('getUserGroupIds');
335
+
336
+        $this->principalBackend->searchPrincipals($this->principalPrefix, []);
337
+    }
338
+
339
+    public function testSearchPrincipalsWrongPrincipalPrefix(): void {
340
+        $this->userSession->expects($this->never())
341
+            ->method('getUser');
342
+        $this->groupManager->expects($this->never())
343
+            ->method('getUserGroupIds');
344
+
345
+        $this->principalBackend->searchPrincipals('principals/users', [
346
+            '{http://sabredav.org/ns}email-address' => 'foo'
347
+        ]);
348
+    }
349
+
350
+    public function testFindByUriByEmail(): void {
351
+        $user = $this->createMock(IUser::class);
352
+        $this->userSession->expects($this->once())
353
+            ->method('getUser')
354
+            ->with()
355
+            ->willReturn($user);
356
+        $this->groupManager->expects($this->once())
357
+            ->method('getUserGroupIds')
358
+            ->with($user)
359
+            ->willReturn(['group1', 'group2']);
360
+
361
+        $actual = $this->principalBackend->findByUri('mailto:[email protected]', $this->principalPrefix);
362
+        $this->assertEquals($this->principalPrefix . '/backend1-res1', $actual);
363
+    }
364
+
365
+    public function testFindByUriByEmailForbiddenResource(): void {
366
+        $user = $this->createMock(IUser::class);
367
+        $this->userSession->expects($this->once())
368
+            ->method('getUser')
369
+            ->with()
370
+            ->willReturn($user);
371
+        $this->groupManager->expects($this->once())
372
+            ->method('getUserGroupIds')
373
+            ->with($user)
374
+            ->willReturn(['group1', 'group2']);
375
+
376
+        $actual = $this->principalBackend->findByUri('mailto:[email protected]', $this->principalPrefix);
377
+        $this->assertEquals(null, $actual);
378
+    }
379
+
380
+    public function testFindByUriByEmailNotFound(): void {
381
+        $user = $this->createMock(IUser::class);
382
+        $this->userSession->expects($this->once())
383
+            ->method('getUser')
384
+            ->with()
385
+            ->willReturn($user);
386
+        $this->groupManager->expects($this->once())
387
+            ->method('getUserGroupIds')
388
+            ->with($user)
389
+            ->willReturn(['group1', 'group2']);
390
+
391
+        $actual = $this->principalBackend->findByUri('mailto:[email protected]', $this->principalPrefix);
392
+        $this->assertEquals(null, $actual);
393
+    }
394
+
395
+    public function testFindByUriByPrincipal(): void {
396
+        $user = $this->createMock(IUser::class);
397
+        $this->userSession->expects($this->once())
398
+            ->method('getUser')
399
+            ->with()
400
+            ->willReturn($user);
401
+        $this->groupManager->expects($this->once())
402
+            ->method('getUserGroupIds')
403
+            ->with($user)
404
+            ->willReturn(['group1', 'group2']);
405
+
406
+        $actual = $this->principalBackend->findByUri('mailto:[email protected]', $this->principalPrefix);
407
+        $this->assertEquals($this->principalPrefix . '/backend3-res6', $actual);
408
+    }
409
+
410
+    public function testFindByUriByPrincipalForbiddenResource(): void {
411
+        $user = $this->createMock(IUser::class);
412
+        $this->userSession->expects($this->once())
413
+            ->method('getUser')
414
+            ->with()
415
+            ->willReturn($user);
416
+        $this->groupManager->expects($this->once())
417
+            ->method('getUserGroupIds')
418
+            ->with($user)
419
+            ->willReturn(['group1', 'group2']);
420
+
421
+        $actual = $this->principalBackend->findByUri('principal:' . $this->principalPrefix . '/backend3-res5', $this->principalPrefix);
422
+        $this->assertEquals(null, $actual);
423
+    }
424
+
425
+    public function testFindByUriByPrincipalNotFound(): void {
426
+        $user = $this->createMock(IUser::class);
427
+        $this->userSession->expects($this->once())
428
+            ->method('getUser')
429
+            ->with()
430
+            ->willReturn($user);
431
+        $this->groupManager->expects($this->once())
432
+            ->method('getUserGroupIds')
433
+            ->with($user)
434
+            ->willReturn(['group1', 'group2']);
435
+
436
+        $actual = $this->principalBackend->findByUri('principal:' . $this->principalPrefix . '/db-123', $this->principalPrefix);
437
+        $this->assertEquals(null, $actual);
438
+    }
439
+
440
+    public function testFindByUriByUnknownUri(): void {
441
+        $user = $this->createMock(IUser::class);
442
+        $this->userSession->expects($this->once())
443
+            ->method('getUser')
444
+            ->with()
445
+            ->willReturn($user);
446
+        $this->groupManager->expects($this->once())
447
+            ->method('getUserGroupIds')
448
+            ->with($user)
449
+            ->willReturn(['group1', 'group2']);
450
+
451
+        $actual = $this->principalBackend->findByUri('foobar:blub', $this->principalPrefix);
452
+        $this->assertEquals(null, $actual);
453
+    }
454
+
455
+    protected function createTestDatasetInDb() {
456
+        $query = self::$realDatabase->getQueryBuilder();
457
+        $query->insert($this->mainDbTable)
458
+            ->values([
459
+                'backend_id' => $query->createNamedParameter('backend1'),
460
+                'resource_id' => $query->createNamedParameter('res1'),
461
+                'email' => $query->createNamedParameter('[email protected]'),
462
+                'displayname' => $query->createNamedParameter('Beamer1'),
463
+                'group_restrictions' => $query->createNamedParameter('[]'),
464
+            ])
465
+            ->execute();
466
+
467
+        $query->insert($this->mainDbTable)
468
+            ->values([
469
+                'backend_id' => $query->createNamedParameter('backend1'),
470
+                'resource_id' => $query->createNamedParameter('res2'),
471
+                'email' => $query->createNamedParameter('[email protected]'),
472
+                'displayname' => $query->createNamedParameter('TV1'),
473
+                'group_restrictions' => $query->createNamedParameter('[]'),
474
+            ])
475
+            ->execute();
476
+
477
+        $query->insert($this->mainDbTable)
478
+            ->values([
479
+                'backend_id' => $query->createNamedParameter('backend2'),
480
+                'resource_id' => $query->createNamedParameter('res3'),
481
+                'email' => $query->createNamedParameter('[email protected]'),
482
+                'displayname' => $query->createNamedParameter('Beamer2'),
483
+                'group_restrictions' => $query->createNamedParameter('[]'),
484
+            ])
485
+            ->execute();
486
+        $id3 = $query->getLastInsertId();
487
+
488
+        $query->insert($this->mainDbTable)
489
+            ->values([
490
+                'backend_id' => $query->createNamedParameter('backend2'),
491
+                'resource_id' => $query->createNamedParameter('res4'),
492
+                'email' => $query->createNamedParameter('[email protected]'),
493
+                'displayname' => $query->createNamedParameter('TV2'),
494
+                'group_restrictions' => $query->createNamedParameter('[]'),
495
+            ])
496
+            ->execute();
497
+        $id4 = $query->getLastInsertId();
498
+
499
+        $query->insert($this->mainDbTable)
500
+            ->values([
501
+                'backend_id' => $query->createNamedParameter('backend3'),
502
+                'resource_id' => $query->createNamedParameter('res5'),
503
+                'email' => $query->createNamedParameter('[email protected]'),
504
+                'displayname' => $query->createNamedParameter('Beamer3'),
505
+                'group_restrictions' => $query->createNamedParameter('["foo", "bar"]'),
506
+            ])
507
+            ->execute();
508
+
509
+        $query->insert($this->mainDbTable)
510
+            ->values([
511
+                'backend_id' => $query->createNamedParameter('backend3'),
512
+                'resource_id' => $query->createNamedParameter('res6'),
513
+                'email' => $query->createNamedParameter('[email protected]'),
514
+                'displayname' => $query->createNamedParameter('Pointer'),
515
+                'group_restrictions' => $query->createNamedParameter('["group1", "bar"]'),
516
+            ])
517
+            ->execute();
518
+        $id6 = $query->getLastInsertId();
519
+
520
+        $query->insert($this->metadataDbTable)
521
+            ->values([
522
+                $this->foreignKey => $query->createNamedParameter($id3),
523
+                'key' => $query->createNamedParameter('{http://nextcloud.com/ns}foo'),
524
+                'value' => $query->createNamedParameter('value1')
525
+            ])
526
+            ->execute();
527
+        $query->insert($this->metadataDbTable)
528
+            ->values([
529
+                $this->foreignKey => $query->createNamedParameter($id3),
530
+                'key' => $query->createNamedParameter('{http://nextcloud.com/ns}meta2'),
531
+                'value' => $query->createNamedParameter('value2')
532
+            ])
533
+            ->execute();
534
+        $query->insert($this->metadataDbTable)
535
+            ->values([
536
+                $this->foreignKey => $query->createNamedParameter($id4),
537
+                'key' => $query->createNamedParameter('{http://nextcloud.com/ns}meta1'),
538
+                'value' => $query->createNamedParameter('value1')
539
+            ])
540
+            ->execute();
541
+        $query->insert($this->metadataDbTable)
542
+            ->values([
543
+                $this->foreignKey => $query->createNamedParameter($id4),
544
+                'key' => $query->createNamedParameter('{http://nextcloud.com/ns}meta3'),
545
+                'value' => $query->createNamedParameter('value3-old')
546
+            ])
547
+            ->execute();
548
+        $query->insert($this->metadataDbTable)
549
+            ->values([
550
+                $this->foreignKey => $query->createNamedParameter($id6),
551
+                'key' => $query->createNamedParameter('{http://nextcloud.com/ns}meta99'),
552
+                'value' => $query->createNamedParameter('value99')
553
+            ])
554
+            ->execute();
555
+    }
556 556
 }
Please login to merge, or discard this patch.