Completed
Push — master ( 158b3e...c62fa5 )
by Joas
29:53 queued 14s
created
tests/lib/Files/Cache/Wrapper/CachePermissionsMaskTest.php 1 patch
Indentation   +68 added lines, -68 removed lines patch added patch discarded remove patch
@@ -18,83 +18,83 @@
 block discarded – undo
18 18
  * @package Test\Files\Cache\Wrapper
19 19
  */
20 20
 class CachePermissionsMaskTest extends CacheTest {
21
-	/**
22
-	 * @var \OC\Files\Cache\Cache $sourceCache
23
-	 */
24
-	protected $sourceCache;
21
+    /**
22
+     * @var \OC\Files\Cache\Cache $sourceCache
23
+     */
24
+    protected $sourceCache;
25 25
 
26
-	protected function setUp(): void {
27
-		parent::setUp();
28
-		$this->storage->mkdir('foo');
29
-		$this->sourceCache = $this->cache;
30
-		$this->cache = $this->getMaskedCached(Constants::PERMISSION_ALL);
31
-	}
26
+    protected function setUp(): void {
27
+        parent::setUp();
28
+        $this->storage->mkdir('foo');
29
+        $this->sourceCache = $this->cache;
30
+        $this->cache = $this->getMaskedCached(Constants::PERMISSION_ALL);
31
+    }
32 32
 
33
-	protected function getMaskedCached($mask) {
34
-		return new \OC\Files\Cache\Wrapper\CachePermissionsMask($this->sourceCache, $mask);
35
-	}
33
+    protected function getMaskedCached($mask) {
34
+        return new \OC\Files\Cache\Wrapper\CachePermissionsMask($this->sourceCache, $mask);
35
+    }
36 36
 
37
-	public static function maskProvider(): array {
38
-		return [
39
-			[Constants::PERMISSION_ALL],
40
-			[Constants::PERMISSION_ALL - Constants::PERMISSION_SHARE],
41
-			[Constants::PERMISSION_ALL - Constants::PERMISSION_UPDATE],
42
-			[Constants::PERMISSION_READ]
43
-		];
44
-	}
37
+    public static function maskProvider(): array {
38
+        return [
39
+            [Constants::PERMISSION_ALL],
40
+            [Constants::PERMISSION_ALL - Constants::PERMISSION_SHARE],
41
+            [Constants::PERMISSION_ALL - Constants::PERMISSION_UPDATE],
42
+            [Constants::PERMISSION_READ]
43
+        ];
44
+    }
45 45
 
46
-	/**
47
-	 * @dataProvider maskProvider
48
-	 * @param int $mask
49
-	 */
50
-	public function testGetMasked($mask): void {
51
-		$cache = $this->getMaskedCached($mask);
52
-		$data = ['size' => 100, 'mtime' => 50, 'mimetype' => 'text/plain', 'permissions' => Constants::PERMISSION_ALL];
53
-		$this->sourceCache->put('foo', $data);
54
-		$result = $cache->get('foo');
55
-		$this->assertEquals($mask, $result['permissions']);
46
+    /**
47
+     * @dataProvider maskProvider
48
+     * @param int $mask
49
+     */
50
+    public function testGetMasked($mask): void {
51
+        $cache = $this->getMaskedCached($mask);
52
+        $data = ['size' => 100, 'mtime' => 50, 'mimetype' => 'text/plain', 'permissions' => Constants::PERMISSION_ALL];
53
+        $this->sourceCache->put('foo', $data);
54
+        $result = $cache->get('foo');
55
+        $this->assertEquals($mask, $result['permissions']);
56 56
 
57
-		$data = ['size' => 100, 'mtime' => 50, 'mimetype' => 'text/plain', 'permissions' => Constants::PERMISSION_ALL - Constants::PERMISSION_DELETE];
58
-		$this->sourceCache->put('bar', $data);
59
-		$result = $cache->get('bar');
60
-		$this->assertEquals($mask & ~Constants::PERMISSION_DELETE, $result['permissions']);
61
-	}
57
+        $data = ['size' => 100, 'mtime' => 50, 'mimetype' => 'text/plain', 'permissions' => Constants::PERMISSION_ALL - Constants::PERMISSION_DELETE];
58
+        $this->sourceCache->put('bar', $data);
59
+        $result = $cache->get('bar');
60
+        $this->assertEquals($mask & ~Constants::PERMISSION_DELETE, $result['permissions']);
61
+    }
62 62
 
63
-	/**
64
-	 * @dataProvider maskProvider
65
-	 * @param int $mask
66
-	 */
67
-	public function testGetFolderContentMasked($mask): void {
68
-		$this->storage->mkdir('foo');
69
-		$this->storage->file_put_contents('foo/bar', 'asd');
70
-		$this->storage->file_put_contents('foo/asd', 'bar');
71
-		$this->storage->getScanner()->scan('');
63
+    /**
64
+     * @dataProvider maskProvider
65
+     * @param int $mask
66
+     */
67
+    public function testGetFolderContentMasked($mask): void {
68
+        $this->storage->mkdir('foo');
69
+        $this->storage->file_put_contents('foo/bar', 'asd');
70
+        $this->storage->file_put_contents('foo/asd', 'bar');
71
+        $this->storage->getScanner()->scan('');
72 72
 
73
-		$cache = $this->getMaskedCached($mask);
74
-		$files = $cache->getFolderContents('foo');
75
-		$this->assertCount(2, $files);
73
+        $cache = $this->getMaskedCached($mask);
74
+        $files = $cache->getFolderContents('foo');
75
+        $this->assertCount(2, $files);
76 76
 
77
-		foreach ($files as $file) {
78
-			$this->assertEquals($mask & ~Constants::PERMISSION_CREATE, $file['permissions']);
79
-		}
80
-	}
77
+        foreach ($files as $file) {
78
+            $this->assertEquals($mask & ~Constants::PERMISSION_CREATE, $file['permissions']);
79
+        }
80
+    }
81 81
 
82
-	/**
83
-	 * @dataProvider maskProvider
84
-	 * @param int $mask
85
-	 */
86
-	public function testSearchMasked($mask): void {
87
-		$this->storage->mkdir('foo');
88
-		$this->storage->file_put_contents('foo/bar', 'asd');
89
-		$this->storage->file_put_contents('foo/foobar', 'bar');
90
-		$this->storage->getScanner()->scan('');
82
+    /**
83
+     * @dataProvider maskProvider
84
+     * @param int $mask
85
+     */
86
+    public function testSearchMasked($mask): void {
87
+        $this->storage->mkdir('foo');
88
+        $this->storage->file_put_contents('foo/bar', 'asd');
89
+        $this->storage->file_put_contents('foo/foobar', 'bar');
90
+        $this->storage->getScanner()->scan('');
91 91
 
92
-		$cache = $this->getMaskedCached($mask);
93
-		$files = $cache->search('%bar');
94
-		$this->assertCount(2, $files);
92
+        $cache = $this->getMaskedCached($mask);
93
+        $files = $cache->search('%bar');
94
+        $this->assertCount(2, $files);
95 95
 
96
-		foreach ($files as $file) {
97
-			$this->assertEquals($mask & ~Constants::PERMISSION_CREATE, $file['permissions']);
98
-		}
99
-	}
96
+        foreach ($files as $file) {
97
+            $this->assertEquals($mask & ~Constants::PERMISSION_CREATE, $file['permissions']);
98
+        }
99
+    }
100 100
 }
Please login to merge, or discard this patch.
tests/lib/Files/Cache/UpdaterTest.php 1 patch
Indentation   +259 added lines, -259 removed lines patch added patch discarded remove patch
@@ -21,319 +21,319 @@
 block discarded – undo
21 21
  * @package Test\Files\Cache
22 22
  */
23 23
 class UpdaterTest extends \Test\TestCase {
24
-	/**
25
-	 * @var \OC\Files\Storage\Storage
26
-	 */
27
-	protected $storage;
24
+    /**
25
+     * @var \OC\Files\Storage\Storage
26
+     */
27
+    protected $storage;
28 28
 
29
-	/**
30
-	 * @var \OC\Files\Cache\Cache
31
-	 */
32
-	protected $cache;
29
+    /**
30
+     * @var \OC\Files\Cache\Cache
31
+     */
32
+    protected $cache;
33 33
 
34
-	/**
35
-	 * @var \OC\Files\View
36
-	 */
37
-	protected $view;
34
+    /**
35
+     * @var \OC\Files\View
36
+     */
37
+    protected $view;
38 38
 
39
-	/**
40
-	 * @var \OC\Files\Cache\Updater
41
-	 */
42
-	protected $updater;
39
+    /**
40
+     * @var \OC\Files\Cache\Updater
41
+     */
42
+    protected $updater;
43 43
 
44
-	protected function setUp(): void {
45
-		parent::setUp();
44
+    protected function setUp(): void {
45
+        parent::setUp();
46 46
 
47
-		$this->loginAsUser();
47
+        $this->loginAsUser();
48 48
 
49
-		$this->storage = new Temporary([]);
50
-		$this->updater = $this->storage->getUpdater();
51
-		$this->cache = $this->storage->getCache();
52
-	}
49
+        $this->storage = new Temporary([]);
50
+        $this->updater = $this->storage->getUpdater();
51
+        $this->cache = $this->storage->getCache();
52
+    }
53 53
 
54
-	protected function tearDown(): void {
55
-		$this->logout();
56
-		parent::tearDown();
57
-	}
54
+    protected function tearDown(): void {
55
+        $this->logout();
56
+        parent::tearDown();
57
+    }
58 58
 
59
-	public function testNewFile(): void {
60
-		$this->storage->file_put_contents('foo.txt', 'bar');
61
-		$this->assertFalse($this->cache->inCache('foo.txt'));
59
+    public function testNewFile(): void {
60
+        $this->storage->file_put_contents('foo.txt', 'bar');
61
+        $this->assertFalse($this->cache->inCache('foo.txt'));
62 62
 
63
-		$this->updater->update('foo.txt');
63
+        $this->updater->update('foo.txt');
64 64
 
65
-		$this->assertTrue($this->cache->inCache('foo.txt'));
66
-		$cached = $this->cache->get('foo.txt');
67
-		$this->assertEquals(3, $cached['size']);
68
-		$this->assertEquals('text/plain', $cached['mimetype']);
69
-	}
65
+        $this->assertTrue($this->cache->inCache('foo.txt'));
66
+        $cached = $this->cache->get('foo.txt');
67
+        $this->assertEquals(3, $cached['size']);
68
+        $this->assertEquals('text/plain', $cached['mimetype']);
69
+    }
70 70
 
71
-	public function testUpdatedFile(): void {
72
-		$this->storage->file_put_contents('foo.txt', 'bar');
73
-		$this->updater->update('foo.txt');
71
+    public function testUpdatedFile(): void {
72
+        $this->storage->file_put_contents('foo.txt', 'bar');
73
+        $this->updater->update('foo.txt');
74 74
 
75
-		$cached = $this->cache->get('foo.txt');
76
-		$this->assertEquals(3, $cached['size']);
77
-		$this->assertEquals('text/plain', $cached['mimetype']);
75
+        $cached = $this->cache->get('foo.txt');
76
+        $this->assertEquals(3, $cached['size']);
77
+        $this->assertEquals('text/plain', $cached['mimetype']);
78 78
 
79
-		$this->storage->file_put_contents('foo.txt', 'qwerty');
79
+        $this->storage->file_put_contents('foo.txt', 'qwerty');
80 80
 
81
-		$cached = $this->cache->get('foo.txt');
82
-		$this->assertEquals(3, $cached['size']);
81
+        $cached = $this->cache->get('foo.txt');
82
+        $this->assertEquals(3, $cached['size']);
83 83
 
84
-		$this->updater->update('/foo.txt');
84
+        $this->updater->update('/foo.txt');
85 85
 
86
-		$cached = $this->cache->get('foo.txt');
87
-		$this->assertEquals(6, $cached['size']);
88
-	}
86
+        $cached = $this->cache->get('foo.txt');
87
+        $this->assertEquals(6, $cached['size']);
88
+    }
89 89
 
90
-	public function testParentSize(): void {
91
-		$this->storage->getScanner()->scan('');
90
+    public function testParentSize(): void {
91
+        $this->storage->getScanner()->scan('');
92 92
 
93
-		$parentCached = $this->cache->get('');
94
-		$this->assertEquals(0, $parentCached['size']);
93
+        $parentCached = $this->cache->get('');
94
+        $this->assertEquals(0, $parentCached['size']);
95 95
 
96
-		$this->storage->file_put_contents('foo.txt', 'bar');
96
+        $this->storage->file_put_contents('foo.txt', 'bar');
97 97
 
98
-		$parentCached = $this->cache->get('');
99
-		$this->assertEquals(0, $parentCached['size']);
98
+        $parentCached = $this->cache->get('');
99
+        $this->assertEquals(0, $parentCached['size']);
100 100
 
101
-		$this->updater->update('foo.txt');
101
+        $this->updater->update('foo.txt');
102 102
 
103
-		$parentCached = $this->cache->get('');
104
-		$this->assertEquals(3, $parentCached['size']);
103
+        $parentCached = $this->cache->get('');
104
+        $this->assertEquals(3, $parentCached['size']);
105 105
 
106
-		$this->storage->file_put_contents('foo.txt', 'qwerty');
106
+        $this->storage->file_put_contents('foo.txt', 'qwerty');
107 107
 
108
-		$parentCached = $this->cache->get('');
109
-		$this->assertEquals(3, $parentCached['size']);
108
+        $parentCached = $this->cache->get('');
109
+        $this->assertEquals(3, $parentCached['size']);
110 110
 
111
-		$this->updater->update('foo.txt');
111
+        $this->updater->update('foo.txt');
112 112
 
113
-		$parentCached = $this->cache->get('');
114
-		$this->assertEquals(6, $parentCached['size']);
113
+        $parentCached = $this->cache->get('');
114
+        $this->assertEquals(6, $parentCached['size']);
115 115
 
116
-		$this->storage->unlink('foo.txt');
116
+        $this->storage->unlink('foo.txt');
117 117
 
118
-		$parentCached = $this->cache->get('');
119
-		$this->assertEquals(6, $parentCached['size']);
118
+        $parentCached = $this->cache->get('');
119
+        $this->assertEquals(6, $parentCached['size']);
120 120
 
121
-		$this->updater->remove('foo.txt');
121
+        $this->updater->remove('foo.txt');
122 122
 
123
-		$parentCached = $this->cache->get('');
124
-		$this->assertEquals(0, $parentCached['size']);
125
-	}
123
+        $parentCached = $this->cache->get('');
124
+        $this->assertEquals(0, $parentCached['size']);
125
+    }
126 126
 
127
-	public function testMove(): void {
128
-		$this->storage->file_put_contents('foo.txt', 'qwerty');
129
-		$this->updater->update('foo.txt');
127
+    public function testMove(): void {
128
+        $this->storage->file_put_contents('foo.txt', 'qwerty');
129
+        $this->updater->update('foo.txt');
130 130
 
131
-		$this->assertTrue($this->cache->inCache('foo.txt'));
132
-		$this->assertFalse($this->cache->inCache('bar.txt'));
133
-		$cached = $this->cache->get('foo.txt');
131
+        $this->assertTrue($this->cache->inCache('foo.txt'));
132
+        $this->assertFalse($this->cache->inCache('bar.txt'));
133
+        $cached = $this->cache->get('foo.txt');
134 134
 
135
-		$this->storage->rename('foo.txt', 'bar.txt');
135
+        $this->storage->rename('foo.txt', 'bar.txt');
136 136
 
137
-		$this->assertTrue($this->cache->inCache('foo.txt'));
138
-		$this->assertFalse($this->cache->inCache('bar.txt'));
137
+        $this->assertTrue($this->cache->inCache('foo.txt'));
138
+        $this->assertFalse($this->cache->inCache('bar.txt'));
139 139
 
140
-		$this->updater->renameFromStorage($this->storage, 'foo.txt', 'bar.txt');
140
+        $this->updater->renameFromStorage($this->storage, 'foo.txt', 'bar.txt');
141 141
 
142
-		$this->assertFalse($this->cache->inCache('foo.txt'));
143
-		$this->assertTrue($this->cache->inCache('bar.txt'));
142
+        $this->assertFalse($this->cache->inCache('foo.txt'));
143
+        $this->assertTrue($this->cache->inCache('bar.txt'));
144 144
 
145
-		$cachedTarget = $this->cache->get('bar.txt');
146
-		$this->assertEquals($cached['etag'], $cachedTarget['etag']);
147
-		$this->assertEquals($cached['mtime'], $cachedTarget['mtime']);
148
-		$this->assertEquals($cached['size'], $cachedTarget['size']);
149
-		$this->assertEquals($cached['fileid'], $cachedTarget['fileid']);
150
-	}
145
+        $cachedTarget = $this->cache->get('bar.txt');
146
+        $this->assertEquals($cached['etag'], $cachedTarget['etag']);
147
+        $this->assertEquals($cached['mtime'], $cachedTarget['mtime']);
148
+        $this->assertEquals($cached['size'], $cachedTarget['size']);
149
+        $this->assertEquals($cached['fileid'], $cachedTarget['fileid']);
150
+    }
151 151
 
152
-	public function testMoveNonExistingOverwrite(): void {
153
-		$this->storage->file_put_contents('bar.txt', 'qwerty');
154
-		$this->updater->update('bar.txt');
152
+    public function testMoveNonExistingOverwrite(): void {
153
+        $this->storage->file_put_contents('bar.txt', 'qwerty');
154
+        $this->updater->update('bar.txt');
155 155
 
156
-		$cached = $this->cache->get('bar.txt');
156
+        $cached = $this->cache->get('bar.txt');
157 157
 
158
-		$this->updater->renameFromStorage($this->storage, 'foo.txt', 'bar.txt');
158
+        $this->updater->renameFromStorage($this->storage, 'foo.txt', 'bar.txt');
159 159
 
160
-		$this->assertFalse($this->cache->inCache('foo.txt'));
161
-		$this->assertTrue($this->cache->inCache('bar.txt'));
160
+        $this->assertFalse($this->cache->inCache('foo.txt'));
161
+        $this->assertTrue($this->cache->inCache('bar.txt'));
162 162
 
163
-		$cachedTarget = $this->cache->get('bar.txt');
164
-		$this->assertEquals($cached['etag'], $cachedTarget['etag']);
165
-		$this->assertEquals($cached['mtime'], $cachedTarget['mtime']);
166
-		$this->assertEquals($cached['size'], $cachedTarget['size']);
167
-		$this->assertEquals($cached['fileid'], $cachedTarget['fileid']);
168
-	}
163
+        $cachedTarget = $this->cache->get('bar.txt');
164
+        $this->assertEquals($cached['etag'], $cachedTarget['etag']);
165
+        $this->assertEquals($cached['mtime'], $cachedTarget['mtime']);
166
+        $this->assertEquals($cached['size'], $cachedTarget['size']);
167
+        $this->assertEquals($cached['fileid'], $cachedTarget['fileid']);
168
+    }
169 169
 
170
-	public function testUpdateStorageMTime(): void {
171
-		$this->storage->mkdir('sub');
172
-		$this->storage->mkdir('sub2');
173
-		$this->storage->file_put_contents('sub/foo.txt', 'qwerty');
170
+    public function testUpdateStorageMTime(): void {
171
+        $this->storage->mkdir('sub');
172
+        $this->storage->mkdir('sub2');
173
+        $this->storage->file_put_contents('sub/foo.txt', 'qwerty');
174 174
 
175
-		$this->updater->update('sub');
176
-		$this->updater->update('sub/foo.txt');
177
-		$this->updater->update('sub2');
175
+        $this->updater->update('sub');
176
+        $this->updater->update('sub/foo.txt');
177
+        $this->updater->update('sub2');
178 178
 
179
-		$cachedSourceParent = $this->cache->get('sub');
180
-		$cachedSource = $this->cache->get('sub/foo.txt');
179
+        $cachedSourceParent = $this->cache->get('sub');
180
+        $cachedSource = $this->cache->get('sub/foo.txt');
181 181
 
182
-		$this->storage->rename('sub/foo.txt', 'sub2/bar.txt');
182
+        $this->storage->rename('sub/foo.txt', 'sub2/bar.txt');
183 183
 
184
-		// simulate storage having a different mtime
185
-		$testmtime = 1433323578;
184
+        // simulate storage having a different mtime
185
+        $testmtime = 1433323578;
186 186
 
187
-		// source storage mtime change
188
-		$this->storage->touch('sub', $testmtime);
187
+        // source storage mtime change
188
+        $this->storage->touch('sub', $testmtime);
189 189
 
190
-		// target storage mtime change
191
-		$this->storage->touch('sub2', $testmtime);
192
-		// some storages (like Dropbox) change storage mtime on rename
193
-		$this->storage->touch('sub2/bar.txt', $testmtime);
190
+        // target storage mtime change
191
+        $this->storage->touch('sub2', $testmtime);
192
+        // some storages (like Dropbox) change storage mtime on rename
193
+        $this->storage->touch('sub2/bar.txt', $testmtime);
194 194
 
195
-		$this->updater->renameFromStorage($this->storage, 'sub/foo.txt', 'sub2/bar.txt');
195
+        $this->updater->renameFromStorage($this->storage, 'sub/foo.txt', 'sub2/bar.txt');
196 196
 
197
-		$cachedTargetParent = $this->cache->get('sub2');
198
-		$cachedTarget = $this->cache->get('sub2/bar.txt');
197
+        $cachedTargetParent = $this->cache->get('sub2');
198
+        $cachedTarget = $this->cache->get('sub2/bar.txt');
199 199
 
200
-		$this->assertEquals($cachedSource['mtime'], $cachedTarget['mtime'], 'file mtime preserved');
200
+        $this->assertEquals($cachedSource['mtime'], $cachedTarget['mtime'], 'file mtime preserved');
201 201
 
202
-		$this->assertNotEquals($cachedTarget['storage_mtime'], $cachedTarget['mtime'], 'mtime is not storage_mtime for moved file');
202
+        $this->assertNotEquals($cachedTarget['storage_mtime'], $cachedTarget['mtime'], 'mtime is not storage_mtime for moved file');
203 203
 
204
-		$this->assertEquals($testmtime, $cachedTarget['storage_mtime'], 'target file storage_mtime propagated');
205
-		$this->assertNotEquals($testmtime, $cachedTarget['mtime'], 'target file mtime changed, not from storage');
204
+        $this->assertEquals($testmtime, $cachedTarget['storage_mtime'], 'target file storage_mtime propagated');
205
+        $this->assertNotEquals($testmtime, $cachedTarget['mtime'], 'target file mtime changed, not from storage');
206 206
 
207
-		$this->assertEquals($testmtime, $cachedTargetParent['storage_mtime'], 'target parent storage_mtime propagated');
208
-		$this->assertNotEquals($testmtime, $cachedTargetParent['mtime'], 'target folder mtime changed, not from storage');
209
-	}
207
+        $this->assertEquals($testmtime, $cachedTargetParent['storage_mtime'], 'target parent storage_mtime propagated');
208
+        $this->assertNotEquals($testmtime, $cachedTargetParent['mtime'], 'target folder mtime changed, not from storage');
209
+    }
210 210
 
211
-	public function testNewFileDisabled(): void {
212
-		$this->storage->file_put_contents('foo.txt', 'bar');
213
-		$this->assertFalse($this->cache->inCache('foo.txt'));
214
-
215
-		$this->updater->disable();
216
-		$this->updater->update('/foo.txt');
217
-
218
-		$this->assertFalse($this->cache->inCache('foo.txt'));
219
-	}
220
-
221
-	public function testMoveCrossStorage(): void {
222
-		$storage2 = new Temporary([]);
223
-		$cache2 = $storage2->getCache();
224
-		Filesystem::mount($storage2, [], '/bar');
225
-		$this->storage->file_put_contents('foo.txt', 'qwerty');
226
-
227
-		$this->updater->update('foo.txt');
228
-
229
-		$this->assertTrue($this->cache->inCache('foo.txt'));
230
-		$this->assertFalse($cache2->inCache('bar.txt'));
231
-		$cached = $this->cache->get('foo.txt');
232
-
233
-		// "rename"
234
-		$storage2->file_put_contents('bar.txt', 'qwerty');
235
-		$this->storage->unlink('foo.txt');
236
-
237
-		$this->assertTrue($this->cache->inCache('foo.txt'));
238
-		$this->assertFalse($cache2->inCache('bar.txt'));
239
-
240
-		$storage2->getUpdater()->renameFromStorage($this->storage, 'foo.txt', 'bar.txt');
241
-
242
-		$this->assertFalse($this->cache->inCache('foo.txt'));
243
-		$this->assertTrue($cache2->inCache('bar.txt'));
244
-
245
-		$cachedTarget = $cache2->get('bar.txt');
246
-		$this->assertEquals($cached['mtime'], $cachedTarget['mtime']);
247
-		$this->assertEquals($cached['size'], $cachedTarget['size']);
248
-		$this->assertEquals($cached['etag'], $cachedTarget['etag']);
249
-		$this->assertEquals($cached['fileid'], $cachedTarget['fileid']);
250
-	}
251
-
252
-	public function testMoveFolderCrossStorage(): void {
253
-		$storage2 = new Temporary([]);
254
-		$cache2 = $storage2->getCache();
255
-		Filesystem::mount($storage2, [], '/bar');
256
-		$this->storage->mkdir('foo');
257
-		$this->storage->mkdir('foo/bar');
258
-		$this->storage->file_put_contents('foo/foo.txt', 'qwerty');
259
-		$this->storage->file_put_contents('foo/bar.txt', 'foo');
260
-		$this->storage->file_put_contents('foo/bar/bar.txt', 'qwertyuiop');
261
-
262
-		$this->storage->getScanner()->scan('');
263
-
264
-		$this->assertTrue($this->cache->inCache('foo'));
265
-		$this->assertTrue($this->cache->inCache('foo/foo.txt'));
266
-		$this->assertTrue($this->cache->inCache('foo/bar.txt'));
267
-		$this->assertTrue($this->cache->inCache('foo/bar'));
268
-		$this->assertTrue($this->cache->inCache('foo/bar/bar.txt'));
269
-		$cached = [];
270
-		$cached[] = $this->cache->get('foo');
271
-		$cached[] = $this->cache->get('foo/foo.txt');
272
-		$cached[] = $this->cache->get('foo/bar.txt');
273
-		$cached[] = $this->cache->get('foo/bar');
274
-		$cached[] = $this->cache->get('foo/bar/bar.txt');
275
-
276
-		// add extension to trigger the possible mimetype change
277
-		$storage2->moveFromStorage($this->storage, 'foo', 'foo.b');
278
-		$storage2->getUpdater()->renameFromStorage($this->storage, 'foo', 'foo.b');
279
-
280
-		$this->assertFalse($this->cache->inCache('foo'));
281
-		$this->assertFalse($this->cache->inCache('foo/foo.txt'));
282
-		$this->assertFalse($this->cache->inCache('foo/bar.txt'));
283
-		$this->assertFalse($this->cache->inCache('foo/bar'));
284
-		$this->assertFalse($this->cache->inCache('foo/bar/bar.txt'));
285
-		$this->assertTrue($cache2->inCache('foo.b'));
286
-		$this->assertTrue($cache2->inCache('foo.b/foo.txt'));
287
-		$this->assertTrue($cache2->inCache('foo.b/bar.txt'));
288
-		$this->assertTrue($cache2->inCache('foo.b/bar'));
289
-		$this->assertTrue($cache2->inCache('foo.b/bar/bar.txt'));
290
-
291
-		$cachedTarget = [];
292
-		$cachedTarget[] = $cache2->get('foo.b');
293
-		$cachedTarget[] = $cache2->get('foo.b/foo.txt');
294
-		$cachedTarget[] = $cache2->get('foo.b/bar.txt');
295
-		$cachedTarget[] = $cache2->get('foo.b/bar');
296
-		$cachedTarget[] = $cache2->get('foo.b/bar/bar.txt');
297
-
298
-		foreach ($cached as $i => $old) {
299
-			$new = $cachedTarget[$i];
300
-			$this->assertEquals($old['mtime'], $new['mtime']);
301
-			$this->assertEquals($old['size'], $new['size']);
302
-			$this->assertEquals($old['etag'], $new['etag']);
303
-			$this->assertEquals($old['fileid'], $new['fileid']);
304
-			$this->assertEquals($old['mimetype'], $new['mimetype']);
305
-		}
306
-	}
307
-
308
-	public static function changeExtensionProvider(): array {
309
-		return [
310
-			[new Temporary()],
311
-			[new ObjectStoreStorage(['objectstore' => new StorageObjectStore(new Temporary())])]
312
-		];
313
-	}
314
-
315
-	/**
316
-	 * @dataProvider changeExtensionProvider
317
-	 */
318
-	public function testChangeExtension(IStorage $storage) {
319
-		$updater = $storage->getUpdater();
320
-		$cache = $storage->getCache();
321
-		$storage->file_put_contents('foo', 'qwerty');
322
-		$updater->update('foo');
323
-
324
-		$bareCached = $cache->get('foo');
325
-		$this->assertEquals('application/octet-stream', $bareCached->getMimeType());
326
-
327
-		$storage->rename('foo', 'foo.txt');
328
-		$updater->renameFromStorage($storage, 'foo', 'foo.txt');
329
-
330
-		$cached = $cache->get('foo.txt');
331
-		$this->assertEquals('text/plain', $cached->getMimeType());
332
-
333
-		$storage->rename('foo.txt', 'foo.md');
334
-		$updater->renameFromStorage($storage, 'foo.txt', 'foo.md');
335
-
336
-		$cachedTarget = $cache->get('foo.md');
337
-		$this->assertEquals('text/markdown', $cachedTarget->getMimeType());
338
-	}
211
+    public function testNewFileDisabled(): void {
212
+        $this->storage->file_put_contents('foo.txt', 'bar');
213
+        $this->assertFalse($this->cache->inCache('foo.txt'));
214
+
215
+        $this->updater->disable();
216
+        $this->updater->update('/foo.txt');
217
+
218
+        $this->assertFalse($this->cache->inCache('foo.txt'));
219
+    }
220
+
221
+    public function testMoveCrossStorage(): void {
222
+        $storage2 = new Temporary([]);
223
+        $cache2 = $storage2->getCache();
224
+        Filesystem::mount($storage2, [], '/bar');
225
+        $this->storage->file_put_contents('foo.txt', 'qwerty');
226
+
227
+        $this->updater->update('foo.txt');
228
+
229
+        $this->assertTrue($this->cache->inCache('foo.txt'));
230
+        $this->assertFalse($cache2->inCache('bar.txt'));
231
+        $cached = $this->cache->get('foo.txt');
232
+
233
+        // "rename"
234
+        $storage2->file_put_contents('bar.txt', 'qwerty');
235
+        $this->storage->unlink('foo.txt');
236
+
237
+        $this->assertTrue($this->cache->inCache('foo.txt'));
238
+        $this->assertFalse($cache2->inCache('bar.txt'));
239
+
240
+        $storage2->getUpdater()->renameFromStorage($this->storage, 'foo.txt', 'bar.txt');
241
+
242
+        $this->assertFalse($this->cache->inCache('foo.txt'));
243
+        $this->assertTrue($cache2->inCache('bar.txt'));
244
+
245
+        $cachedTarget = $cache2->get('bar.txt');
246
+        $this->assertEquals($cached['mtime'], $cachedTarget['mtime']);
247
+        $this->assertEquals($cached['size'], $cachedTarget['size']);
248
+        $this->assertEquals($cached['etag'], $cachedTarget['etag']);
249
+        $this->assertEquals($cached['fileid'], $cachedTarget['fileid']);
250
+    }
251
+
252
+    public function testMoveFolderCrossStorage(): void {
253
+        $storage2 = new Temporary([]);
254
+        $cache2 = $storage2->getCache();
255
+        Filesystem::mount($storage2, [], '/bar');
256
+        $this->storage->mkdir('foo');
257
+        $this->storage->mkdir('foo/bar');
258
+        $this->storage->file_put_contents('foo/foo.txt', 'qwerty');
259
+        $this->storage->file_put_contents('foo/bar.txt', 'foo');
260
+        $this->storage->file_put_contents('foo/bar/bar.txt', 'qwertyuiop');
261
+
262
+        $this->storage->getScanner()->scan('');
263
+
264
+        $this->assertTrue($this->cache->inCache('foo'));
265
+        $this->assertTrue($this->cache->inCache('foo/foo.txt'));
266
+        $this->assertTrue($this->cache->inCache('foo/bar.txt'));
267
+        $this->assertTrue($this->cache->inCache('foo/bar'));
268
+        $this->assertTrue($this->cache->inCache('foo/bar/bar.txt'));
269
+        $cached = [];
270
+        $cached[] = $this->cache->get('foo');
271
+        $cached[] = $this->cache->get('foo/foo.txt');
272
+        $cached[] = $this->cache->get('foo/bar.txt');
273
+        $cached[] = $this->cache->get('foo/bar');
274
+        $cached[] = $this->cache->get('foo/bar/bar.txt');
275
+
276
+        // add extension to trigger the possible mimetype change
277
+        $storage2->moveFromStorage($this->storage, 'foo', 'foo.b');
278
+        $storage2->getUpdater()->renameFromStorage($this->storage, 'foo', 'foo.b');
279
+
280
+        $this->assertFalse($this->cache->inCache('foo'));
281
+        $this->assertFalse($this->cache->inCache('foo/foo.txt'));
282
+        $this->assertFalse($this->cache->inCache('foo/bar.txt'));
283
+        $this->assertFalse($this->cache->inCache('foo/bar'));
284
+        $this->assertFalse($this->cache->inCache('foo/bar/bar.txt'));
285
+        $this->assertTrue($cache2->inCache('foo.b'));
286
+        $this->assertTrue($cache2->inCache('foo.b/foo.txt'));
287
+        $this->assertTrue($cache2->inCache('foo.b/bar.txt'));
288
+        $this->assertTrue($cache2->inCache('foo.b/bar'));
289
+        $this->assertTrue($cache2->inCache('foo.b/bar/bar.txt'));
290
+
291
+        $cachedTarget = [];
292
+        $cachedTarget[] = $cache2->get('foo.b');
293
+        $cachedTarget[] = $cache2->get('foo.b/foo.txt');
294
+        $cachedTarget[] = $cache2->get('foo.b/bar.txt');
295
+        $cachedTarget[] = $cache2->get('foo.b/bar');
296
+        $cachedTarget[] = $cache2->get('foo.b/bar/bar.txt');
297
+
298
+        foreach ($cached as $i => $old) {
299
+            $new = $cachedTarget[$i];
300
+            $this->assertEquals($old['mtime'], $new['mtime']);
301
+            $this->assertEquals($old['size'], $new['size']);
302
+            $this->assertEquals($old['etag'], $new['etag']);
303
+            $this->assertEquals($old['fileid'], $new['fileid']);
304
+            $this->assertEquals($old['mimetype'], $new['mimetype']);
305
+        }
306
+    }
307
+
308
+    public static function changeExtensionProvider(): array {
309
+        return [
310
+            [new Temporary()],
311
+            [new ObjectStoreStorage(['objectstore' => new StorageObjectStore(new Temporary())])]
312
+        ];
313
+    }
314
+
315
+    /**
316
+     * @dataProvider changeExtensionProvider
317
+     */
318
+    public function testChangeExtension(IStorage $storage) {
319
+        $updater = $storage->getUpdater();
320
+        $cache = $storage->getCache();
321
+        $storage->file_put_contents('foo', 'qwerty');
322
+        $updater->update('foo');
323
+
324
+        $bareCached = $cache->get('foo');
325
+        $this->assertEquals('application/octet-stream', $bareCached->getMimeType());
326
+
327
+        $storage->rename('foo', 'foo.txt');
328
+        $updater->renameFromStorage($storage, 'foo', 'foo.txt');
329
+
330
+        $cached = $cache->get('foo.txt');
331
+        $this->assertEquals('text/plain', $cached->getMimeType());
332
+
333
+        $storage->rename('foo.txt', 'foo.md');
334
+        $updater->renameFromStorage($storage, 'foo.txt', 'foo.md');
335
+
336
+        $cachedTarget = $cache->get('foo.md');
337
+        $this->assertEquals('text/markdown', $cachedTarget->getMimeType());
338
+    }
339 339
 }
Please login to merge, or discard this patch.
tests/lib/Files/Cache/SearchBuilderTest.php 1 patch
Indentation   +185 added lines, -185 removed lines patch added patch discarded remove patch
@@ -22,189 +22,189 @@
 block discarded – undo
22 22
  * @group DB
23 23
  */
24 24
 class SearchBuilderTest extends TestCase {
25
-	/** @var IQueryBuilder */
26
-	private $builder;
27
-
28
-	/** @var IMimeTypeLoader&\PHPUnit\Framework\MockObject\MockObject */
29
-	private $mimetypeLoader;
30
-
31
-	/** @var IFilesMetadataManager&\PHPUnit\Framework\MockObject\MockObject */
32
-	private $filesMetadataManager;
33
-
34
-	/** @var SearchBuilder */
35
-	private $searchBuilder;
36
-
37
-	/** @var integer */
38
-	private $numericStorageId;
39
-
40
-	protected function setUp(): void {
41
-		parent::setUp();
42
-		$this->builder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
43
-		$this->mimetypeLoader = $this->createMock(IMimeTypeLoader::class);
44
-		$this->filesMetadataManager = $this->createMock(IFilesMetadataManager::class);
45
-
46
-		$this->mimetypeLoader->expects($this->any())
47
-			->method('getId')
48
-			->willReturnMap([
49
-				['text', 1],
50
-				['text/plain', 2],
51
-				['text/xml', 3],
52
-				['image/jpg', 4],
53
-				['image/png', 5],
54
-				['image', 6],
55
-			]);
56
-
57
-		$this->mimetypeLoader->expects($this->any())
58
-			->method('getMimetypeById')
59
-			->willReturnMap([
60
-				[1, 'text'],
61
-				[2, 'text/plain'],
62
-				[3, 'text/xml'],
63
-				[4, 'image/jpg'],
64
-				[5, 'image/png'],
65
-				[6, 'image']
66
-			]);
67
-
68
-		$this->searchBuilder = new SearchBuilder($this->mimetypeLoader, $this->filesMetadataManager);
69
-		$this->numericStorageId = 10000;
70
-
71
-		$this->builder->select(['fileid'])
72
-			->from('filecache', 'file') // alias needed for QuerySearchHelper#getOperatorFieldAndValue
73
-			->where($this->builder->expr()->eq('storage', new Literal($this->numericStorageId)));
74
-	}
75
-
76
-	protected function tearDown(): void {
77
-		parent::tearDown();
78
-
79
-		$builder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
80
-
81
-		$builder->delete('filecache')
82
-			->where($builder->expr()->eq('storage', $builder->createNamedParameter($this->numericStorageId, IQueryBuilder::PARAM_INT)));
83
-
84
-		$builder->execute();
85
-	}
86
-
87
-	private function addCacheEntry(array $data) {
88
-		$data['storage'] = $this->numericStorageId;
89
-		$data['etag'] = 'unimportant';
90
-		$data['storage_mtime'] = $data['mtime'];
91
-		if (!isset($data['path'])) {
92
-			$data['path'] = 'random/' . $this->getUniqueID();
93
-		}
94
-		$data['path_hash'] = md5($data['path']);
95
-		if (!isset($data['mtime'])) {
96
-			$data['mtime'] = 100;
97
-		}
98
-		if (!isset($data['size'])) {
99
-			$data['size'] = 100;
100
-		}
101
-		$data['name'] = basename($data['path']);
102
-		$data['parent'] = -1;
103
-		if (isset($data['mimetype'])) {
104
-			[$mimepart,] = explode('/', $data['mimetype']);
105
-			$data['mimepart'] = $this->mimetypeLoader->getId($mimepart);
106
-			$data['mimetype'] = $this->mimetypeLoader->getId($data['mimetype']);
107
-		} else {
108
-			$data['mimepart'] = 1;
109
-			$data['mimetype'] = 1;
110
-		}
111
-
112
-		$builder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
113
-
114
-		$values = [];
115
-		foreach ($data as $key => $value) {
116
-			$values[$key] = $builder->createNamedParameter($value);
117
-		}
118
-
119
-		$builder->insert('filecache')
120
-			->values($values)
121
-			->execute();
122
-
123
-		return $builder->getLastInsertId();
124
-	}
125
-
126
-	private function search(ISearchOperator $operator) {
127
-		$dbOperator = $this->searchBuilder->searchOperatorToDBExpr($this->builder, $operator);
128
-		$this->builder->andWhere($dbOperator);
129
-
130
-		$result = $this->builder->execute();
131
-		$rows = $result->fetchAll(\PDO::FETCH_COLUMN);
132
-		$result->closeCursor();
133
-
134
-		return $rows;
135
-	}
136
-
137
-	public static function comparisonProvider(): array {
138
-		return [
139
-			[new SearchComparison(ISearchComparison::COMPARE_GREATER_THAN, 'mtime', 125), [1]],
140
-			[new SearchComparison(ISearchComparison::COMPARE_LESS_THAN, 'mtime', 125), [0]],
141
-			[new SearchComparison(ISearchComparison::COMPARE_EQUAL, 'size', 125), []],
142
-			[new SearchComparison(ISearchComparison::COMPARE_EQUAL, 'size', 50), [0, 1]],
143
-			[new SearchComparison(ISearchComparison::COMPARE_EQUAL, 'name', 'foobar'), [0]],
144
-			[new SearchComparison(ISearchComparison::COMPARE_LIKE, 'name', 'foo%'), [0, 1]],
145
-			[new SearchComparison(ISearchComparison::COMPARE_EQUAL, 'mimetype', 'image/jpg'), [0]],
146
-			[new SearchComparison(ISearchComparison::COMPARE_LIKE, 'mimetype', 'image/%'), [0, 1]],
147
-			[new SearchComparison(ISearchComparison::COMPARE_IN, 'mimetype', ['image/jpg', 'image/png']), [0, 1]],
148
-			[new SearchBinaryOperator(ISearchBinaryOperator::OPERATOR_AND, [
149
-				new SearchComparison(ISearchComparison::COMPARE_EQUAL, 'size', 50),
150
-				new SearchComparison(ISearchComparison::COMPARE_LESS_THAN, 'mtime', 125)
151
-			]), [0]],
152
-			[new SearchBinaryOperator(ISearchBinaryOperator::OPERATOR_AND, [
153
-				new SearchComparison(ISearchComparison::COMPARE_EQUAL, 'size', 50),
154
-				new SearchComparison(ISearchComparison::COMPARE_LESS_THAN, 'mtime', 125),
155
-				new SearchComparison(ISearchComparison::COMPARE_LIKE, 'mimetype', 'text/%')
156
-			]), []],
157
-			[new SearchBinaryOperator(ISearchBinaryOperator::OPERATOR_OR, [
158
-				new SearchComparison(ISearchComparison::COMPARE_EQUAL, 'mtime', 100),
159
-				new SearchComparison(ISearchComparison::COMPARE_EQUAL, 'mtime', 150),
160
-			]), [0, 1]],
161
-			[new SearchBinaryOperator(ISearchBinaryOperator::OPERATOR_NOT, [
162
-				new SearchComparison(ISearchComparison::COMPARE_EQUAL, 'mtime', 150),
163
-			]), [0]],
164
-			[new SearchBinaryOperator(ISearchBinaryOperator::OPERATOR_NOT, [
165
-				new SearchComparison(ISearchComparison::COMPARE_GREATER_THAN, 'mtime', 125),
166
-			]), [0]],
167
-			[new SearchBinaryOperator(ISearchBinaryOperator::OPERATOR_NOT, [
168
-				new SearchComparison(ISearchComparison::COMPARE_LESS_THAN, 'mtime', 125),
169
-			]), [1]],
170
-			[new SearchBinaryOperator(ISearchBinaryOperator::OPERATOR_NOT, [
171
-				new SearchComparison(ISearchComparison::COMPARE_LIKE, 'name', '%bar'),
172
-			]), [1]],
173
-
174
-		];
175
-	}
176
-
177
-	/**
178
-	 * @dataProvider comparisonProvider
179
-	 *
180
-	 * @param ISearchOperator $operator
181
-	 * @param array $fileIds
182
-	 */
183
-	public function testComparison(ISearchOperator $operator, array $fileIds): void {
184
-		$fileId = [];
185
-		$fileId[] = $this->addCacheEntry([
186
-			'path' => 'foobar',
187
-			'mtime' => 100,
188
-			'size' => 50,
189
-			'mimetype' => 'image/jpg'
190
-		]);
191
-
192
-		$fileId[] = $this->addCacheEntry([
193
-			'path' => 'fooasd',
194
-			'mtime' => 150,
195
-			'size' => 50,
196
-			'mimetype' => 'image/png'
197
-		]);
198
-
199
-		$fileIds = array_map(function ($i) use ($fileId) {
200
-			return $fileId[$i];
201
-		}, $fileIds);
202
-
203
-		$results = $this->search($operator);
204
-
205
-		sort($fileIds);
206
-		sort($results);
207
-
208
-		$this->assertEquals($fileIds, $results);
209
-	}
25
+    /** @var IQueryBuilder */
26
+    private $builder;
27
+
28
+    /** @var IMimeTypeLoader&\PHPUnit\Framework\MockObject\MockObject */
29
+    private $mimetypeLoader;
30
+
31
+    /** @var IFilesMetadataManager&\PHPUnit\Framework\MockObject\MockObject */
32
+    private $filesMetadataManager;
33
+
34
+    /** @var SearchBuilder */
35
+    private $searchBuilder;
36
+
37
+    /** @var integer */
38
+    private $numericStorageId;
39
+
40
+    protected function setUp(): void {
41
+        parent::setUp();
42
+        $this->builder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
43
+        $this->mimetypeLoader = $this->createMock(IMimeTypeLoader::class);
44
+        $this->filesMetadataManager = $this->createMock(IFilesMetadataManager::class);
45
+
46
+        $this->mimetypeLoader->expects($this->any())
47
+            ->method('getId')
48
+            ->willReturnMap([
49
+                ['text', 1],
50
+                ['text/plain', 2],
51
+                ['text/xml', 3],
52
+                ['image/jpg', 4],
53
+                ['image/png', 5],
54
+                ['image', 6],
55
+            ]);
56
+
57
+        $this->mimetypeLoader->expects($this->any())
58
+            ->method('getMimetypeById')
59
+            ->willReturnMap([
60
+                [1, 'text'],
61
+                [2, 'text/plain'],
62
+                [3, 'text/xml'],
63
+                [4, 'image/jpg'],
64
+                [5, 'image/png'],
65
+                [6, 'image']
66
+            ]);
67
+
68
+        $this->searchBuilder = new SearchBuilder($this->mimetypeLoader, $this->filesMetadataManager);
69
+        $this->numericStorageId = 10000;
70
+
71
+        $this->builder->select(['fileid'])
72
+            ->from('filecache', 'file') // alias needed for QuerySearchHelper#getOperatorFieldAndValue
73
+            ->where($this->builder->expr()->eq('storage', new Literal($this->numericStorageId)));
74
+    }
75
+
76
+    protected function tearDown(): void {
77
+        parent::tearDown();
78
+
79
+        $builder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
80
+
81
+        $builder->delete('filecache')
82
+            ->where($builder->expr()->eq('storage', $builder->createNamedParameter($this->numericStorageId, IQueryBuilder::PARAM_INT)));
83
+
84
+        $builder->execute();
85
+    }
86
+
87
+    private function addCacheEntry(array $data) {
88
+        $data['storage'] = $this->numericStorageId;
89
+        $data['etag'] = 'unimportant';
90
+        $data['storage_mtime'] = $data['mtime'];
91
+        if (!isset($data['path'])) {
92
+            $data['path'] = 'random/' . $this->getUniqueID();
93
+        }
94
+        $data['path_hash'] = md5($data['path']);
95
+        if (!isset($data['mtime'])) {
96
+            $data['mtime'] = 100;
97
+        }
98
+        if (!isset($data['size'])) {
99
+            $data['size'] = 100;
100
+        }
101
+        $data['name'] = basename($data['path']);
102
+        $data['parent'] = -1;
103
+        if (isset($data['mimetype'])) {
104
+            [$mimepart,] = explode('/', $data['mimetype']);
105
+            $data['mimepart'] = $this->mimetypeLoader->getId($mimepart);
106
+            $data['mimetype'] = $this->mimetypeLoader->getId($data['mimetype']);
107
+        } else {
108
+            $data['mimepart'] = 1;
109
+            $data['mimetype'] = 1;
110
+        }
111
+
112
+        $builder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
113
+
114
+        $values = [];
115
+        foreach ($data as $key => $value) {
116
+            $values[$key] = $builder->createNamedParameter($value);
117
+        }
118
+
119
+        $builder->insert('filecache')
120
+            ->values($values)
121
+            ->execute();
122
+
123
+        return $builder->getLastInsertId();
124
+    }
125
+
126
+    private function search(ISearchOperator $operator) {
127
+        $dbOperator = $this->searchBuilder->searchOperatorToDBExpr($this->builder, $operator);
128
+        $this->builder->andWhere($dbOperator);
129
+
130
+        $result = $this->builder->execute();
131
+        $rows = $result->fetchAll(\PDO::FETCH_COLUMN);
132
+        $result->closeCursor();
133
+
134
+        return $rows;
135
+    }
136
+
137
+    public static function comparisonProvider(): array {
138
+        return [
139
+            [new SearchComparison(ISearchComparison::COMPARE_GREATER_THAN, 'mtime', 125), [1]],
140
+            [new SearchComparison(ISearchComparison::COMPARE_LESS_THAN, 'mtime', 125), [0]],
141
+            [new SearchComparison(ISearchComparison::COMPARE_EQUAL, 'size', 125), []],
142
+            [new SearchComparison(ISearchComparison::COMPARE_EQUAL, 'size', 50), [0, 1]],
143
+            [new SearchComparison(ISearchComparison::COMPARE_EQUAL, 'name', 'foobar'), [0]],
144
+            [new SearchComparison(ISearchComparison::COMPARE_LIKE, 'name', 'foo%'), [0, 1]],
145
+            [new SearchComparison(ISearchComparison::COMPARE_EQUAL, 'mimetype', 'image/jpg'), [0]],
146
+            [new SearchComparison(ISearchComparison::COMPARE_LIKE, 'mimetype', 'image/%'), [0, 1]],
147
+            [new SearchComparison(ISearchComparison::COMPARE_IN, 'mimetype', ['image/jpg', 'image/png']), [0, 1]],
148
+            [new SearchBinaryOperator(ISearchBinaryOperator::OPERATOR_AND, [
149
+                new SearchComparison(ISearchComparison::COMPARE_EQUAL, 'size', 50),
150
+                new SearchComparison(ISearchComparison::COMPARE_LESS_THAN, 'mtime', 125)
151
+            ]), [0]],
152
+            [new SearchBinaryOperator(ISearchBinaryOperator::OPERATOR_AND, [
153
+                new SearchComparison(ISearchComparison::COMPARE_EQUAL, 'size', 50),
154
+                new SearchComparison(ISearchComparison::COMPARE_LESS_THAN, 'mtime', 125),
155
+                new SearchComparison(ISearchComparison::COMPARE_LIKE, 'mimetype', 'text/%')
156
+            ]), []],
157
+            [new SearchBinaryOperator(ISearchBinaryOperator::OPERATOR_OR, [
158
+                new SearchComparison(ISearchComparison::COMPARE_EQUAL, 'mtime', 100),
159
+                new SearchComparison(ISearchComparison::COMPARE_EQUAL, 'mtime', 150),
160
+            ]), [0, 1]],
161
+            [new SearchBinaryOperator(ISearchBinaryOperator::OPERATOR_NOT, [
162
+                new SearchComparison(ISearchComparison::COMPARE_EQUAL, 'mtime', 150),
163
+            ]), [0]],
164
+            [new SearchBinaryOperator(ISearchBinaryOperator::OPERATOR_NOT, [
165
+                new SearchComparison(ISearchComparison::COMPARE_GREATER_THAN, 'mtime', 125),
166
+            ]), [0]],
167
+            [new SearchBinaryOperator(ISearchBinaryOperator::OPERATOR_NOT, [
168
+                new SearchComparison(ISearchComparison::COMPARE_LESS_THAN, 'mtime', 125),
169
+            ]), [1]],
170
+            [new SearchBinaryOperator(ISearchBinaryOperator::OPERATOR_NOT, [
171
+                new SearchComparison(ISearchComparison::COMPARE_LIKE, 'name', '%bar'),
172
+            ]), [1]],
173
+
174
+        ];
175
+    }
176
+
177
+    /**
178
+     * @dataProvider comparisonProvider
179
+     *
180
+     * @param ISearchOperator $operator
181
+     * @param array $fileIds
182
+     */
183
+    public function testComparison(ISearchOperator $operator, array $fileIds): void {
184
+        $fileId = [];
185
+        $fileId[] = $this->addCacheEntry([
186
+            'path' => 'foobar',
187
+            'mtime' => 100,
188
+            'size' => 50,
189
+            'mimetype' => 'image/jpg'
190
+        ]);
191
+
192
+        $fileId[] = $this->addCacheEntry([
193
+            'path' => 'fooasd',
194
+            'mtime' => 150,
195
+            'size' => 50,
196
+            'mimetype' => 'image/png'
197
+        ]);
198
+
199
+        $fileIds = array_map(function ($i) use ($fileId) {
200
+            return $fileId[$i];
201
+        }, $fileIds);
202
+
203
+        $results = $this->search($operator);
204
+
205
+        sort($fileIds);
206
+        sort($results);
207
+
208
+        $this->assertEquals($fileIds, $results);
209
+    }
210 210
 }
Please login to merge, or discard this patch.
tests/lib/Files/Utils/ScannerTest.php 1 patch
Indentation   +190 added lines, -190 removed lines patch added patch discarded remove patch
@@ -17,21 +17,21 @@  discard block
 block discarded – undo
17 17
 use Psr\Log\LoggerInterface;
18 18
 
19 19
 class TestScanner extends \OC\Files\Utils\Scanner {
20
-	/**
21
-	 * @var \OC\Files\Mount\MountPoint[] $mounts
22
-	 */
23
-	private $mounts = [];
24
-
25
-	/**
26
-	 * @param \OC\Files\Mount\MountPoint $mount
27
-	 */
28
-	public function addMount($mount) {
29
-		$this->mounts[] = $mount;
30
-	}
31
-
32
-	protected function getMounts($dir) {
33
-		return $this->mounts;
34
-	}
20
+    /**
21
+     * @var \OC\Files\Mount\MountPoint[] $mounts
22
+     */
23
+    private $mounts = [];
24
+
25
+    /**
26
+     * @param \OC\Files\Mount\MountPoint $mount
27
+     */
28
+    public function addMount($mount) {
29
+        $this->mounts[] = $mount;
30
+    }
31
+
32
+    protected function getMounts($dir) {
33
+        return $this->mounts;
34
+    }
35 35
 }
36 36
 
37 37
 /**
@@ -42,179 +42,179 @@  discard block
 block discarded – undo
42 42
  * @package Test\Files\Utils
43 43
  */
44 44
 class ScannerTest extends \Test\TestCase {
45
-	/**
46
-	 * @var \Test\Util\User\Dummy
47
-	 */
48
-	private $userBackend;
49
-
50
-	protected function setUp(): void {
51
-		parent::setUp();
52
-
53
-		$this->userBackend = new \Test\Util\User\Dummy();
54
-		\OC::$server->getUserManager()->registerBackend($this->userBackend);
55
-		$this->loginAsUser();
56
-	}
57
-
58
-	protected function tearDown(): void {
59
-		$this->logout();
60
-		\OC::$server->getUserManager()->removeBackend($this->userBackend);
61
-		parent::tearDown();
62
-	}
63
-
64
-	public function testReuseExistingRoot(): void {
65
-		$storage = new Temporary([]);
66
-		$mount = new MountPoint($storage, '');
67
-		Filesystem::getMountManager()->addMount($mount);
68
-		$cache = $storage->getCache();
69
-
70
-		$storage->mkdir('folder');
71
-		$storage->file_put_contents('foo.txt', 'qwerty');
72
-		$storage->file_put_contents('folder/bar.txt', 'qwerty');
73
-
74
-		$scanner = new TestScanner('', \OC::$server->getDatabaseConnection(), $this->createMock(IEventDispatcher::class), \OC::$server->get(LoggerInterface::class));
75
-		$scanner->addMount($mount);
76
-
77
-		$scanner->scan('');
78
-		$this->assertTrue($cache->inCache('folder/bar.txt'));
79
-		$oldRoot = $cache->get('');
80
-
81
-		$scanner->scan('');
82
-		$newRoot = $cache->get('');
83
-		$this->assertEquals($oldRoot, $newRoot);
84
-	}
85
-
86
-	public function testReuseExistingFile(): void {
87
-		$storage = new Temporary([]);
88
-		$mount = new MountPoint($storage, '');
89
-		Filesystem::getMountManager()->addMount($mount);
90
-		$cache = $storage->getCache();
91
-
92
-		$storage->mkdir('folder');
93
-		$storage->file_put_contents('foo.txt', 'qwerty');
94
-		$storage->file_put_contents('folder/bar.txt', 'qwerty');
95
-
96
-		$scanner = new TestScanner('', \OC::$server->getDatabaseConnection(), $this->createMock(IEventDispatcher::class), \OC::$server->get(LoggerInterface::class));
97
-		$scanner->addMount($mount);
98
-
99
-		$scanner->scan('');
100
-		$this->assertTrue($cache->inCache('folder/bar.txt'));
101
-		$old = $cache->get('folder/bar.txt');
102
-
103
-		$scanner->scan('');
104
-		$new = $cache->get('folder/bar.txt');
105
-		$this->assertEquals($old, $new);
106
-	}
107
-
108
-	public function testScanSubMount(): void {
109
-		$uid = $this->getUniqueID();
110
-		$this->userBackend->createUser($uid, 'test');
111
-
112
-		$mountProvider = $this->createMock(IMountProvider::class);
113
-
114
-		$storage = new Temporary([]);
115
-		$mount = new MountPoint($storage, '/' . $uid . '/files/foo');
116
-
117
-		$mountProvider->expects($this->any())
118
-			->method('getMountsForUser')
119
-			->willReturnCallback(function (IUser $user, IStorageFactory $storageFactory) use ($mount, $uid) {
120
-				if ($user->getUID() === $uid) {
121
-					return [$mount];
122
-				} else {
123
-					return [];
124
-				}
125
-			});
126
-
127
-		\OC::$server->getMountProviderCollection()->registerProvider($mountProvider);
128
-		$cache = $storage->getCache();
129
-
130
-		$storage->mkdir('folder');
131
-		$storage->file_put_contents('foo.txt', 'qwerty');
132
-		$storage->file_put_contents('folder/bar.txt', 'qwerty');
133
-
134
-		$scanner = new \OC\Files\Utils\Scanner($uid, \OC::$server->getDatabaseConnection(), \OC::$server->query(IEventDispatcher::class), \OC::$server->get(LoggerInterface::class));
135
-
136
-		$this->assertFalse($cache->inCache('folder/bar.txt'));
137
-		$scanner->scan('/' . $uid . '/files/foo');
138
-		$this->assertTrue($cache->inCache('folder/bar.txt'));
139
-	}
140
-
141
-	public static function invalidPathProvider(): array {
142
-		return [
143
-			[
144
-				'../',
145
-			],
146
-			[
147
-				'..\\',
148
-			],
149
-			[
150
-				'../..\\../',
151
-			],
152
-		];
153
-	}
154
-
155
-	/**
156
-	 * @dataProvider invalidPathProvider
157
-	 * @param string $invalidPath
158
-	 */
159
-	public function testInvalidPathScanning($invalidPath): void {
160
-		$this->expectException(\InvalidArgumentException::class);
161
-		$this->expectExceptionMessage('Invalid path to scan');
162
-
163
-		$scanner = new TestScanner('', \OC::$server->getDatabaseConnection(), $this->createMock(IEventDispatcher::class), \OC::$server->get(LoggerInterface::class));
164
-		$scanner->scan($invalidPath);
165
-	}
166
-
167
-	public function testPropagateEtag(): void {
168
-		$storage = new Temporary([]);
169
-		$mount = new MountPoint($storage, '');
170
-		Filesystem::getMountManager()->addMount($mount);
171
-		$cache = $storage->getCache();
172
-
173
-		$storage->mkdir('folder');
174
-		$storage->file_put_contents('folder/bar.txt', 'qwerty');
175
-		$storage->touch('folder/bar.txt', time() - 200);
176
-
177
-		$scanner = new TestScanner('', \OC::$server->getDatabaseConnection(), $this->createMock(IEventDispatcher::class), \OC::$server->get(LoggerInterface::class));
178
-		$scanner->addMount($mount);
179
-
180
-		$scanner->scan('');
181
-		$this->assertTrue($cache->inCache('folder/bar.txt'));
182
-		$oldRoot = $cache->get('');
183
-
184
-		$storage->file_put_contents('folder/bar.txt', 'qwerty');
185
-		$scanner->scan('');
186
-		$newRoot = $cache->get('');
187
-
188
-		$this->assertNotEquals($oldRoot->getEtag(), $newRoot->getEtag());
189
-	}
190
-
191
-	public function testShallow(): void {
192
-		$storage = new Temporary([]);
193
-		$mount = new MountPoint($storage, '');
194
-		Filesystem::getMountManager()->addMount($mount);
195
-		$cache = $storage->getCache();
196
-
197
-		$storage->mkdir('folder');
198
-		$storage->mkdir('folder/subfolder');
199
-		$storage->file_put_contents('foo.txt', 'qwerty');
200
-		$storage->file_put_contents('folder/bar.txt', 'qwerty');
201
-		$storage->file_put_contents('folder/subfolder/foobar.txt', 'qwerty');
202
-
203
-		$scanner = new TestScanner('', \OC::$server->getDatabaseConnection(), $this->createMock(IEventDispatcher::class), \OC::$server->get(LoggerInterface::class));
204
-		$scanner->addMount($mount);
205
-
206
-		$scanner->scan('', $recusive = false);
207
-		$this->assertTrue($cache->inCache('folder'));
208
-		$this->assertFalse($cache->inCache('folder/subfolder'));
209
-		$this->assertTrue($cache->inCache('foo.txt'));
210
-		$this->assertFalse($cache->inCache('folder/bar.txt'));
211
-		$this->assertFalse($cache->inCache('folder/subfolder/foobar.txt'));
212
-
213
-		$scanner->scan('folder', $recusive = false);
214
-		$this->assertTrue($cache->inCache('folder'));
215
-		$this->assertTrue($cache->inCache('folder/subfolder'));
216
-		$this->assertTrue($cache->inCache('foo.txt'));
217
-		$this->assertTrue($cache->inCache('folder/bar.txt'));
218
-		$this->assertFalse($cache->inCache('folder/subfolder/foobar.txt'));
219
-	}
45
+    /**
46
+     * @var \Test\Util\User\Dummy
47
+     */
48
+    private $userBackend;
49
+
50
+    protected function setUp(): void {
51
+        parent::setUp();
52
+
53
+        $this->userBackend = new \Test\Util\User\Dummy();
54
+        \OC::$server->getUserManager()->registerBackend($this->userBackend);
55
+        $this->loginAsUser();
56
+    }
57
+
58
+    protected function tearDown(): void {
59
+        $this->logout();
60
+        \OC::$server->getUserManager()->removeBackend($this->userBackend);
61
+        parent::tearDown();
62
+    }
63
+
64
+    public function testReuseExistingRoot(): void {
65
+        $storage = new Temporary([]);
66
+        $mount = new MountPoint($storage, '');
67
+        Filesystem::getMountManager()->addMount($mount);
68
+        $cache = $storage->getCache();
69
+
70
+        $storage->mkdir('folder');
71
+        $storage->file_put_contents('foo.txt', 'qwerty');
72
+        $storage->file_put_contents('folder/bar.txt', 'qwerty');
73
+
74
+        $scanner = new TestScanner('', \OC::$server->getDatabaseConnection(), $this->createMock(IEventDispatcher::class), \OC::$server->get(LoggerInterface::class));
75
+        $scanner->addMount($mount);
76
+
77
+        $scanner->scan('');
78
+        $this->assertTrue($cache->inCache('folder/bar.txt'));
79
+        $oldRoot = $cache->get('');
80
+
81
+        $scanner->scan('');
82
+        $newRoot = $cache->get('');
83
+        $this->assertEquals($oldRoot, $newRoot);
84
+    }
85
+
86
+    public function testReuseExistingFile(): void {
87
+        $storage = new Temporary([]);
88
+        $mount = new MountPoint($storage, '');
89
+        Filesystem::getMountManager()->addMount($mount);
90
+        $cache = $storage->getCache();
91
+
92
+        $storage->mkdir('folder');
93
+        $storage->file_put_contents('foo.txt', 'qwerty');
94
+        $storage->file_put_contents('folder/bar.txt', 'qwerty');
95
+
96
+        $scanner = new TestScanner('', \OC::$server->getDatabaseConnection(), $this->createMock(IEventDispatcher::class), \OC::$server->get(LoggerInterface::class));
97
+        $scanner->addMount($mount);
98
+
99
+        $scanner->scan('');
100
+        $this->assertTrue($cache->inCache('folder/bar.txt'));
101
+        $old = $cache->get('folder/bar.txt');
102
+
103
+        $scanner->scan('');
104
+        $new = $cache->get('folder/bar.txt');
105
+        $this->assertEquals($old, $new);
106
+    }
107
+
108
+    public function testScanSubMount(): void {
109
+        $uid = $this->getUniqueID();
110
+        $this->userBackend->createUser($uid, 'test');
111
+
112
+        $mountProvider = $this->createMock(IMountProvider::class);
113
+
114
+        $storage = new Temporary([]);
115
+        $mount = new MountPoint($storage, '/' . $uid . '/files/foo');
116
+
117
+        $mountProvider->expects($this->any())
118
+            ->method('getMountsForUser')
119
+            ->willReturnCallback(function (IUser $user, IStorageFactory $storageFactory) use ($mount, $uid) {
120
+                if ($user->getUID() === $uid) {
121
+                    return [$mount];
122
+                } else {
123
+                    return [];
124
+                }
125
+            });
126
+
127
+        \OC::$server->getMountProviderCollection()->registerProvider($mountProvider);
128
+        $cache = $storage->getCache();
129
+
130
+        $storage->mkdir('folder');
131
+        $storage->file_put_contents('foo.txt', 'qwerty');
132
+        $storage->file_put_contents('folder/bar.txt', 'qwerty');
133
+
134
+        $scanner = new \OC\Files\Utils\Scanner($uid, \OC::$server->getDatabaseConnection(), \OC::$server->query(IEventDispatcher::class), \OC::$server->get(LoggerInterface::class));
135
+
136
+        $this->assertFalse($cache->inCache('folder/bar.txt'));
137
+        $scanner->scan('/' . $uid . '/files/foo');
138
+        $this->assertTrue($cache->inCache('folder/bar.txt'));
139
+    }
140
+
141
+    public static function invalidPathProvider(): array {
142
+        return [
143
+            [
144
+                '../',
145
+            ],
146
+            [
147
+                '..\\',
148
+            ],
149
+            [
150
+                '../..\\../',
151
+            ],
152
+        ];
153
+    }
154
+
155
+    /**
156
+     * @dataProvider invalidPathProvider
157
+     * @param string $invalidPath
158
+     */
159
+    public function testInvalidPathScanning($invalidPath): void {
160
+        $this->expectException(\InvalidArgumentException::class);
161
+        $this->expectExceptionMessage('Invalid path to scan');
162
+
163
+        $scanner = new TestScanner('', \OC::$server->getDatabaseConnection(), $this->createMock(IEventDispatcher::class), \OC::$server->get(LoggerInterface::class));
164
+        $scanner->scan($invalidPath);
165
+    }
166
+
167
+    public function testPropagateEtag(): void {
168
+        $storage = new Temporary([]);
169
+        $mount = new MountPoint($storage, '');
170
+        Filesystem::getMountManager()->addMount($mount);
171
+        $cache = $storage->getCache();
172
+
173
+        $storage->mkdir('folder');
174
+        $storage->file_put_contents('folder/bar.txt', 'qwerty');
175
+        $storage->touch('folder/bar.txt', time() - 200);
176
+
177
+        $scanner = new TestScanner('', \OC::$server->getDatabaseConnection(), $this->createMock(IEventDispatcher::class), \OC::$server->get(LoggerInterface::class));
178
+        $scanner->addMount($mount);
179
+
180
+        $scanner->scan('');
181
+        $this->assertTrue($cache->inCache('folder/bar.txt'));
182
+        $oldRoot = $cache->get('');
183
+
184
+        $storage->file_put_contents('folder/bar.txt', 'qwerty');
185
+        $scanner->scan('');
186
+        $newRoot = $cache->get('');
187
+
188
+        $this->assertNotEquals($oldRoot->getEtag(), $newRoot->getEtag());
189
+    }
190
+
191
+    public function testShallow(): void {
192
+        $storage = new Temporary([]);
193
+        $mount = new MountPoint($storage, '');
194
+        Filesystem::getMountManager()->addMount($mount);
195
+        $cache = $storage->getCache();
196
+
197
+        $storage->mkdir('folder');
198
+        $storage->mkdir('folder/subfolder');
199
+        $storage->file_put_contents('foo.txt', 'qwerty');
200
+        $storage->file_put_contents('folder/bar.txt', 'qwerty');
201
+        $storage->file_put_contents('folder/subfolder/foobar.txt', 'qwerty');
202
+
203
+        $scanner = new TestScanner('', \OC::$server->getDatabaseConnection(), $this->createMock(IEventDispatcher::class), \OC::$server->get(LoggerInterface::class));
204
+        $scanner->addMount($mount);
205
+
206
+        $scanner->scan('', $recusive = false);
207
+        $this->assertTrue($cache->inCache('folder'));
208
+        $this->assertFalse($cache->inCache('folder/subfolder'));
209
+        $this->assertTrue($cache->inCache('foo.txt'));
210
+        $this->assertFalse($cache->inCache('folder/bar.txt'));
211
+        $this->assertFalse($cache->inCache('folder/subfolder/foobar.txt'));
212
+
213
+        $scanner->scan('folder', $recusive = false);
214
+        $this->assertTrue($cache->inCache('folder'));
215
+        $this->assertTrue($cache->inCache('folder/subfolder'));
216
+        $this->assertTrue($cache->inCache('foo.txt'));
217
+        $this->assertTrue($cache->inCache('folder/bar.txt'));
218
+        $this->assertFalse($cache->inCache('folder/subfolder/foobar.txt'));
219
+    }
220 220
 }
Please login to merge, or discard this patch.
tests/lib/Files/Storage/Storage.php 2 patches
Indentation   +653 added lines, -653 removed lines patch added patch discarded remove patch
@@ -12,657 +12,657 @@
 block discarded – undo
12 12
 use OCP\Files\Storage\IWriteStreamStorage;
13 13
 
14 14
 abstract class Storage extends \Test\TestCase {
15
-	/**
16
-	 * @var \OC\Files\Storage\Storage instance
17
-	 */
18
-	protected $instance;
19
-	protected $waitDelay = 0;
20
-
21
-	/**
22
-	 * Sleep for the number of seconds specified in the
23
-	 * $waitDelay attribute
24
-	 */
25
-	protected function wait() {
26
-		if ($this->waitDelay > 0) {
27
-			sleep($this->waitDelay);
28
-		}
29
-	}
30
-
31
-	/**
32
-	 * the root folder of the storage should always exist, be readable and be recognized as a directory
33
-	 */
34
-	public function testRoot(): void {
35
-		$this->assertTrue($this->instance->file_exists('/'), 'Root folder does not exist');
36
-		$this->assertTrue($this->instance->isReadable('/'), 'Root folder is not readable');
37
-		$this->assertTrue($this->instance->is_dir('/'), 'Root folder is not a directory');
38
-		$this->assertFalse($this->instance->is_file('/'), 'Root folder is a file');
39
-		$this->assertEquals('dir', $this->instance->filetype('/'));
40
-
41
-		//without this, any further testing would be useless, not an actual requirement for filestorage though
42
-		$this->assertTrue($this->instance->isUpdatable('/'), 'Root folder is not writable');
43
-	}
44
-
45
-	/**
46
-	 * Check that the test() function works
47
-	 */
48
-	public function testTestFunction(): void {
49
-		$this->assertTrue($this->instance->test());
50
-	}
51
-
52
-	/**
53
-	 * @dataProvider directoryProvider
54
-	 */
55
-	public function testDirectories($directory): void {
56
-		$this->assertFalse($this->instance->file_exists('/' . $directory));
57
-
58
-		$this->assertTrue($this->instance->mkdir('/' . $directory));
59
-
60
-		$this->assertTrue($this->instance->file_exists('/' . $directory));
61
-		$this->assertTrue($this->instance->is_dir('/' . $directory));
62
-		$this->assertFalse($this->instance->is_file('/' . $directory));
63
-		$this->assertEquals('dir', $this->instance->filetype('/' . $directory));
64
-		$this->assertEquals(0, $this->instance->filesize('/' . $directory));
65
-		$this->assertTrue($this->instance->isReadable('/' . $directory));
66
-		$this->assertTrue($this->instance->isUpdatable('/' . $directory));
67
-
68
-		$dh = $this->instance->opendir('/');
69
-		$content = [];
70
-		while (($file = readdir($dh)) !== false) {
71
-			if ($file != '.' and $file != '..') {
72
-				$content[] = $file;
73
-			}
74
-		}
75
-		$this->assertEquals([$directory], $content);
76
-
77
-		$content = iterator_to_array($this->instance->getDirectoryContent('/'));
78
-
79
-		$this->assertCount(1, $content);
80
-		$dirEntry = $content[0];
81
-		unset($dirEntry['scan_permissions']);
82
-		unset($dirEntry['etag']);
83
-		$this->assertLessThanOrEqual(1, abs($dirEntry['mtime'] - $this->instance->filemtime($directory)));
84
-		unset($dirEntry['mtime']);
85
-		unset($dirEntry['storage_mtime']);
86
-		$this->assertEquals([
87
-			'name' => $directory,
88
-			'mimetype' => $this->instance->getMimeType($directory),
89
-			'size' => -1,
90
-			'permissions' => $this->instance->getPermissions($directory),
91
-		], $dirEntry);
92
-
93
-		$this->assertFalse($this->instance->mkdir('/' . $directory)); //can't create existing folders
94
-		$this->assertTrue($this->instance->rmdir('/' . $directory));
95
-
96
-		$this->wait();
97
-		$this->assertFalse($this->instance->file_exists('/' . $directory));
98
-
99
-		$this->assertFalse($this->instance->rmdir('/' . $directory)); //can't remove non existing folders
100
-
101
-		$dh = $this->instance->opendir('/');
102
-		$content = [];
103
-		while (($file = readdir($dh)) !== false) {
104
-			if ($file != '.' and $file != '..') {
105
-				$content[] = $file;
106
-			}
107
-		}
108
-		$this->assertEquals([], $content);
109
-	}
110
-
111
-	public static function fileNameProvider(): array {
112
-		return [
113
-			['file.txt'],
114
-			[' file.txt'],
115
-			['folder .txt'],
116
-			['file with space.txt'],
117
-			['spéciäl fäile'],
118
-			['test single\'quote.txt'],
119
-		];
120
-	}
121
-
122
-	public static function directoryProvider(): array {
123
-		return [
124
-			['folder'],
125
-			[' folder'],
126
-			['folder '],
127
-			['folder with space'],
128
-			['spéciäl földer'],
129
-			['test single\'quote'],
130
-		];
131
-	}
132
-
133
-	public static function loremFileProvider(): array {
134
-		$root = \OC::$SERVERROOT . '/tests/data/';
135
-		return [
136
-			// small file
137
-			[$root . 'lorem.txt'],
138
-			// bigger file (> 8 KB which is the standard PHP block size)
139
-			[$root . 'lorem-big.txt']
140
-		];
141
-	}
142
-
143
-	/**
144
-	 * test the various uses of file_get_contents and file_put_contents
145
-	 *
146
-	 * @dataProvider loremFileProvider
147
-	 */
148
-	public function testGetPutContents($sourceFile): void {
149
-		$sourceText = file_get_contents($sourceFile);
150
-
151
-		//fill a file with string data
152
-		$this->instance->file_put_contents('/lorem.txt', $sourceText);
153
-		$this->assertFalse($this->instance->is_dir('/lorem.txt'));
154
-		$this->assertEquals($sourceText, $this->instance->file_get_contents('/lorem.txt'), 'data returned from file_get_contents is not equal to the source data');
155
-
156
-		//empty the file
157
-		$this->instance->file_put_contents('/lorem.txt', '');
158
-		$this->assertEquals('', $this->instance->file_get_contents('/lorem.txt'), 'file not emptied');
159
-	}
160
-
161
-	/**
162
-	 * test various known mimetypes
163
-	 */
164
-	public function testMimeType(): void {
165
-		$this->assertEquals('httpd/unix-directory', $this->instance->getMimeType('/'));
166
-		$this->assertEquals(false, $this->instance->getMimeType('/non/existing/file'));
167
-
168
-		$textFile = \OC::$SERVERROOT . '/tests/data/lorem.txt';
169
-		$this->instance->file_put_contents('/lorem.txt', file_get_contents($textFile, 'r'));
170
-		$this->assertEquals('text/plain', $this->instance->getMimeType('/lorem.txt'));
171
-
172
-		$pngFile = \OC::$SERVERROOT . '/tests/data/desktopapp.png';
173
-		$this->instance->file_put_contents('/desktopapp.png', file_get_contents($pngFile, 'r'));
174
-		$this->assertEquals('image/png', $this->instance->getMimeType('/desktopapp.png'));
175
-
176
-		$svgFile = \OC::$SERVERROOT . '/tests/data/desktopapp.svg';
177
-		$this->instance->file_put_contents('/desktopapp.svg', file_get_contents($svgFile, 'r'));
178
-		$this->assertEquals('image/svg+xml', $this->instance->getMimeType('/desktopapp.svg'));
179
-	}
180
-
181
-
182
-	public static function copyAndMoveProvider(): array {
183
-		return [
184
-			['/source.txt', '/target.txt'],
185
-			['/source.txt', '/target with space.txt'],
186
-			['/source with space.txt', '/target.txt'],
187
-			['/source with space.txt', '/target with space.txt'],
188
-			['/source.txt', '/tärgét.txt'],
189
-			['/sòurcē.txt', '/target.txt'],
190
-			['/sòurcē.txt', '/tärgét.txt'],
191
-			['/single \' quote.txt', '/tar\'get.txt'],
192
-		];
193
-	}
194
-
195
-	public function initSourceAndTarget($source, $target = null) {
196
-		$textFile = \OC::$SERVERROOT . '/tests/data/lorem.txt';
197
-		$this->instance->file_put_contents($source, file_get_contents($textFile));
198
-		if ($target) {
199
-			$testContents = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
200
-			$this->instance->file_put_contents($target, $testContents);
201
-		}
202
-	}
203
-
204
-	public function assertSameAsLorem($file) {
205
-		$textFile = \OC::$SERVERROOT . '/tests/data/lorem.txt';
206
-		$this->assertEquals(
207
-			file_get_contents($textFile),
208
-			$this->instance->file_get_contents($file),
209
-			'Expected ' . $file . ' to be a copy of ' . $textFile
210
-		);
211
-	}
212
-
213
-	/**
214
-	 * @dataProvider copyAndMoveProvider
215
-	 */
216
-	public function testCopy($source, $target): void {
217
-		$this->initSourceAndTarget($source);
218
-
219
-		$this->instance->copy($source, $target);
220
-
221
-		$this->assertTrue($this->instance->file_exists($target), $target . ' was not created');
222
-		$this->assertSameAsLorem($target);
223
-		$this->assertTrue($this->instance->file_exists($source), $source . ' was deleted');
224
-	}
225
-
226
-	/**
227
-	 * @dataProvider copyAndMoveProvider
228
-	 */
229
-	public function testMove($source, $target): void {
230
-		$this->initSourceAndTarget($source);
231
-
232
-		$this->instance->rename($source, $target);
233
-
234
-		$this->wait();
235
-		$this->assertTrue($this->instance->file_exists($target), $target . ' was not created');
236
-		$this->assertFalse($this->instance->file_exists($source), $source . ' still exists');
237
-		$this->assertSameAsLorem($target);
238
-	}
239
-
240
-	/**
241
-	 * @dataProvider copyAndMoveProvider
242
-	 */
243
-	public function testCopyOverwrite($source, $target): void {
244
-		$this->initSourceAndTarget($source, $target);
245
-
246
-		$this->instance->copy($source, $target);
247
-
248
-		$this->assertTrue($this->instance->file_exists($target), $target . ' was not created');
249
-		$this->assertTrue($this->instance->file_exists($source), $source . ' was deleted');
250
-		$this->assertSameAsLorem($target);
251
-		$this->assertSameAsLorem($source);
252
-	}
253
-
254
-	/**
255
-	 * @dataProvider copyAndMoveProvider
256
-	 */
257
-	public function testMoveOverwrite($source, $target): void {
258
-		$this->initSourceAndTarget($source, $target);
259
-
260
-		$this->instance->rename($source, $target);
261
-
262
-		$this->assertTrue($this->instance->file_exists($target), $target . ' was not created');
263
-		$this->assertFalse($this->instance->file_exists($source), $source . ' still exists');
264
-		$this->assertSameAsLorem($target);
265
-	}
266
-
267
-	public function testLocal(): void {
268
-		$textFile = \OC::$SERVERROOT . '/tests/data/lorem.txt';
269
-		$this->instance->file_put_contents('/lorem.txt', file_get_contents($textFile));
270
-		$localFile = $this->instance->getLocalFile('/lorem.txt');
271
-		$this->assertTrue(file_exists($localFile));
272
-		$this->assertEquals(file_get_contents($textFile), file_get_contents($localFile));
273
-
274
-		$this->instance->mkdir('/folder');
275
-		$this->instance->file_put_contents('/folder/lorem.txt', file_get_contents($textFile));
276
-		$this->instance->file_put_contents('/folder/bar.txt', 'asd');
277
-		$this->instance->mkdir('/folder/recursive');
278
-		$this->instance->file_put_contents('/folder/recursive/file.txt', 'foo');
279
-
280
-		// test below require to use instance->getLocalFile because the physical storage might be different
281
-		$localFile = $this->instance->getLocalFile('/folder/lorem.txt');
282
-		$this->assertTrue(file_exists($localFile));
283
-		$this->assertEquals(file_get_contents($localFile), file_get_contents($textFile));
284
-
285
-		$localFile = $this->instance->getLocalFile('/folder/bar.txt');
286
-		$this->assertTrue(file_exists($localFile));
287
-		$this->assertEquals(file_get_contents($localFile), 'asd');
288
-
289
-		$localFile = $this->instance->getLocalFile('/folder/recursive/file.txt');
290
-		$this->assertTrue(file_exists($localFile));
291
-		$this->assertEquals(file_get_contents($localFile), 'foo');
292
-	}
293
-
294
-	public function testStat(): void {
295
-		$textFile = \OC::$SERVERROOT . '/tests/data/lorem.txt';
296
-		$ctimeStart = time();
297
-		$this->instance->file_put_contents('/lorem.txt', file_get_contents($textFile));
298
-		$this->assertTrue($this->instance->isReadable('/lorem.txt'));
299
-		$ctimeEnd = time();
300
-		$mTime = $this->instance->filemtime('/lorem.txt');
301
-		$this->assertTrue($this->instance->hasUpdated('/lorem.txt', $ctimeStart - 5));
302
-		$this->assertTrue($this->instance->hasUpdated('/', $ctimeStart - 5));
303
-
304
-		// check that ($ctimeStart - 5) <= $mTime <= ($ctimeEnd + 1)
305
-		$this->assertGreaterThanOrEqual(($ctimeStart - 5), $mTime);
306
-		$this->assertLessThanOrEqual(($ctimeEnd + 1), $mTime);
307
-		$this->assertEquals(filesize($textFile), $this->instance->filesize('/lorem.txt'));
308
-
309
-		$stat = $this->instance->stat('/lorem.txt');
310
-		//only size and mtime are required in the result
311
-		$this->assertEquals($stat['size'], $this->instance->filesize('/lorem.txt'));
312
-		$this->assertEquals($stat['mtime'], $mTime);
313
-
314
-		if ($this->instance->touch('/lorem.txt', 100) !== false) {
315
-			$mTime = $this->instance->filemtime('/lorem.txt');
316
-			$this->assertEquals($mTime, 100);
317
-		}
318
-
319
-		$mtimeStart = time();
320
-
321
-		$this->instance->unlink('/lorem.txt');
322
-		$this->assertTrue($this->instance->hasUpdated('/', $mtimeStart - 5));
323
-	}
324
-
325
-	/**
326
-	 * Test whether checkUpdate properly returns false when there was
327
-	 * no change.
328
-	 */
329
-	public function testCheckUpdate(): void {
330
-		if ($this->instance instanceof \OC\Files\Storage\Wrapper\Wrapper) {
331
-			$this->markTestSkipped('Cannot test update check on wrappers');
332
-		}
333
-		$textFile = \OC::$SERVERROOT . '/tests/data/lorem.txt';
334
-		$watcher = $this->instance->getWatcher();
335
-		$watcher->setPolicy(Watcher::CHECK_ALWAYS);
336
-		$this->instance->file_put_contents('/lorem.txt', file_get_contents($textFile));
337
-		$this->assertTrue($watcher->checkUpdate('/lorem.txt'), 'Update detected');
338
-		$this->assertFalse($watcher->checkUpdate('/lorem.txt'), 'No update');
339
-	}
340
-
341
-	public function testUnlink(): void {
342
-		$textFile = \OC::$SERVERROOT . '/tests/data/lorem.txt';
343
-		$this->instance->file_put_contents('/lorem.txt', file_get_contents($textFile));
344
-
345
-		$this->assertTrue($this->instance->file_exists('/lorem.txt'));
346
-
347
-		$this->assertTrue($this->instance->unlink('/lorem.txt'));
348
-		$this->wait();
349
-
350
-		$this->assertFalse($this->instance->file_exists('/lorem.txt'));
351
-	}
352
-
353
-	/**
354
-	 * @dataProvider fileNameProvider
355
-	 */
356
-	public function testFOpen($fileName): void {
357
-		$textFile = \OC::$SERVERROOT . '/tests/data/lorem.txt';
358
-
359
-		$fh = @$this->instance->fopen($fileName, 'r');
360
-		if ($fh) {
361
-			fclose($fh);
362
-		}
363
-		$this->assertFalse($fh);
364
-		$this->assertFalse($this->instance->file_exists($fileName));
365
-
366
-		$fh = $this->instance->fopen($fileName, 'w');
367
-		fwrite($fh, file_get_contents($textFile));
368
-		fclose($fh);
369
-		$this->assertTrue($this->instance->file_exists($fileName));
370
-
371
-		$fh = $this->instance->fopen($fileName, 'r');
372
-		$content = stream_get_contents($fh);
373
-		$this->assertEquals(file_get_contents($textFile), $content);
374
-	}
375
-
376
-	public function testTouchCreateFile(): void {
377
-		$this->assertFalse($this->instance->file_exists('touch'));
378
-		// returns true on success
379
-		$this->assertTrue($this->instance->touch('touch'));
380
-		$this->assertTrue($this->instance->file_exists('touch'));
381
-	}
382
-
383
-	public function testRecursiveRmdir(): void {
384
-		$this->instance->mkdir('folder');
385
-		$this->instance->mkdir('folder/bar');
386
-		$this->wait();
387
-		$this->instance->file_put_contents('folder/asd.txt', 'foobar');
388
-		$this->instance->file_put_contents('folder/bar/foo.txt', 'asd');
389
-		$this->assertTrue($this->instance->rmdir('folder'));
390
-		$this->wait();
391
-		$this->assertFalse($this->instance->file_exists('folder/asd.txt'));
392
-		$this->assertFalse($this->instance->file_exists('folder/bar/foo.txt'));
393
-		$this->assertFalse($this->instance->file_exists('folder/bar'));
394
-		$this->assertFalse($this->instance->file_exists('folder'));
395
-	}
396
-
397
-	public function testRmdirEmptyFolder(): void {
398
-		$this->assertTrue($this->instance->mkdir('empty'));
399
-		$this->wait();
400
-		$this->assertTrue($this->instance->rmdir('empty'));
401
-		$this->assertFalse($this->instance->file_exists('empty'));
402
-	}
403
-
404
-	public function testRecursiveUnlink(): void {
405
-		$this->instance->mkdir('folder');
406
-		$this->instance->mkdir('folder/bar');
407
-		$this->instance->file_put_contents('folder/asd.txt', 'foobar');
408
-		$this->instance->file_put_contents('folder/bar/foo.txt', 'asd');
409
-		$this->assertTrue($this->instance->unlink('folder'));
410
-		$this->wait();
411
-		$this->assertFalse($this->instance->file_exists('folder/asd.txt'));
412
-		$this->assertFalse($this->instance->file_exists('folder/bar/foo.txt'));
413
-		$this->assertFalse($this->instance->file_exists('folder/bar'));
414
-		$this->assertFalse($this->instance->file_exists('folder'));
415
-	}
416
-
417
-	public static function hashProvider(): array {
418
-		return [
419
-			['Foobar', 'md5'],
420
-			['Foobar', 'sha1'],
421
-			['Foobar', 'sha256'],
422
-		];
423
-	}
424
-
425
-	/**
426
-	 * @dataProvider hashProvider
427
-	 */
428
-	public function testHash($data, $type): void {
429
-		$this->instance->file_put_contents('hash.txt', $data);
430
-		$this->assertEquals(hash($type, $data), $this->instance->hash($type, 'hash.txt'));
431
-		$this->assertEquals(hash($type, $data, true), $this->instance->hash($type, 'hash.txt', true));
432
-	}
433
-
434
-	public function testHashInFileName(): void {
435
-		$this->instance->file_put_contents('#test.txt', 'data');
436
-		$this->assertEquals('data', $this->instance->file_get_contents('#test.txt'));
437
-
438
-		$this->instance->mkdir('#foo');
439
-		$this->instance->file_put_contents('#foo/test.txt', 'data');
440
-		$this->assertEquals('data', $this->instance->file_get_contents('#foo/test.txt'));
441
-
442
-		$dh = $this->instance->opendir('#foo');
443
-		$content = [];
444
-		while ($file = readdir($dh)) {
445
-			if ($file != '.' and $file != '..') {
446
-				$content[] = $file;
447
-			}
448
-		}
449
-
450
-		$this->assertEquals(['test.txt'], $content);
451
-	}
452
-
453
-	public function testCopyOverWriteFile(): void {
454
-		$this->instance->file_put_contents('target.txt', 'foo');
455
-		$this->instance->file_put_contents('source.txt', 'bar');
456
-		$this->instance->copy('source.txt', 'target.txt');
457
-		$this->assertEquals('bar', $this->instance->file_get_contents('target.txt'));
458
-	}
459
-
460
-	public function testRenameOverWriteFile(): void {
461
-		$this->instance->file_put_contents('target.txt', 'foo');
462
-		$this->instance->file_put_contents('source.txt', 'bar');
463
-		$this->instance->rename('source.txt', 'target.txt');
464
-		$this->assertEquals('bar', $this->instance->file_get_contents('target.txt'));
465
-		$this->assertFalse($this->instance->file_exists('source.txt'));
466
-	}
467
-
468
-	public function testRenameDirectory(): void {
469
-		$this->instance->mkdir('source');
470
-		$this->instance->file_put_contents('source/test1.txt', 'foo');
471
-		$this->instance->file_put_contents('source/test2.txt', 'qwerty');
472
-		$this->instance->mkdir('source/subfolder');
473
-		$this->instance->file_put_contents('source/subfolder/test.txt', 'bar');
474
-		$this->instance->rename('source', 'target');
475
-
476
-		$this->assertFalse($this->instance->file_exists('source'));
477
-		$this->assertFalse($this->instance->file_exists('source/test1.txt'));
478
-		$this->assertFalse($this->instance->file_exists('source/test2.txt'));
479
-		$this->assertFalse($this->instance->file_exists('source/subfolder'));
480
-		$this->assertFalse($this->instance->file_exists('source/subfolder/test.txt'));
481
-
482
-		$this->assertTrue($this->instance->file_exists('target'));
483
-		$this->assertTrue($this->instance->file_exists('target/test1.txt'));
484
-		$this->assertTrue($this->instance->file_exists('target/test2.txt'));
485
-		$this->assertTrue($this->instance->file_exists('target/subfolder'));
486
-		$this->assertTrue($this->instance->file_exists('target/subfolder/test.txt'));
487
-
488
-		$contents = iterator_to_array($this->instance->getDirectoryContent(''));
489
-		$this->assertCount(1, $contents);
490
-
491
-		$this->assertEquals('foo', $this->instance->file_get_contents('target/test1.txt'));
492
-		$this->assertEquals('qwerty', $this->instance->file_get_contents('target/test2.txt'));
493
-		$this->assertEquals('bar', $this->instance->file_get_contents('target/subfolder/test.txt'));
494
-	}
495
-
496
-	public function testRenameOverWriteDirectory(): void {
497
-		$this->instance->mkdir('source');
498
-		$this->instance->file_put_contents('source/test1.txt', 'foo');
499
-
500
-		$this->instance->mkdir('target');
501
-		$this->instance->file_put_contents('target/test1.txt', 'bar');
502
-		$this->instance->file_put_contents('target/test2.txt', 'bar');
503
-
504
-		$this->assertTrue($this->instance->rename('source', 'target'), 'rename must return true on success');
505
-
506
-		$this->assertFalse($this->instance->file_exists('source'), 'source has not been removed');
507
-		$this->assertFalse($this->instance->file_exists('source/test1.txt'), 'source/test1.txt has not been removed');
508
-		$this->assertFalse($this->instance->file_exists('target/test2.txt'), 'target/test2.txt has not been removed');
509
-		$this->assertEquals('foo', $this->instance->file_get_contents('target/test1.txt'), 'target/test1.txt has not been overwritten');
510
-	}
511
-
512
-	public function testRenameOverWriteDirectoryOverFile(): void {
513
-		$this->instance->mkdir('source');
514
-		$this->instance->file_put_contents('source/test1.txt', 'foo');
515
-
516
-		$this->instance->file_put_contents('target', 'bar');
517
-
518
-		$this->assertTrue($this->instance->rename('source', 'target'), 'rename must return true on success');
519
-
520
-		$this->assertFalse($this->instance->file_exists('source'));
521
-		$this->assertFalse($this->instance->file_exists('source/test1.txt'));
522
-		$this->assertEquals('foo', $this->instance->file_get_contents('target/test1.txt'));
523
-	}
524
-
525
-	public function testCopyDirectory(): void {
526
-		$this->instance->mkdir('source');
527
-		$this->instance->file_put_contents('source/test1.txt', 'foo');
528
-		$this->instance->file_put_contents('source/test2.txt', 'qwerty');
529
-		$this->instance->mkdir('source/subfolder');
530
-		$this->instance->file_put_contents('source/subfolder/test.txt', 'bar');
531
-		$this->instance->copy('source', 'target');
532
-
533
-		$this->assertTrue($this->instance->file_exists('source'));
534
-		$this->assertTrue($this->instance->file_exists('source/test1.txt'));
535
-		$this->assertTrue($this->instance->file_exists('source/test2.txt'));
536
-		$this->assertTrue($this->instance->file_exists('source/subfolder'));
537
-		$this->assertTrue($this->instance->file_exists('source/subfolder/test.txt'));
538
-
539
-		$this->assertTrue($this->instance->file_exists('target'));
540
-		$this->assertTrue($this->instance->file_exists('target/test1.txt'));
541
-		$this->assertTrue($this->instance->file_exists('target/test2.txt'));
542
-		$this->assertTrue($this->instance->file_exists('target/subfolder'));
543
-		$this->assertTrue($this->instance->file_exists('target/subfolder/test.txt'));
544
-
545
-		$this->assertEquals('foo', $this->instance->file_get_contents('target/test1.txt'));
546
-		$this->assertEquals('qwerty', $this->instance->file_get_contents('target/test2.txt'));
547
-		$this->assertEquals('bar', $this->instance->file_get_contents('target/subfolder/test.txt'));
548
-	}
549
-
550
-	public function testCopyOverWriteDirectory(): void {
551
-		$this->instance->mkdir('source');
552
-		$this->instance->file_put_contents('source/test1.txt', 'foo');
553
-
554
-		$this->instance->mkdir('target');
555
-		$this->instance->file_put_contents('target/test1.txt', 'bar');
556
-		$this->instance->file_put_contents('target/test2.txt', 'bar');
557
-
558
-		$this->instance->copy('source', 'target');
559
-
560
-		$this->assertFalse($this->instance->file_exists('target/test2.txt'));
561
-		$this->assertEquals('foo', $this->instance->file_get_contents('target/test1.txt'));
562
-	}
563
-
564
-	public function testCopyOverWriteDirectoryOverFile(): void {
565
-		$this->instance->mkdir('source');
566
-		$this->instance->file_put_contents('source/test1.txt', 'foo');
567
-
568
-		$this->instance->file_put_contents('target', 'bar');
569
-
570
-		$this->instance->copy('source', 'target');
571
-
572
-		$this->assertEquals('foo', $this->instance->file_get_contents('target/test1.txt'));
573
-	}
574
-
575
-	public function testInstanceOfStorage(): void {
576
-		$this->assertTrue($this->instance->instanceOfStorage(IStorage::class));
577
-		$this->assertTrue($this->instance->instanceOfStorage(get_class($this->instance)));
578
-		$this->assertFalse($this->instance->instanceOfStorage('\OC'));
579
-	}
580
-
581
-	/**
582
-	 * @dataProvider copyAndMoveProvider
583
-	 */
584
-	public function testCopyFromSameStorage($source, $target): void {
585
-		$this->initSourceAndTarget($source);
586
-
587
-		$this->instance->copyFromStorage($this->instance, $source, $target);
588
-
589
-		$this->assertTrue($this->instance->file_exists($target), $target . ' was not created');
590
-		$this->assertSameAsLorem($target);
591
-		$this->assertTrue($this->instance->file_exists($source), $source . ' was deleted');
592
-	}
593
-
594
-	public function testIsCreatable(): void {
595
-		$this->instance->mkdir('source');
596
-		$this->assertTrue($this->instance->isCreatable('source'));
597
-	}
598
-
599
-	public function testIsReadable(): void {
600
-		$this->instance->mkdir('source');
601
-		$this->assertTrue($this->instance->isReadable('source'));
602
-	}
603
-
604
-	public function testIsUpdatable(): void {
605
-		$this->instance->mkdir('source');
606
-		$this->assertTrue($this->instance->isUpdatable('source'));
607
-	}
608
-
609
-	public function testIsDeletable(): void {
610
-		$this->instance->mkdir('source');
611
-		$this->assertTrue($this->instance->isDeletable('source'));
612
-	}
613
-
614
-	public function testIsShareable(): void {
615
-		$this->instance->mkdir('source');
616
-		$this->assertTrue($this->instance->isSharable('source'));
617
-	}
618
-
619
-	public function testStatAfterWrite(): void {
620
-		$this->instance->file_put_contents('foo.txt', 'bar');
621
-		$stat = $this->instance->stat('foo.txt');
622
-		$this->assertEquals(3, $stat['size']);
623
-
624
-		$fh = $this->instance->fopen('foo.txt', 'w');
625
-		fwrite($fh, 'qwerty');
626
-		fclose($fh);
627
-
628
-		$stat = $this->instance->stat('foo.txt');
629
-		$this->assertEquals(6, $stat['size']);
630
-	}
631
-
632
-	public function testPartFile(): void {
633
-		$this->instance->file_put_contents('bar.txt.part', 'bar');
634
-		$this->instance->rename('bar.txt.part', 'bar.txt');
635
-		$this->assertEquals('bar', $this->instance->file_get_contents('bar.txt'));
636
-	}
637
-
638
-	public function testWriteStream(): void {
639
-		$textFile = \OC::$SERVERROOT . '/tests/data/lorem.txt';
640
-
641
-		if (!$this->instance->instanceOfStorage(IWriteStreamStorage::class)) {
642
-			$this->markTestSkipped('Not a WriteSteamStorage');
643
-		}
644
-		/** @var IWriteStreamStorage $storage */
645
-		$storage = $this->instance;
646
-
647
-		$source = fopen($textFile, 'r');
648
-
649
-		$storage->writeStream('test.txt', $source);
650
-		$this->assertTrue($storage->file_exists('test.txt'));
651
-		$this->assertStringEqualsFile($textFile, $storage->file_get_contents('test.txt'));
652
-		$this->assertEquals('resource (closed)', gettype($source));
653
-	}
654
-
655
-	public function testFseekSize(): void {
656
-		$textFile = \OC::$SERVERROOT . '/tests/data/lorem.txt';
657
-		$this->instance->file_put_contents('bar.txt', file_get_contents($textFile));
658
-
659
-		$size = $this->instance->filesize('bar.txt');
660
-		$this->assertEquals(filesize($textFile), $size);
661
-		$fh = $this->instance->fopen('bar.txt', 'r');
662
-
663
-		fseek($fh, 0, SEEK_END);
664
-		$pos = ftell($fh);
665
-
666
-		$this->assertEquals($size, $pos);
667
-	}
15
+    /**
16
+     * @var \OC\Files\Storage\Storage instance
17
+     */
18
+    protected $instance;
19
+    protected $waitDelay = 0;
20
+
21
+    /**
22
+     * Sleep for the number of seconds specified in the
23
+     * $waitDelay attribute
24
+     */
25
+    protected function wait() {
26
+        if ($this->waitDelay > 0) {
27
+            sleep($this->waitDelay);
28
+        }
29
+    }
30
+
31
+    /**
32
+     * the root folder of the storage should always exist, be readable and be recognized as a directory
33
+     */
34
+    public function testRoot(): void {
35
+        $this->assertTrue($this->instance->file_exists('/'), 'Root folder does not exist');
36
+        $this->assertTrue($this->instance->isReadable('/'), 'Root folder is not readable');
37
+        $this->assertTrue($this->instance->is_dir('/'), 'Root folder is not a directory');
38
+        $this->assertFalse($this->instance->is_file('/'), 'Root folder is a file');
39
+        $this->assertEquals('dir', $this->instance->filetype('/'));
40
+
41
+        //without this, any further testing would be useless, not an actual requirement for filestorage though
42
+        $this->assertTrue($this->instance->isUpdatable('/'), 'Root folder is not writable');
43
+    }
44
+
45
+    /**
46
+     * Check that the test() function works
47
+     */
48
+    public function testTestFunction(): void {
49
+        $this->assertTrue($this->instance->test());
50
+    }
51
+
52
+    /**
53
+     * @dataProvider directoryProvider
54
+     */
55
+    public function testDirectories($directory): void {
56
+        $this->assertFalse($this->instance->file_exists('/' . $directory));
57
+
58
+        $this->assertTrue($this->instance->mkdir('/' . $directory));
59
+
60
+        $this->assertTrue($this->instance->file_exists('/' . $directory));
61
+        $this->assertTrue($this->instance->is_dir('/' . $directory));
62
+        $this->assertFalse($this->instance->is_file('/' . $directory));
63
+        $this->assertEquals('dir', $this->instance->filetype('/' . $directory));
64
+        $this->assertEquals(0, $this->instance->filesize('/' . $directory));
65
+        $this->assertTrue($this->instance->isReadable('/' . $directory));
66
+        $this->assertTrue($this->instance->isUpdatable('/' . $directory));
67
+
68
+        $dh = $this->instance->opendir('/');
69
+        $content = [];
70
+        while (($file = readdir($dh)) !== false) {
71
+            if ($file != '.' and $file != '..') {
72
+                $content[] = $file;
73
+            }
74
+        }
75
+        $this->assertEquals([$directory], $content);
76
+
77
+        $content = iterator_to_array($this->instance->getDirectoryContent('/'));
78
+
79
+        $this->assertCount(1, $content);
80
+        $dirEntry = $content[0];
81
+        unset($dirEntry['scan_permissions']);
82
+        unset($dirEntry['etag']);
83
+        $this->assertLessThanOrEqual(1, abs($dirEntry['mtime'] - $this->instance->filemtime($directory)));
84
+        unset($dirEntry['mtime']);
85
+        unset($dirEntry['storage_mtime']);
86
+        $this->assertEquals([
87
+            'name' => $directory,
88
+            'mimetype' => $this->instance->getMimeType($directory),
89
+            'size' => -1,
90
+            'permissions' => $this->instance->getPermissions($directory),
91
+        ], $dirEntry);
92
+
93
+        $this->assertFalse($this->instance->mkdir('/' . $directory)); //can't create existing folders
94
+        $this->assertTrue($this->instance->rmdir('/' . $directory));
95
+
96
+        $this->wait();
97
+        $this->assertFalse($this->instance->file_exists('/' . $directory));
98
+
99
+        $this->assertFalse($this->instance->rmdir('/' . $directory)); //can't remove non existing folders
100
+
101
+        $dh = $this->instance->opendir('/');
102
+        $content = [];
103
+        while (($file = readdir($dh)) !== false) {
104
+            if ($file != '.' and $file != '..') {
105
+                $content[] = $file;
106
+            }
107
+        }
108
+        $this->assertEquals([], $content);
109
+    }
110
+
111
+    public static function fileNameProvider(): array {
112
+        return [
113
+            ['file.txt'],
114
+            [' file.txt'],
115
+            ['folder .txt'],
116
+            ['file with space.txt'],
117
+            ['spéciäl fäile'],
118
+            ['test single\'quote.txt'],
119
+        ];
120
+    }
121
+
122
+    public static function directoryProvider(): array {
123
+        return [
124
+            ['folder'],
125
+            [' folder'],
126
+            ['folder '],
127
+            ['folder with space'],
128
+            ['spéciäl földer'],
129
+            ['test single\'quote'],
130
+        ];
131
+    }
132
+
133
+    public static function loremFileProvider(): array {
134
+        $root = \OC::$SERVERROOT . '/tests/data/';
135
+        return [
136
+            // small file
137
+            [$root . 'lorem.txt'],
138
+            // bigger file (> 8 KB which is the standard PHP block size)
139
+            [$root . 'lorem-big.txt']
140
+        ];
141
+    }
142
+
143
+    /**
144
+     * test the various uses of file_get_contents and file_put_contents
145
+     *
146
+     * @dataProvider loremFileProvider
147
+     */
148
+    public function testGetPutContents($sourceFile): void {
149
+        $sourceText = file_get_contents($sourceFile);
150
+
151
+        //fill a file with string data
152
+        $this->instance->file_put_contents('/lorem.txt', $sourceText);
153
+        $this->assertFalse($this->instance->is_dir('/lorem.txt'));
154
+        $this->assertEquals($sourceText, $this->instance->file_get_contents('/lorem.txt'), 'data returned from file_get_contents is not equal to the source data');
155
+
156
+        //empty the file
157
+        $this->instance->file_put_contents('/lorem.txt', '');
158
+        $this->assertEquals('', $this->instance->file_get_contents('/lorem.txt'), 'file not emptied');
159
+    }
160
+
161
+    /**
162
+     * test various known mimetypes
163
+     */
164
+    public function testMimeType(): void {
165
+        $this->assertEquals('httpd/unix-directory', $this->instance->getMimeType('/'));
166
+        $this->assertEquals(false, $this->instance->getMimeType('/non/existing/file'));
167
+
168
+        $textFile = \OC::$SERVERROOT . '/tests/data/lorem.txt';
169
+        $this->instance->file_put_contents('/lorem.txt', file_get_contents($textFile, 'r'));
170
+        $this->assertEquals('text/plain', $this->instance->getMimeType('/lorem.txt'));
171
+
172
+        $pngFile = \OC::$SERVERROOT . '/tests/data/desktopapp.png';
173
+        $this->instance->file_put_contents('/desktopapp.png', file_get_contents($pngFile, 'r'));
174
+        $this->assertEquals('image/png', $this->instance->getMimeType('/desktopapp.png'));
175
+
176
+        $svgFile = \OC::$SERVERROOT . '/tests/data/desktopapp.svg';
177
+        $this->instance->file_put_contents('/desktopapp.svg', file_get_contents($svgFile, 'r'));
178
+        $this->assertEquals('image/svg+xml', $this->instance->getMimeType('/desktopapp.svg'));
179
+    }
180
+
181
+
182
+    public static function copyAndMoveProvider(): array {
183
+        return [
184
+            ['/source.txt', '/target.txt'],
185
+            ['/source.txt', '/target with space.txt'],
186
+            ['/source with space.txt', '/target.txt'],
187
+            ['/source with space.txt', '/target with space.txt'],
188
+            ['/source.txt', '/tärgét.txt'],
189
+            ['/sòurcē.txt', '/target.txt'],
190
+            ['/sòurcē.txt', '/tärgét.txt'],
191
+            ['/single \' quote.txt', '/tar\'get.txt'],
192
+        ];
193
+    }
194
+
195
+    public function initSourceAndTarget($source, $target = null) {
196
+        $textFile = \OC::$SERVERROOT . '/tests/data/lorem.txt';
197
+        $this->instance->file_put_contents($source, file_get_contents($textFile));
198
+        if ($target) {
199
+            $testContents = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
200
+            $this->instance->file_put_contents($target, $testContents);
201
+        }
202
+    }
203
+
204
+    public function assertSameAsLorem($file) {
205
+        $textFile = \OC::$SERVERROOT . '/tests/data/lorem.txt';
206
+        $this->assertEquals(
207
+            file_get_contents($textFile),
208
+            $this->instance->file_get_contents($file),
209
+            'Expected ' . $file . ' to be a copy of ' . $textFile
210
+        );
211
+    }
212
+
213
+    /**
214
+     * @dataProvider copyAndMoveProvider
215
+     */
216
+    public function testCopy($source, $target): void {
217
+        $this->initSourceAndTarget($source);
218
+
219
+        $this->instance->copy($source, $target);
220
+
221
+        $this->assertTrue($this->instance->file_exists($target), $target . ' was not created');
222
+        $this->assertSameAsLorem($target);
223
+        $this->assertTrue($this->instance->file_exists($source), $source . ' was deleted');
224
+    }
225
+
226
+    /**
227
+     * @dataProvider copyAndMoveProvider
228
+     */
229
+    public function testMove($source, $target): void {
230
+        $this->initSourceAndTarget($source);
231
+
232
+        $this->instance->rename($source, $target);
233
+
234
+        $this->wait();
235
+        $this->assertTrue($this->instance->file_exists($target), $target . ' was not created');
236
+        $this->assertFalse($this->instance->file_exists($source), $source . ' still exists');
237
+        $this->assertSameAsLorem($target);
238
+    }
239
+
240
+    /**
241
+     * @dataProvider copyAndMoveProvider
242
+     */
243
+    public function testCopyOverwrite($source, $target): void {
244
+        $this->initSourceAndTarget($source, $target);
245
+
246
+        $this->instance->copy($source, $target);
247
+
248
+        $this->assertTrue($this->instance->file_exists($target), $target . ' was not created');
249
+        $this->assertTrue($this->instance->file_exists($source), $source . ' was deleted');
250
+        $this->assertSameAsLorem($target);
251
+        $this->assertSameAsLorem($source);
252
+    }
253
+
254
+    /**
255
+     * @dataProvider copyAndMoveProvider
256
+     */
257
+    public function testMoveOverwrite($source, $target): void {
258
+        $this->initSourceAndTarget($source, $target);
259
+
260
+        $this->instance->rename($source, $target);
261
+
262
+        $this->assertTrue($this->instance->file_exists($target), $target . ' was not created');
263
+        $this->assertFalse($this->instance->file_exists($source), $source . ' still exists');
264
+        $this->assertSameAsLorem($target);
265
+    }
266
+
267
+    public function testLocal(): void {
268
+        $textFile = \OC::$SERVERROOT . '/tests/data/lorem.txt';
269
+        $this->instance->file_put_contents('/lorem.txt', file_get_contents($textFile));
270
+        $localFile = $this->instance->getLocalFile('/lorem.txt');
271
+        $this->assertTrue(file_exists($localFile));
272
+        $this->assertEquals(file_get_contents($textFile), file_get_contents($localFile));
273
+
274
+        $this->instance->mkdir('/folder');
275
+        $this->instance->file_put_contents('/folder/lorem.txt', file_get_contents($textFile));
276
+        $this->instance->file_put_contents('/folder/bar.txt', 'asd');
277
+        $this->instance->mkdir('/folder/recursive');
278
+        $this->instance->file_put_contents('/folder/recursive/file.txt', 'foo');
279
+
280
+        // test below require to use instance->getLocalFile because the physical storage might be different
281
+        $localFile = $this->instance->getLocalFile('/folder/lorem.txt');
282
+        $this->assertTrue(file_exists($localFile));
283
+        $this->assertEquals(file_get_contents($localFile), file_get_contents($textFile));
284
+
285
+        $localFile = $this->instance->getLocalFile('/folder/bar.txt');
286
+        $this->assertTrue(file_exists($localFile));
287
+        $this->assertEquals(file_get_contents($localFile), 'asd');
288
+
289
+        $localFile = $this->instance->getLocalFile('/folder/recursive/file.txt');
290
+        $this->assertTrue(file_exists($localFile));
291
+        $this->assertEquals(file_get_contents($localFile), 'foo');
292
+    }
293
+
294
+    public function testStat(): void {
295
+        $textFile = \OC::$SERVERROOT . '/tests/data/lorem.txt';
296
+        $ctimeStart = time();
297
+        $this->instance->file_put_contents('/lorem.txt', file_get_contents($textFile));
298
+        $this->assertTrue($this->instance->isReadable('/lorem.txt'));
299
+        $ctimeEnd = time();
300
+        $mTime = $this->instance->filemtime('/lorem.txt');
301
+        $this->assertTrue($this->instance->hasUpdated('/lorem.txt', $ctimeStart - 5));
302
+        $this->assertTrue($this->instance->hasUpdated('/', $ctimeStart - 5));
303
+
304
+        // check that ($ctimeStart - 5) <= $mTime <= ($ctimeEnd + 1)
305
+        $this->assertGreaterThanOrEqual(($ctimeStart - 5), $mTime);
306
+        $this->assertLessThanOrEqual(($ctimeEnd + 1), $mTime);
307
+        $this->assertEquals(filesize($textFile), $this->instance->filesize('/lorem.txt'));
308
+
309
+        $stat = $this->instance->stat('/lorem.txt');
310
+        //only size and mtime are required in the result
311
+        $this->assertEquals($stat['size'], $this->instance->filesize('/lorem.txt'));
312
+        $this->assertEquals($stat['mtime'], $mTime);
313
+
314
+        if ($this->instance->touch('/lorem.txt', 100) !== false) {
315
+            $mTime = $this->instance->filemtime('/lorem.txt');
316
+            $this->assertEquals($mTime, 100);
317
+        }
318
+
319
+        $mtimeStart = time();
320
+
321
+        $this->instance->unlink('/lorem.txt');
322
+        $this->assertTrue($this->instance->hasUpdated('/', $mtimeStart - 5));
323
+    }
324
+
325
+    /**
326
+     * Test whether checkUpdate properly returns false when there was
327
+     * no change.
328
+     */
329
+    public function testCheckUpdate(): void {
330
+        if ($this->instance instanceof \OC\Files\Storage\Wrapper\Wrapper) {
331
+            $this->markTestSkipped('Cannot test update check on wrappers');
332
+        }
333
+        $textFile = \OC::$SERVERROOT . '/tests/data/lorem.txt';
334
+        $watcher = $this->instance->getWatcher();
335
+        $watcher->setPolicy(Watcher::CHECK_ALWAYS);
336
+        $this->instance->file_put_contents('/lorem.txt', file_get_contents($textFile));
337
+        $this->assertTrue($watcher->checkUpdate('/lorem.txt'), 'Update detected');
338
+        $this->assertFalse($watcher->checkUpdate('/lorem.txt'), 'No update');
339
+    }
340
+
341
+    public function testUnlink(): void {
342
+        $textFile = \OC::$SERVERROOT . '/tests/data/lorem.txt';
343
+        $this->instance->file_put_contents('/lorem.txt', file_get_contents($textFile));
344
+
345
+        $this->assertTrue($this->instance->file_exists('/lorem.txt'));
346
+
347
+        $this->assertTrue($this->instance->unlink('/lorem.txt'));
348
+        $this->wait();
349
+
350
+        $this->assertFalse($this->instance->file_exists('/lorem.txt'));
351
+    }
352
+
353
+    /**
354
+     * @dataProvider fileNameProvider
355
+     */
356
+    public function testFOpen($fileName): void {
357
+        $textFile = \OC::$SERVERROOT . '/tests/data/lorem.txt';
358
+
359
+        $fh = @$this->instance->fopen($fileName, 'r');
360
+        if ($fh) {
361
+            fclose($fh);
362
+        }
363
+        $this->assertFalse($fh);
364
+        $this->assertFalse($this->instance->file_exists($fileName));
365
+
366
+        $fh = $this->instance->fopen($fileName, 'w');
367
+        fwrite($fh, file_get_contents($textFile));
368
+        fclose($fh);
369
+        $this->assertTrue($this->instance->file_exists($fileName));
370
+
371
+        $fh = $this->instance->fopen($fileName, 'r');
372
+        $content = stream_get_contents($fh);
373
+        $this->assertEquals(file_get_contents($textFile), $content);
374
+    }
375
+
376
+    public function testTouchCreateFile(): void {
377
+        $this->assertFalse($this->instance->file_exists('touch'));
378
+        // returns true on success
379
+        $this->assertTrue($this->instance->touch('touch'));
380
+        $this->assertTrue($this->instance->file_exists('touch'));
381
+    }
382
+
383
+    public function testRecursiveRmdir(): void {
384
+        $this->instance->mkdir('folder');
385
+        $this->instance->mkdir('folder/bar');
386
+        $this->wait();
387
+        $this->instance->file_put_contents('folder/asd.txt', 'foobar');
388
+        $this->instance->file_put_contents('folder/bar/foo.txt', 'asd');
389
+        $this->assertTrue($this->instance->rmdir('folder'));
390
+        $this->wait();
391
+        $this->assertFalse($this->instance->file_exists('folder/asd.txt'));
392
+        $this->assertFalse($this->instance->file_exists('folder/bar/foo.txt'));
393
+        $this->assertFalse($this->instance->file_exists('folder/bar'));
394
+        $this->assertFalse($this->instance->file_exists('folder'));
395
+    }
396
+
397
+    public function testRmdirEmptyFolder(): void {
398
+        $this->assertTrue($this->instance->mkdir('empty'));
399
+        $this->wait();
400
+        $this->assertTrue($this->instance->rmdir('empty'));
401
+        $this->assertFalse($this->instance->file_exists('empty'));
402
+    }
403
+
404
+    public function testRecursiveUnlink(): void {
405
+        $this->instance->mkdir('folder');
406
+        $this->instance->mkdir('folder/bar');
407
+        $this->instance->file_put_contents('folder/asd.txt', 'foobar');
408
+        $this->instance->file_put_contents('folder/bar/foo.txt', 'asd');
409
+        $this->assertTrue($this->instance->unlink('folder'));
410
+        $this->wait();
411
+        $this->assertFalse($this->instance->file_exists('folder/asd.txt'));
412
+        $this->assertFalse($this->instance->file_exists('folder/bar/foo.txt'));
413
+        $this->assertFalse($this->instance->file_exists('folder/bar'));
414
+        $this->assertFalse($this->instance->file_exists('folder'));
415
+    }
416
+
417
+    public static function hashProvider(): array {
418
+        return [
419
+            ['Foobar', 'md5'],
420
+            ['Foobar', 'sha1'],
421
+            ['Foobar', 'sha256'],
422
+        ];
423
+    }
424
+
425
+    /**
426
+     * @dataProvider hashProvider
427
+     */
428
+    public function testHash($data, $type): void {
429
+        $this->instance->file_put_contents('hash.txt', $data);
430
+        $this->assertEquals(hash($type, $data), $this->instance->hash($type, 'hash.txt'));
431
+        $this->assertEquals(hash($type, $data, true), $this->instance->hash($type, 'hash.txt', true));
432
+    }
433
+
434
+    public function testHashInFileName(): void {
435
+        $this->instance->file_put_contents('#test.txt', 'data');
436
+        $this->assertEquals('data', $this->instance->file_get_contents('#test.txt'));
437
+
438
+        $this->instance->mkdir('#foo');
439
+        $this->instance->file_put_contents('#foo/test.txt', 'data');
440
+        $this->assertEquals('data', $this->instance->file_get_contents('#foo/test.txt'));
441
+
442
+        $dh = $this->instance->opendir('#foo');
443
+        $content = [];
444
+        while ($file = readdir($dh)) {
445
+            if ($file != '.' and $file != '..') {
446
+                $content[] = $file;
447
+            }
448
+        }
449
+
450
+        $this->assertEquals(['test.txt'], $content);
451
+    }
452
+
453
+    public function testCopyOverWriteFile(): void {
454
+        $this->instance->file_put_contents('target.txt', 'foo');
455
+        $this->instance->file_put_contents('source.txt', 'bar');
456
+        $this->instance->copy('source.txt', 'target.txt');
457
+        $this->assertEquals('bar', $this->instance->file_get_contents('target.txt'));
458
+    }
459
+
460
+    public function testRenameOverWriteFile(): void {
461
+        $this->instance->file_put_contents('target.txt', 'foo');
462
+        $this->instance->file_put_contents('source.txt', 'bar');
463
+        $this->instance->rename('source.txt', 'target.txt');
464
+        $this->assertEquals('bar', $this->instance->file_get_contents('target.txt'));
465
+        $this->assertFalse($this->instance->file_exists('source.txt'));
466
+    }
467
+
468
+    public function testRenameDirectory(): void {
469
+        $this->instance->mkdir('source');
470
+        $this->instance->file_put_contents('source/test1.txt', 'foo');
471
+        $this->instance->file_put_contents('source/test2.txt', 'qwerty');
472
+        $this->instance->mkdir('source/subfolder');
473
+        $this->instance->file_put_contents('source/subfolder/test.txt', 'bar');
474
+        $this->instance->rename('source', 'target');
475
+
476
+        $this->assertFalse($this->instance->file_exists('source'));
477
+        $this->assertFalse($this->instance->file_exists('source/test1.txt'));
478
+        $this->assertFalse($this->instance->file_exists('source/test2.txt'));
479
+        $this->assertFalse($this->instance->file_exists('source/subfolder'));
480
+        $this->assertFalse($this->instance->file_exists('source/subfolder/test.txt'));
481
+
482
+        $this->assertTrue($this->instance->file_exists('target'));
483
+        $this->assertTrue($this->instance->file_exists('target/test1.txt'));
484
+        $this->assertTrue($this->instance->file_exists('target/test2.txt'));
485
+        $this->assertTrue($this->instance->file_exists('target/subfolder'));
486
+        $this->assertTrue($this->instance->file_exists('target/subfolder/test.txt'));
487
+
488
+        $contents = iterator_to_array($this->instance->getDirectoryContent(''));
489
+        $this->assertCount(1, $contents);
490
+
491
+        $this->assertEquals('foo', $this->instance->file_get_contents('target/test1.txt'));
492
+        $this->assertEquals('qwerty', $this->instance->file_get_contents('target/test2.txt'));
493
+        $this->assertEquals('bar', $this->instance->file_get_contents('target/subfolder/test.txt'));
494
+    }
495
+
496
+    public function testRenameOverWriteDirectory(): void {
497
+        $this->instance->mkdir('source');
498
+        $this->instance->file_put_contents('source/test1.txt', 'foo');
499
+
500
+        $this->instance->mkdir('target');
501
+        $this->instance->file_put_contents('target/test1.txt', 'bar');
502
+        $this->instance->file_put_contents('target/test2.txt', 'bar');
503
+
504
+        $this->assertTrue($this->instance->rename('source', 'target'), 'rename must return true on success');
505
+
506
+        $this->assertFalse($this->instance->file_exists('source'), 'source has not been removed');
507
+        $this->assertFalse($this->instance->file_exists('source/test1.txt'), 'source/test1.txt has not been removed');
508
+        $this->assertFalse($this->instance->file_exists('target/test2.txt'), 'target/test2.txt has not been removed');
509
+        $this->assertEquals('foo', $this->instance->file_get_contents('target/test1.txt'), 'target/test1.txt has not been overwritten');
510
+    }
511
+
512
+    public function testRenameOverWriteDirectoryOverFile(): void {
513
+        $this->instance->mkdir('source');
514
+        $this->instance->file_put_contents('source/test1.txt', 'foo');
515
+
516
+        $this->instance->file_put_contents('target', 'bar');
517
+
518
+        $this->assertTrue($this->instance->rename('source', 'target'), 'rename must return true on success');
519
+
520
+        $this->assertFalse($this->instance->file_exists('source'));
521
+        $this->assertFalse($this->instance->file_exists('source/test1.txt'));
522
+        $this->assertEquals('foo', $this->instance->file_get_contents('target/test1.txt'));
523
+    }
524
+
525
+    public function testCopyDirectory(): void {
526
+        $this->instance->mkdir('source');
527
+        $this->instance->file_put_contents('source/test1.txt', 'foo');
528
+        $this->instance->file_put_contents('source/test2.txt', 'qwerty');
529
+        $this->instance->mkdir('source/subfolder');
530
+        $this->instance->file_put_contents('source/subfolder/test.txt', 'bar');
531
+        $this->instance->copy('source', 'target');
532
+
533
+        $this->assertTrue($this->instance->file_exists('source'));
534
+        $this->assertTrue($this->instance->file_exists('source/test1.txt'));
535
+        $this->assertTrue($this->instance->file_exists('source/test2.txt'));
536
+        $this->assertTrue($this->instance->file_exists('source/subfolder'));
537
+        $this->assertTrue($this->instance->file_exists('source/subfolder/test.txt'));
538
+
539
+        $this->assertTrue($this->instance->file_exists('target'));
540
+        $this->assertTrue($this->instance->file_exists('target/test1.txt'));
541
+        $this->assertTrue($this->instance->file_exists('target/test2.txt'));
542
+        $this->assertTrue($this->instance->file_exists('target/subfolder'));
543
+        $this->assertTrue($this->instance->file_exists('target/subfolder/test.txt'));
544
+
545
+        $this->assertEquals('foo', $this->instance->file_get_contents('target/test1.txt'));
546
+        $this->assertEquals('qwerty', $this->instance->file_get_contents('target/test2.txt'));
547
+        $this->assertEquals('bar', $this->instance->file_get_contents('target/subfolder/test.txt'));
548
+    }
549
+
550
+    public function testCopyOverWriteDirectory(): void {
551
+        $this->instance->mkdir('source');
552
+        $this->instance->file_put_contents('source/test1.txt', 'foo');
553
+
554
+        $this->instance->mkdir('target');
555
+        $this->instance->file_put_contents('target/test1.txt', 'bar');
556
+        $this->instance->file_put_contents('target/test2.txt', 'bar');
557
+
558
+        $this->instance->copy('source', 'target');
559
+
560
+        $this->assertFalse($this->instance->file_exists('target/test2.txt'));
561
+        $this->assertEquals('foo', $this->instance->file_get_contents('target/test1.txt'));
562
+    }
563
+
564
+    public function testCopyOverWriteDirectoryOverFile(): void {
565
+        $this->instance->mkdir('source');
566
+        $this->instance->file_put_contents('source/test1.txt', 'foo');
567
+
568
+        $this->instance->file_put_contents('target', 'bar');
569
+
570
+        $this->instance->copy('source', 'target');
571
+
572
+        $this->assertEquals('foo', $this->instance->file_get_contents('target/test1.txt'));
573
+    }
574
+
575
+    public function testInstanceOfStorage(): void {
576
+        $this->assertTrue($this->instance->instanceOfStorage(IStorage::class));
577
+        $this->assertTrue($this->instance->instanceOfStorage(get_class($this->instance)));
578
+        $this->assertFalse($this->instance->instanceOfStorage('\OC'));
579
+    }
580
+
581
+    /**
582
+     * @dataProvider copyAndMoveProvider
583
+     */
584
+    public function testCopyFromSameStorage($source, $target): void {
585
+        $this->initSourceAndTarget($source);
586
+
587
+        $this->instance->copyFromStorage($this->instance, $source, $target);
588
+
589
+        $this->assertTrue($this->instance->file_exists($target), $target . ' was not created');
590
+        $this->assertSameAsLorem($target);
591
+        $this->assertTrue($this->instance->file_exists($source), $source . ' was deleted');
592
+    }
593
+
594
+    public function testIsCreatable(): void {
595
+        $this->instance->mkdir('source');
596
+        $this->assertTrue($this->instance->isCreatable('source'));
597
+    }
598
+
599
+    public function testIsReadable(): void {
600
+        $this->instance->mkdir('source');
601
+        $this->assertTrue($this->instance->isReadable('source'));
602
+    }
603
+
604
+    public function testIsUpdatable(): void {
605
+        $this->instance->mkdir('source');
606
+        $this->assertTrue($this->instance->isUpdatable('source'));
607
+    }
608
+
609
+    public function testIsDeletable(): void {
610
+        $this->instance->mkdir('source');
611
+        $this->assertTrue($this->instance->isDeletable('source'));
612
+    }
613
+
614
+    public function testIsShareable(): void {
615
+        $this->instance->mkdir('source');
616
+        $this->assertTrue($this->instance->isSharable('source'));
617
+    }
618
+
619
+    public function testStatAfterWrite(): void {
620
+        $this->instance->file_put_contents('foo.txt', 'bar');
621
+        $stat = $this->instance->stat('foo.txt');
622
+        $this->assertEquals(3, $stat['size']);
623
+
624
+        $fh = $this->instance->fopen('foo.txt', 'w');
625
+        fwrite($fh, 'qwerty');
626
+        fclose($fh);
627
+
628
+        $stat = $this->instance->stat('foo.txt');
629
+        $this->assertEquals(6, $stat['size']);
630
+    }
631
+
632
+    public function testPartFile(): void {
633
+        $this->instance->file_put_contents('bar.txt.part', 'bar');
634
+        $this->instance->rename('bar.txt.part', 'bar.txt');
635
+        $this->assertEquals('bar', $this->instance->file_get_contents('bar.txt'));
636
+    }
637
+
638
+    public function testWriteStream(): void {
639
+        $textFile = \OC::$SERVERROOT . '/tests/data/lorem.txt';
640
+
641
+        if (!$this->instance->instanceOfStorage(IWriteStreamStorage::class)) {
642
+            $this->markTestSkipped('Not a WriteSteamStorage');
643
+        }
644
+        /** @var IWriteStreamStorage $storage */
645
+        $storage = $this->instance;
646
+
647
+        $source = fopen($textFile, 'r');
648
+
649
+        $storage->writeStream('test.txt', $source);
650
+        $this->assertTrue($storage->file_exists('test.txt'));
651
+        $this->assertStringEqualsFile($textFile, $storage->file_get_contents('test.txt'));
652
+        $this->assertEquals('resource (closed)', gettype($source));
653
+    }
654
+
655
+    public function testFseekSize(): void {
656
+        $textFile = \OC::$SERVERROOT . '/tests/data/lorem.txt';
657
+        $this->instance->file_put_contents('bar.txt', file_get_contents($textFile));
658
+
659
+        $size = $this->instance->filesize('bar.txt');
660
+        $this->assertEquals(filesize($textFile), $size);
661
+        $fh = $this->instance->fopen('bar.txt', 'r');
662
+
663
+        fseek($fh, 0, SEEK_END);
664
+        $pos = ftell($fh);
665
+
666
+        $this->assertEquals($size, $pos);
667
+    }
668 668
 }
Please login to merge, or discard this patch.
Spacing   +39 added lines, -39 removed lines patch added patch discarded remove patch
@@ -53,17 +53,17 @@  discard block
 block discarded – undo
53 53
 	 * @dataProvider directoryProvider
54 54
 	 */
55 55
 	public function testDirectories($directory): void {
56
-		$this->assertFalse($this->instance->file_exists('/' . $directory));
56
+		$this->assertFalse($this->instance->file_exists('/'.$directory));
57 57
 
58
-		$this->assertTrue($this->instance->mkdir('/' . $directory));
58
+		$this->assertTrue($this->instance->mkdir('/'.$directory));
59 59
 
60
-		$this->assertTrue($this->instance->file_exists('/' . $directory));
61
-		$this->assertTrue($this->instance->is_dir('/' . $directory));
62
-		$this->assertFalse($this->instance->is_file('/' . $directory));
63
-		$this->assertEquals('dir', $this->instance->filetype('/' . $directory));
64
-		$this->assertEquals(0, $this->instance->filesize('/' . $directory));
65
-		$this->assertTrue($this->instance->isReadable('/' . $directory));
66
-		$this->assertTrue($this->instance->isUpdatable('/' . $directory));
60
+		$this->assertTrue($this->instance->file_exists('/'.$directory));
61
+		$this->assertTrue($this->instance->is_dir('/'.$directory));
62
+		$this->assertFalse($this->instance->is_file('/'.$directory));
63
+		$this->assertEquals('dir', $this->instance->filetype('/'.$directory));
64
+		$this->assertEquals(0, $this->instance->filesize('/'.$directory));
65
+		$this->assertTrue($this->instance->isReadable('/'.$directory));
66
+		$this->assertTrue($this->instance->isUpdatable('/'.$directory));
67 67
 
68 68
 		$dh = $this->instance->opendir('/');
69 69
 		$content = [];
@@ -90,13 +90,13 @@  discard block
 block discarded – undo
90 90
 			'permissions' => $this->instance->getPermissions($directory),
91 91
 		], $dirEntry);
92 92
 
93
-		$this->assertFalse($this->instance->mkdir('/' . $directory)); //can't create existing folders
94
-		$this->assertTrue($this->instance->rmdir('/' . $directory));
93
+		$this->assertFalse($this->instance->mkdir('/'.$directory)); //can't create existing folders
94
+		$this->assertTrue($this->instance->rmdir('/'.$directory));
95 95
 
96 96
 		$this->wait();
97
-		$this->assertFalse($this->instance->file_exists('/' . $directory));
97
+		$this->assertFalse($this->instance->file_exists('/'.$directory));
98 98
 
99
-		$this->assertFalse($this->instance->rmdir('/' . $directory)); //can't remove non existing folders
99
+		$this->assertFalse($this->instance->rmdir('/'.$directory)); //can't remove non existing folders
100 100
 
101 101
 		$dh = $this->instance->opendir('/');
102 102
 		$content = [];
@@ -131,12 +131,12 @@  discard block
 block discarded – undo
131 131
 	}
132 132
 
133 133
 	public static function loremFileProvider(): array {
134
-		$root = \OC::$SERVERROOT . '/tests/data/';
134
+		$root = \OC::$SERVERROOT.'/tests/data/';
135 135
 		return [
136 136
 			// small file
137
-			[$root . 'lorem.txt'],
137
+			[$root.'lorem.txt'],
138 138
 			// bigger file (> 8 KB which is the standard PHP block size)
139
-			[$root . 'lorem-big.txt']
139
+			[$root.'lorem-big.txt']
140 140
 		];
141 141
 	}
142 142
 
@@ -165,15 +165,15 @@  discard block
 block discarded – undo
165 165
 		$this->assertEquals('httpd/unix-directory', $this->instance->getMimeType('/'));
166 166
 		$this->assertEquals(false, $this->instance->getMimeType('/non/existing/file'));
167 167
 
168
-		$textFile = \OC::$SERVERROOT . '/tests/data/lorem.txt';
168
+		$textFile = \OC::$SERVERROOT.'/tests/data/lorem.txt';
169 169
 		$this->instance->file_put_contents('/lorem.txt', file_get_contents($textFile, 'r'));
170 170
 		$this->assertEquals('text/plain', $this->instance->getMimeType('/lorem.txt'));
171 171
 
172
-		$pngFile = \OC::$SERVERROOT . '/tests/data/desktopapp.png';
172
+		$pngFile = \OC::$SERVERROOT.'/tests/data/desktopapp.png';
173 173
 		$this->instance->file_put_contents('/desktopapp.png', file_get_contents($pngFile, 'r'));
174 174
 		$this->assertEquals('image/png', $this->instance->getMimeType('/desktopapp.png'));
175 175
 
176
-		$svgFile = \OC::$SERVERROOT . '/tests/data/desktopapp.svg';
176
+		$svgFile = \OC::$SERVERROOT.'/tests/data/desktopapp.svg';
177 177
 		$this->instance->file_put_contents('/desktopapp.svg', file_get_contents($svgFile, 'r'));
178 178
 		$this->assertEquals('image/svg+xml', $this->instance->getMimeType('/desktopapp.svg'));
179 179
 	}
@@ -193,7 +193,7 @@  discard block
 block discarded – undo
193 193
 	}
194 194
 
195 195
 	public function initSourceAndTarget($source, $target = null) {
196
-		$textFile = \OC::$SERVERROOT . '/tests/data/lorem.txt';
196
+		$textFile = \OC::$SERVERROOT.'/tests/data/lorem.txt';
197 197
 		$this->instance->file_put_contents($source, file_get_contents($textFile));
198 198
 		if ($target) {
199 199
 			$testContents = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
@@ -202,11 +202,11 @@  discard block
 block discarded – undo
202 202
 	}
203 203
 
204 204
 	public function assertSameAsLorem($file) {
205
-		$textFile = \OC::$SERVERROOT . '/tests/data/lorem.txt';
205
+		$textFile = \OC::$SERVERROOT.'/tests/data/lorem.txt';
206 206
 		$this->assertEquals(
207 207
 			file_get_contents($textFile),
208 208
 			$this->instance->file_get_contents($file),
209
-			'Expected ' . $file . ' to be a copy of ' . $textFile
209
+			'Expected '.$file.' to be a copy of '.$textFile
210 210
 		);
211 211
 	}
212 212
 
@@ -218,9 +218,9 @@  discard block
 block discarded – undo
218 218
 
219 219
 		$this->instance->copy($source, $target);
220 220
 
221
-		$this->assertTrue($this->instance->file_exists($target), $target . ' was not created');
221
+		$this->assertTrue($this->instance->file_exists($target), $target.' was not created');
222 222
 		$this->assertSameAsLorem($target);
223
-		$this->assertTrue($this->instance->file_exists($source), $source . ' was deleted');
223
+		$this->assertTrue($this->instance->file_exists($source), $source.' was deleted');
224 224
 	}
225 225
 
226 226
 	/**
@@ -232,8 +232,8 @@  discard block
 block discarded – undo
232 232
 		$this->instance->rename($source, $target);
233 233
 
234 234
 		$this->wait();
235
-		$this->assertTrue($this->instance->file_exists($target), $target . ' was not created');
236
-		$this->assertFalse($this->instance->file_exists($source), $source . ' still exists');
235
+		$this->assertTrue($this->instance->file_exists($target), $target.' was not created');
236
+		$this->assertFalse($this->instance->file_exists($source), $source.' still exists');
237 237
 		$this->assertSameAsLorem($target);
238 238
 	}
239 239
 
@@ -245,8 +245,8 @@  discard block
 block discarded – undo
245 245
 
246 246
 		$this->instance->copy($source, $target);
247 247
 
248
-		$this->assertTrue($this->instance->file_exists($target), $target . ' was not created');
249
-		$this->assertTrue($this->instance->file_exists($source), $source . ' was deleted');
248
+		$this->assertTrue($this->instance->file_exists($target), $target.' was not created');
249
+		$this->assertTrue($this->instance->file_exists($source), $source.' was deleted');
250 250
 		$this->assertSameAsLorem($target);
251 251
 		$this->assertSameAsLorem($source);
252 252
 	}
@@ -259,13 +259,13 @@  discard block
 block discarded – undo
259 259
 
260 260
 		$this->instance->rename($source, $target);
261 261
 
262
-		$this->assertTrue($this->instance->file_exists($target), $target . ' was not created');
263
-		$this->assertFalse($this->instance->file_exists($source), $source . ' still exists');
262
+		$this->assertTrue($this->instance->file_exists($target), $target.' was not created');
263
+		$this->assertFalse($this->instance->file_exists($source), $source.' still exists');
264 264
 		$this->assertSameAsLorem($target);
265 265
 	}
266 266
 
267 267
 	public function testLocal(): void {
268
-		$textFile = \OC::$SERVERROOT . '/tests/data/lorem.txt';
268
+		$textFile = \OC::$SERVERROOT.'/tests/data/lorem.txt';
269 269
 		$this->instance->file_put_contents('/lorem.txt', file_get_contents($textFile));
270 270
 		$localFile = $this->instance->getLocalFile('/lorem.txt');
271 271
 		$this->assertTrue(file_exists($localFile));
@@ -292,7 +292,7 @@  discard block
 block discarded – undo
292 292
 	}
293 293
 
294 294
 	public function testStat(): void {
295
-		$textFile = \OC::$SERVERROOT . '/tests/data/lorem.txt';
295
+		$textFile = \OC::$SERVERROOT.'/tests/data/lorem.txt';
296 296
 		$ctimeStart = time();
297 297
 		$this->instance->file_put_contents('/lorem.txt', file_get_contents($textFile));
298 298
 		$this->assertTrue($this->instance->isReadable('/lorem.txt'));
@@ -330,7 +330,7 @@  discard block
 block discarded – undo
330 330
 		if ($this->instance instanceof \OC\Files\Storage\Wrapper\Wrapper) {
331 331
 			$this->markTestSkipped('Cannot test update check on wrappers');
332 332
 		}
333
-		$textFile = \OC::$SERVERROOT . '/tests/data/lorem.txt';
333
+		$textFile = \OC::$SERVERROOT.'/tests/data/lorem.txt';
334 334
 		$watcher = $this->instance->getWatcher();
335 335
 		$watcher->setPolicy(Watcher::CHECK_ALWAYS);
336 336
 		$this->instance->file_put_contents('/lorem.txt', file_get_contents($textFile));
@@ -339,7 +339,7 @@  discard block
 block discarded – undo
339 339
 	}
340 340
 
341 341
 	public function testUnlink(): void {
342
-		$textFile = \OC::$SERVERROOT . '/tests/data/lorem.txt';
342
+		$textFile = \OC::$SERVERROOT.'/tests/data/lorem.txt';
343 343
 		$this->instance->file_put_contents('/lorem.txt', file_get_contents($textFile));
344 344
 
345 345
 		$this->assertTrue($this->instance->file_exists('/lorem.txt'));
@@ -354,7 +354,7 @@  discard block
 block discarded – undo
354 354
 	 * @dataProvider fileNameProvider
355 355
 	 */
356 356
 	public function testFOpen($fileName): void {
357
-		$textFile = \OC::$SERVERROOT . '/tests/data/lorem.txt';
357
+		$textFile = \OC::$SERVERROOT.'/tests/data/lorem.txt';
358 358
 
359 359
 		$fh = @$this->instance->fopen($fileName, 'r');
360 360
 		if ($fh) {
@@ -586,9 +586,9 @@  discard block
 block discarded – undo
586 586
 
587 587
 		$this->instance->copyFromStorage($this->instance, $source, $target);
588 588
 
589
-		$this->assertTrue($this->instance->file_exists($target), $target . ' was not created');
589
+		$this->assertTrue($this->instance->file_exists($target), $target.' was not created');
590 590
 		$this->assertSameAsLorem($target);
591
-		$this->assertTrue($this->instance->file_exists($source), $source . ' was deleted');
591
+		$this->assertTrue($this->instance->file_exists($source), $source.' was deleted');
592 592
 	}
593 593
 
594 594
 	public function testIsCreatable(): void {
@@ -636,7 +636,7 @@  discard block
 block discarded – undo
636 636
 	}
637 637
 
638 638
 	public function testWriteStream(): void {
639
-		$textFile = \OC::$SERVERROOT . '/tests/data/lorem.txt';
639
+		$textFile = \OC::$SERVERROOT.'/tests/data/lorem.txt';
640 640
 
641 641
 		if (!$this->instance->instanceOfStorage(IWriteStreamStorage::class)) {
642 642
 			$this->markTestSkipped('Not a WriteSteamStorage');
@@ -653,7 +653,7 @@  discard block
 block discarded – undo
653 653
 	}
654 654
 
655 655
 	public function testFseekSize(): void {
656
-		$textFile = \OC::$SERVERROOT . '/tests/data/lorem.txt';
656
+		$textFile = \OC::$SERVERROOT.'/tests/data/lorem.txt';
657 657
 		$this->instance->file_put_contents('bar.txt', file_get_contents($textFile));
658 658
 
659 659
 		$size = $this->instance->filesize('bar.txt');
Please login to merge, or discard this patch.
tests/lib/Files/Storage/Wrapper/EncodingTest.php 2 patches
Indentation   +239 added lines, -239 removed lines patch added patch discarded remove patch
@@ -8,244 +8,244 @@
 block discarded – undo
8 8
 namespace Test\Files\Storage\Wrapper;
9 9
 
10 10
 class EncodingTest extends \Test\Files\Storage\Storage {
11
-	public const NFD_NAME = 'ümlaut';
12
-	public const NFC_NAME = 'ümlaut';
13
-
14
-	/**
15
-	 * @var \OC\Files\Storage\Temporary
16
-	 */
17
-	private $sourceStorage;
18
-
19
-	protected function setUp(): void {
20
-		parent::setUp();
21
-		$this->sourceStorage = new \OC\Files\Storage\Temporary([]);
22
-		$this->instance = new \OC\Files\Storage\Wrapper\Encoding([
23
-			'storage' => $this->sourceStorage
24
-		]);
25
-	}
26
-
27
-	protected function tearDown(): void {
28
-		$this->sourceStorage->cleanUp();
29
-		parent::tearDown();
30
-	}
31
-
32
-	public static function directoryProvider(): array {
33
-		$a = parent::directoryProvider();
34
-		$a[] = [self::NFC_NAME];
35
-		return $a;
36
-	}
37
-
38
-	public static function fileNameProvider(): array {
39
-		$a = parent::fileNameProvider();
40
-		$a[] = [self::NFD_NAME . '.txt'];
41
-		return $a;
42
-	}
43
-
44
-	public static function copyAndMoveProvider(): array {
45
-		$a = parent::copyAndMoveProvider();
46
-		$a[] = [self::NFD_NAME . '.txt', self::NFC_NAME . '-renamed.txt'];
47
-		return $a;
48
-	}
49
-
50
-	public static function accessNameProvider(): array {
51
-		return [
52
-			[self::NFD_NAME],
53
-			[self::NFC_NAME],
54
-		];
55
-	}
56
-
57
-	/**
58
-	 * @dataProvider accessNameProvider
59
-	 */
60
-	public function testFputEncoding($accessName): void {
61
-		$this->sourceStorage->file_put_contents(self::NFD_NAME, 'bar');
62
-		$this->assertEquals('bar', $this->instance->file_get_contents($accessName));
63
-	}
64
-
65
-	/**
66
-	 * @dataProvider accessNameProvider
67
-	 */
68
-	public function testFopenReadEncoding($accessName): void {
69
-		$this->sourceStorage->file_put_contents(self::NFD_NAME, 'bar');
70
-		$fh = $this->instance->fopen($accessName, 'r');
71
-		$data = fgets($fh);
72
-		fclose($fh);
73
-		$this->assertEquals('bar', $data);
74
-	}
75
-
76
-	/**
77
-	 * @dataProvider accessNameProvider
78
-	 */
79
-	public function testFopenOverwriteEncoding($accessName): void {
80
-		$this->sourceStorage->file_put_contents(self::NFD_NAME, 'bar');
81
-		$fh = $this->instance->fopen($accessName, 'w');
82
-		$data = fputs($fh, 'test');
83
-		fclose($fh);
84
-		$data = $this->sourceStorage->file_get_contents(self::NFD_NAME);
85
-		$this->assertEquals('test', $data);
86
-		$this->assertFalse($this->sourceStorage->file_exists(self::NFC_NAME));
87
-	}
88
-
89
-	/**
90
-	 * @dataProvider accessNameProvider
91
-	 */
92
-	public function testFileExistsEncoding($accessName): void {
93
-		$this->sourceStorage->file_put_contents(self::NFD_NAME, 'bar');
94
-		$this->assertTrue($this->instance->file_exists($accessName));
95
-	}
96
-
97
-	/**
98
-	 * @dataProvider accessNameProvider
99
-	 */
100
-	public function testUnlinkEncoding($accessName): void {
101
-		$this->sourceStorage->file_put_contents(self::NFD_NAME, 'bar');
102
-		$this->assertTrue($this->instance->unlink($accessName));
103
-		$this->assertFalse($this->sourceStorage->file_exists(self::NFC_NAME));
104
-		$this->assertFalse($this->sourceStorage->file_exists(self::NFD_NAME));
105
-	}
106
-
107
-	public function testNfcHigherPriority(): void {
108
-		$this->sourceStorage->file_put_contents(self::NFC_NAME, 'nfc');
109
-		$this->sourceStorage->file_put_contents(self::NFD_NAME, 'nfd');
110
-		$this->assertEquals('nfc', $this->instance->file_get_contents(self::NFC_NAME));
111
-	}
112
-
113
-	public static function encodedDirectoriesProvider(): array {
114
-		return [
115
-			[self::NFD_NAME, self::NFC_NAME],
116
-			[self::NFD_NAME . '/' . self::NFD_NAME, self::NFC_NAME . '/' . self::NFC_NAME],
117
-			[self::NFD_NAME . '/' . self::NFC_NAME . '/' . self::NFD_NAME, self::NFC_NAME . '/' . self::NFC_NAME . '/' . self::NFC_NAME],
118
-		];
119
-	}
120
-
121
-	/**
122
-	 * @dataProvider encodedDirectoriesProvider
123
-	 */
124
-	public function testOperationInsideDirectory($sourceDir, $accessDir): void {
125
-		$this->sourceStorage->mkdir($sourceDir);
126
-		$this->instance->file_put_contents($accessDir . '/test.txt', 'bar');
127
-		$this->assertTrue($this->instance->file_exists($accessDir . '/test.txt'));
128
-		$this->assertEquals('bar', $this->instance->file_get_contents($accessDir . '/test.txt'));
129
-
130
-		$this->sourceStorage->file_put_contents($sourceDir . '/' . self::NFD_NAME, 'foo');
131
-		$this->assertTrue($this->instance->file_exists($accessDir . '/' . self::NFC_NAME));
132
-		$this->assertEquals('foo', $this->instance->file_get_contents($accessDir . '/' . self::NFC_NAME));
133
-
134
-		// try again to make it use cached path
135
-		$this->assertEquals('bar', $this->instance->file_get_contents($accessDir . '/test.txt'));
136
-		$this->assertTrue($this->instance->file_exists($accessDir . '/test.txt'));
137
-		$this->assertEquals('foo', $this->instance->file_get_contents($accessDir . '/' . self::NFC_NAME));
138
-		$this->assertTrue($this->instance->file_exists($accessDir . '/' . self::NFC_NAME));
139
-	}
140
-
141
-	public function testCacheExtraSlash(): void {
142
-		$this->sourceStorage->file_put_contents(self::NFD_NAME, 'foo');
143
-		$this->assertEquals(3, $this->instance->file_put_contents(self::NFC_NAME, 'bar'));
144
-		$this->assertEquals('bar', $this->instance->file_get_contents(self::NFC_NAME));
145
-		clearstatcache();
146
-		$this->assertEquals(5, $this->instance->file_put_contents('/' . self::NFC_NAME, 'baric'));
147
-		$this->assertEquals('baric', $this->instance->file_get_contents(self::NFC_NAME));
148
-		clearstatcache();
149
-		$this->assertEquals(8, $this->instance->file_put_contents('/' . self::NFC_NAME, 'barbaric'));
150
-		$this->assertEquals('barbaric', $this->instance->file_get_contents('//' . self::NFC_NAME));
151
-	}
152
-
153
-	public static function sourceAndTargetDirectoryProvider(): array {
154
-		return [
155
-			[self::NFC_NAME . '1', self::NFC_NAME . '2'],
156
-			[self::NFD_NAME . '1', self::NFC_NAME . '2'],
157
-			[self::NFC_NAME . '1', self::NFD_NAME . '2'],
158
-			[self::NFD_NAME . '1', self::NFD_NAME . '2'],
159
-		];
160
-	}
161
-
162
-	/**
163
-	 * @dataProvider sourceAndTargetDirectoryProvider
164
-	 */
165
-	public function testCopyAndMoveEncodedFolder($sourceDir, $targetDir): void {
166
-		$this->sourceStorage->mkdir($sourceDir);
167
-		$this->sourceStorage->mkdir($targetDir);
168
-		$this->sourceStorage->file_put_contents($sourceDir . '/test.txt', 'bar');
169
-		$this->assertTrue($this->instance->copy(self::NFC_NAME . '1/test.txt', self::NFC_NAME . '2/test.txt'));
170
-
171
-		$this->assertTrue($this->instance->file_exists(self::NFC_NAME . '1/test.txt'));
172
-		$this->assertTrue($this->instance->file_exists(self::NFC_NAME . '2/test.txt'));
173
-		$this->assertEquals('bar', $this->instance->file_get_contents(self::NFC_NAME . '2/test.txt'));
174
-
175
-		$this->assertTrue($this->instance->rename(self::NFC_NAME . '1/test.txt', self::NFC_NAME . '2/test2.txt'));
176
-		$this->assertFalse($this->instance->file_exists(self::NFC_NAME . '1/test.txt'));
177
-		$this->assertTrue($this->instance->file_exists(self::NFC_NAME . '2/test2.txt'));
178
-
179
-		$this->assertEquals('bar', $this->instance->file_get_contents(self::NFC_NAME . '2/test2.txt'));
180
-	}
181
-
182
-	/**
183
-	 * @dataProvider sourceAndTargetDirectoryProvider
184
-	 */
185
-	public function testCopyAndMoveFromStorageEncodedFolder($sourceDir, $targetDir): void {
186
-		$this->sourceStorage->mkdir($sourceDir);
187
-		$this->sourceStorage->mkdir($targetDir);
188
-		$this->sourceStorage->file_put_contents($sourceDir . '/test.txt', 'bar');
189
-		$this->assertTrue($this->instance->copyFromStorage($this->instance, self::NFC_NAME . '1/test.txt', self::NFC_NAME . '2/test.txt'));
190
-
191
-		$this->assertTrue($this->instance->file_exists(self::NFC_NAME . '1/test.txt'));
192
-		$this->assertTrue($this->instance->file_exists(self::NFC_NAME . '2/test.txt'));
193
-		$this->assertEquals('bar', $this->instance->file_get_contents(self::NFC_NAME . '2/test.txt'));
194
-
195
-		$this->assertTrue($this->instance->moveFromStorage($this->instance, self::NFC_NAME . '1/test.txt', self::NFC_NAME . '2/test2.txt'));
196
-		$this->assertFalse($this->instance->file_exists(self::NFC_NAME . '1/test.txt'));
197
-		$this->assertTrue($this->instance->file_exists(self::NFC_NAME . '2/test2.txt'));
198
-
199
-		$this->assertEquals('bar', $this->instance->file_get_contents(self::NFC_NAME . '2/test2.txt'));
200
-	}
201
-
202
-	public function testNormalizedDirectoryEntriesOpenDir(): void {
203
-		$this->sourceStorage->mkdir('/test');
204
-		$this->sourceStorage->mkdir('/test/' . self::NFD_NAME);
205
-
206
-		$this->assertTrue($this->instance->file_exists('/test/' . self::NFC_NAME));
207
-		$this->assertTrue($this->instance->file_exists('/test/' . self::NFD_NAME));
208
-
209
-		$dh = $this->instance->opendir('/test');
210
-		$content = [];
211
-		while (($file = readdir($dh)) !== false) {
212
-			if ($file != '.' and $file != '..') {
213
-				$content[] = $file;
214
-			}
215
-		}
216
-
217
-		$this->assertCount(1, $content);
218
-		$this->assertEquals(self::NFC_NAME, $content[0]);
219
-	}
220
-
221
-	public function testNormalizedDirectoryEntriesGetDirectoryContent(): void {
222
-		$this->sourceStorage->mkdir('/test');
223
-		$this->sourceStorage->mkdir('/test/' . self::NFD_NAME);
224
-
225
-		$this->assertTrue($this->instance->file_exists('/test/' . self::NFC_NAME));
226
-		$this->assertTrue($this->instance->file_exists('/test/' . self::NFD_NAME));
227
-
228
-		$content = iterator_to_array($this->instance->getDirectoryContent('/test'));
229
-		$this->assertCount(1, $content);
230
-		$this->assertEquals(self::NFC_NAME, $content[0]['name']);
231
-	}
232
-
233
-	public function testNormalizedGetMetaData(): void {
234
-		$this->sourceStorage->mkdir('/test');
235
-		$this->sourceStorage->mkdir('/test/' . self::NFD_NAME);
236
-
237
-		$entry = $this->instance->getMetaData('/test/' . self::NFC_NAME);
238
-		$this->assertEquals(self::NFC_NAME, $entry['name']);
239
-
240
-		$entry = $this->instance->getMetaData('/test/' . self::NFD_NAME);
241
-		$this->assertEquals(self::NFC_NAME, $entry['name']);
242
-	}
243
-
244
-	/**
245
-	 * Regression test of https://github.com/nextcloud/server/issues/50431
246
-	 */
247
-	public function testNoMetadata() {
248
-		$this->assertNull($this->instance->getMetaData('/test/null'));
249
-	}
11
+    public const NFD_NAME = 'ümlaut';
12
+    public const NFC_NAME = 'ümlaut';
13
+
14
+    /**
15
+     * @var \OC\Files\Storage\Temporary
16
+     */
17
+    private $sourceStorage;
18
+
19
+    protected function setUp(): void {
20
+        parent::setUp();
21
+        $this->sourceStorage = new \OC\Files\Storage\Temporary([]);
22
+        $this->instance = new \OC\Files\Storage\Wrapper\Encoding([
23
+            'storage' => $this->sourceStorage
24
+        ]);
25
+    }
26
+
27
+    protected function tearDown(): void {
28
+        $this->sourceStorage->cleanUp();
29
+        parent::tearDown();
30
+    }
31
+
32
+    public static function directoryProvider(): array {
33
+        $a = parent::directoryProvider();
34
+        $a[] = [self::NFC_NAME];
35
+        return $a;
36
+    }
37
+
38
+    public static function fileNameProvider(): array {
39
+        $a = parent::fileNameProvider();
40
+        $a[] = [self::NFD_NAME . '.txt'];
41
+        return $a;
42
+    }
43
+
44
+    public static function copyAndMoveProvider(): array {
45
+        $a = parent::copyAndMoveProvider();
46
+        $a[] = [self::NFD_NAME . '.txt', self::NFC_NAME . '-renamed.txt'];
47
+        return $a;
48
+    }
49
+
50
+    public static function accessNameProvider(): array {
51
+        return [
52
+            [self::NFD_NAME],
53
+            [self::NFC_NAME],
54
+        ];
55
+    }
56
+
57
+    /**
58
+     * @dataProvider accessNameProvider
59
+     */
60
+    public function testFputEncoding($accessName): void {
61
+        $this->sourceStorage->file_put_contents(self::NFD_NAME, 'bar');
62
+        $this->assertEquals('bar', $this->instance->file_get_contents($accessName));
63
+    }
64
+
65
+    /**
66
+     * @dataProvider accessNameProvider
67
+     */
68
+    public function testFopenReadEncoding($accessName): void {
69
+        $this->sourceStorage->file_put_contents(self::NFD_NAME, 'bar');
70
+        $fh = $this->instance->fopen($accessName, 'r');
71
+        $data = fgets($fh);
72
+        fclose($fh);
73
+        $this->assertEquals('bar', $data);
74
+    }
75
+
76
+    /**
77
+     * @dataProvider accessNameProvider
78
+     */
79
+    public function testFopenOverwriteEncoding($accessName): void {
80
+        $this->sourceStorage->file_put_contents(self::NFD_NAME, 'bar');
81
+        $fh = $this->instance->fopen($accessName, 'w');
82
+        $data = fputs($fh, 'test');
83
+        fclose($fh);
84
+        $data = $this->sourceStorage->file_get_contents(self::NFD_NAME);
85
+        $this->assertEquals('test', $data);
86
+        $this->assertFalse($this->sourceStorage->file_exists(self::NFC_NAME));
87
+    }
88
+
89
+    /**
90
+     * @dataProvider accessNameProvider
91
+     */
92
+    public function testFileExistsEncoding($accessName): void {
93
+        $this->sourceStorage->file_put_contents(self::NFD_NAME, 'bar');
94
+        $this->assertTrue($this->instance->file_exists($accessName));
95
+    }
96
+
97
+    /**
98
+     * @dataProvider accessNameProvider
99
+     */
100
+    public function testUnlinkEncoding($accessName): void {
101
+        $this->sourceStorage->file_put_contents(self::NFD_NAME, 'bar');
102
+        $this->assertTrue($this->instance->unlink($accessName));
103
+        $this->assertFalse($this->sourceStorage->file_exists(self::NFC_NAME));
104
+        $this->assertFalse($this->sourceStorage->file_exists(self::NFD_NAME));
105
+    }
106
+
107
+    public function testNfcHigherPriority(): void {
108
+        $this->sourceStorage->file_put_contents(self::NFC_NAME, 'nfc');
109
+        $this->sourceStorage->file_put_contents(self::NFD_NAME, 'nfd');
110
+        $this->assertEquals('nfc', $this->instance->file_get_contents(self::NFC_NAME));
111
+    }
112
+
113
+    public static function encodedDirectoriesProvider(): array {
114
+        return [
115
+            [self::NFD_NAME, self::NFC_NAME],
116
+            [self::NFD_NAME . '/' . self::NFD_NAME, self::NFC_NAME . '/' . self::NFC_NAME],
117
+            [self::NFD_NAME . '/' . self::NFC_NAME . '/' . self::NFD_NAME, self::NFC_NAME . '/' . self::NFC_NAME . '/' . self::NFC_NAME],
118
+        ];
119
+    }
120
+
121
+    /**
122
+     * @dataProvider encodedDirectoriesProvider
123
+     */
124
+    public function testOperationInsideDirectory($sourceDir, $accessDir): void {
125
+        $this->sourceStorage->mkdir($sourceDir);
126
+        $this->instance->file_put_contents($accessDir . '/test.txt', 'bar');
127
+        $this->assertTrue($this->instance->file_exists($accessDir . '/test.txt'));
128
+        $this->assertEquals('bar', $this->instance->file_get_contents($accessDir . '/test.txt'));
129
+
130
+        $this->sourceStorage->file_put_contents($sourceDir . '/' . self::NFD_NAME, 'foo');
131
+        $this->assertTrue($this->instance->file_exists($accessDir . '/' . self::NFC_NAME));
132
+        $this->assertEquals('foo', $this->instance->file_get_contents($accessDir . '/' . self::NFC_NAME));
133
+
134
+        // try again to make it use cached path
135
+        $this->assertEquals('bar', $this->instance->file_get_contents($accessDir . '/test.txt'));
136
+        $this->assertTrue($this->instance->file_exists($accessDir . '/test.txt'));
137
+        $this->assertEquals('foo', $this->instance->file_get_contents($accessDir . '/' . self::NFC_NAME));
138
+        $this->assertTrue($this->instance->file_exists($accessDir . '/' . self::NFC_NAME));
139
+    }
140
+
141
+    public function testCacheExtraSlash(): void {
142
+        $this->sourceStorage->file_put_contents(self::NFD_NAME, 'foo');
143
+        $this->assertEquals(3, $this->instance->file_put_contents(self::NFC_NAME, 'bar'));
144
+        $this->assertEquals('bar', $this->instance->file_get_contents(self::NFC_NAME));
145
+        clearstatcache();
146
+        $this->assertEquals(5, $this->instance->file_put_contents('/' . self::NFC_NAME, 'baric'));
147
+        $this->assertEquals('baric', $this->instance->file_get_contents(self::NFC_NAME));
148
+        clearstatcache();
149
+        $this->assertEquals(8, $this->instance->file_put_contents('/' . self::NFC_NAME, 'barbaric'));
150
+        $this->assertEquals('barbaric', $this->instance->file_get_contents('//' . self::NFC_NAME));
151
+    }
152
+
153
+    public static function sourceAndTargetDirectoryProvider(): array {
154
+        return [
155
+            [self::NFC_NAME . '1', self::NFC_NAME . '2'],
156
+            [self::NFD_NAME . '1', self::NFC_NAME . '2'],
157
+            [self::NFC_NAME . '1', self::NFD_NAME . '2'],
158
+            [self::NFD_NAME . '1', self::NFD_NAME . '2'],
159
+        ];
160
+    }
161
+
162
+    /**
163
+     * @dataProvider sourceAndTargetDirectoryProvider
164
+     */
165
+    public function testCopyAndMoveEncodedFolder($sourceDir, $targetDir): void {
166
+        $this->sourceStorage->mkdir($sourceDir);
167
+        $this->sourceStorage->mkdir($targetDir);
168
+        $this->sourceStorage->file_put_contents($sourceDir . '/test.txt', 'bar');
169
+        $this->assertTrue($this->instance->copy(self::NFC_NAME . '1/test.txt', self::NFC_NAME . '2/test.txt'));
170
+
171
+        $this->assertTrue($this->instance->file_exists(self::NFC_NAME . '1/test.txt'));
172
+        $this->assertTrue($this->instance->file_exists(self::NFC_NAME . '2/test.txt'));
173
+        $this->assertEquals('bar', $this->instance->file_get_contents(self::NFC_NAME . '2/test.txt'));
174
+
175
+        $this->assertTrue($this->instance->rename(self::NFC_NAME . '1/test.txt', self::NFC_NAME . '2/test2.txt'));
176
+        $this->assertFalse($this->instance->file_exists(self::NFC_NAME . '1/test.txt'));
177
+        $this->assertTrue($this->instance->file_exists(self::NFC_NAME . '2/test2.txt'));
178
+
179
+        $this->assertEquals('bar', $this->instance->file_get_contents(self::NFC_NAME . '2/test2.txt'));
180
+    }
181
+
182
+    /**
183
+     * @dataProvider sourceAndTargetDirectoryProvider
184
+     */
185
+    public function testCopyAndMoveFromStorageEncodedFolder($sourceDir, $targetDir): void {
186
+        $this->sourceStorage->mkdir($sourceDir);
187
+        $this->sourceStorage->mkdir($targetDir);
188
+        $this->sourceStorage->file_put_contents($sourceDir . '/test.txt', 'bar');
189
+        $this->assertTrue($this->instance->copyFromStorage($this->instance, self::NFC_NAME . '1/test.txt', self::NFC_NAME . '2/test.txt'));
190
+
191
+        $this->assertTrue($this->instance->file_exists(self::NFC_NAME . '1/test.txt'));
192
+        $this->assertTrue($this->instance->file_exists(self::NFC_NAME . '2/test.txt'));
193
+        $this->assertEquals('bar', $this->instance->file_get_contents(self::NFC_NAME . '2/test.txt'));
194
+
195
+        $this->assertTrue($this->instance->moveFromStorage($this->instance, self::NFC_NAME . '1/test.txt', self::NFC_NAME . '2/test2.txt'));
196
+        $this->assertFalse($this->instance->file_exists(self::NFC_NAME . '1/test.txt'));
197
+        $this->assertTrue($this->instance->file_exists(self::NFC_NAME . '2/test2.txt'));
198
+
199
+        $this->assertEquals('bar', $this->instance->file_get_contents(self::NFC_NAME . '2/test2.txt'));
200
+    }
201
+
202
+    public function testNormalizedDirectoryEntriesOpenDir(): void {
203
+        $this->sourceStorage->mkdir('/test');
204
+        $this->sourceStorage->mkdir('/test/' . self::NFD_NAME);
205
+
206
+        $this->assertTrue($this->instance->file_exists('/test/' . self::NFC_NAME));
207
+        $this->assertTrue($this->instance->file_exists('/test/' . self::NFD_NAME));
208
+
209
+        $dh = $this->instance->opendir('/test');
210
+        $content = [];
211
+        while (($file = readdir($dh)) !== false) {
212
+            if ($file != '.' and $file != '..') {
213
+                $content[] = $file;
214
+            }
215
+        }
216
+
217
+        $this->assertCount(1, $content);
218
+        $this->assertEquals(self::NFC_NAME, $content[0]);
219
+    }
220
+
221
+    public function testNormalizedDirectoryEntriesGetDirectoryContent(): void {
222
+        $this->sourceStorage->mkdir('/test');
223
+        $this->sourceStorage->mkdir('/test/' . self::NFD_NAME);
224
+
225
+        $this->assertTrue($this->instance->file_exists('/test/' . self::NFC_NAME));
226
+        $this->assertTrue($this->instance->file_exists('/test/' . self::NFD_NAME));
227
+
228
+        $content = iterator_to_array($this->instance->getDirectoryContent('/test'));
229
+        $this->assertCount(1, $content);
230
+        $this->assertEquals(self::NFC_NAME, $content[0]['name']);
231
+    }
232
+
233
+    public function testNormalizedGetMetaData(): void {
234
+        $this->sourceStorage->mkdir('/test');
235
+        $this->sourceStorage->mkdir('/test/' . self::NFD_NAME);
236
+
237
+        $entry = $this->instance->getMetaData('/test/' . self::NFC_NAME);
238
+        $this->assertEquals(self::NFC_NAME, $entry['name']);
239
+
240
+        $entry = $this->instance->getMetaData('/test/' . self::NFD_NAME);
241
+        $this->assertEquals(self::NFC_NAME, $entry['name']);
242
+    }
243
+
244
+    /**
245
+     * Regression test of https://github.com/nextcloud/server/issues/50431
246
+     */
247
+    public function testNoMetadata() {
248
+        $this->assertNull($this->instance->getMetaData('/test/null'));
249
+    }
250 250
 
251 251
 }
Please login to merge, or discard this patch.
Spacing   +48 added lines, -48 removed lines patch added patch discarded remove patch
@@ -37,13 +37,13 @@  discard block
 block discarded – undo
37 37
 
38 38
 	public static function fileNameProvider(): array {
39 39
 		$a = parent::fileNameProvider();
40
-		$a[] = [self::NFD_NAME . '.txt'];
40
+		$a[] = [self::NFD_NAME.'.txt'];
41 41
 		return $a;
42 42
 	}
43 43
 
44 44
 	public static function copyAndMoveProvider(): array {
45 45
 		$a = parent::copyAndMoveProvider();
46
-		$a[] = [self::NFD_NAME . '.txt', self::NFC_NAME . '-renamed.txt'];
46
+		$a[] = [self::NFD_NAME.'.txt', self::NFC_NAME.'-renamed.txt'];
47 47
 		return $a;
48 48
 	}
49 49
 
@@ -113,8 +113,8 @@  discard block
 block discarded – undo
113 113
 	public static function encodedDirectoriesProvider(): array {
114 114
 		return [
115 115
 			[self::NFD_NAME, self::NFC_NAME],
116
-			[self::NFD_NAME . '/' . self::NFD_NAME, self::NFC_NAME . '/' . self::NFC_NAME],
117
-			[self::NFD_NAME . '/' . self::NFC_NAME . '/' . self::NFD_NAME, self::NFC_NAME . '/' . self::NFC_NAME . '/' . self::NFC_NAME],
116
+			[self::NFD_NAME.'/'.self::NFD_NAME, self::NFC_NAME.'/'.self::NFC_NAME],
117
+			[self::NFD_NAME.'/'.self::NFC_NAME.'/'.self::NFD_NAME, self::NFC_NAME.'/'.self::NFC_NAME.'/'.self::NFC_NAME],
118 118
 		];
119 119
 	}
120 120
 
@@ -123,19 +123,19 @@  discard block
 block discarded – undo
123 123
 	 */
124 124
 	public function testOperationInsideDirectory($sourceDir, $accessDir): void {
125 125
 		$this->sourceStorage->mkdir($sourceDir);
126
-		$this->instance->file_put_contents($accessDir . '/test.txt', 'bar');
127
-		$this->assertTrue($this->instance->file_exists($accessDir . '/test.txt'));
128
-		$this->assertEquals('bar', $this->instance->file_get_contents($accessDir . '/test.txt'));
126
+		$this->instance->file_put_contents($accessDir.'/test.txt', 'bar');
127
+		$this->assertTrue($this->instance->file_exists($accessDir.'/test.txt'));
128
+		$this->assertEquals('bar', $this->instance->file_get_contents($accessDir.'/test.txt'));
129 129
 
130
-		$this->sourceStorage->file_put_contents($sourceDir . '/' . self::NFD_NAME, 'foo');
131
-		$this->assertTrue($this->instance->file_exists($accessDir . '/' . self::NFC_NAME));
132
-		$this->assertEquals('foo', $this->instance->file_get_contents($accessDir . '/' . self::NFC_NAME));
130
+		$this->sourceStorage->file_put_contents($sourceDir.'/'.self::NFD_NAME, 'foo');
131
+		$this->assertTrue($this->instance->file_exists($accessDir.'/'.self::NFC_NAME));
132
+		$this->assertEquals('foo', $this->instance->file_get_contents($accessDir.'/'.self::NFC_NAME));
133 133
 
134 134
 		// try again to make it use cached path
135
-		$this->assertEquals('bar', $this->instance->file_get_contents($accessDir . '/test.txt'));
136
-		$this->assertTrue($this->instance->file_exists($accessDir . '/test.txt'));
137
-		$this->assertEquals('foo', $this->instance->file_get_contents($accessDir . '/' . self::NFC_NAME));
138
-		$this->assertTrue($this->instance->file_exists($accessDir . '/' . self::NFC_NAME));
135
+		$this->assertEquals('bar', $this->instance->file_get_contents($accessDir.'/test.txt'));
136
+		$this->assertTrue($this->instance->file_exists($accessDir.'/test.txt'));
137
+		$this->assertEquals('foo', $this->instance->file_get_contents($accessDir.'/'.self::NFC_NAME));
138
+		$this->assertTrue($this->instance->file_exists($accessDir.'/'.self::NFC_NAME));
139 139
 	}
140 140
 
141 141
 	public function testCacheExtraSlash(): void {
@@ -143,19 +143,19 @@  discard block
 block discarded – undo
143 143
 		$this->assertEquals(3, $this->instance->file_put_contents(self::NFC_NAME, 'bar'));
144 144
 		$this->assertEquals('bar', $this->instance->file_get_contents(self::NFC_NAME));
145 145
 		clearstatcache();
146
-		$this->assertEquals(5, $this->instance->file_put_contents('/' . self::NFC_NAME, 'baric'));
146
+		$this->assertEquals(5, $this->instance->file_put_contents('/'.self::NFC_NAME, 'baric'));
147 147
 		$this->assertEquals('baric', $this->instance->file_get_contents(self::NFC_NAME));
148 148
 		clearstatcache();
149
-		$this->assertEquals(8, $this->instance->file_put_contents('/' . self::NFC_NAME, 'barbaric'));
150
-		$this->assertEquals('barbaric', $this->instance->file_get_contents('//' . self::NFC_NAME));
149
+		$this->assertEquals(8, $this->instance->file_put_contents('/'.self::NFC_NAME, 'barbaric'));
150
+		$this->assertEquals('barbaric', $this->instance->file_get_contents('//'.self::NFC_NAME));
151 151
 	}
152 152
 
153 153
 	public static function sourceAndTargetDirectoryProvider(): array {
154 154
 		return [
155
-			[self::NFC_NAME . '1', self::NFC_NAME . '2'],
156
-			[self::NFD_NAME . '1', self::NFC_NAME . '2'],
157
-			[self::NFC_NAME . '1', self::NFD_NAME . '2'],
158
-			[self::NFD_NAME . '1', self::NFD_NAME . '2'],
155
+			[self::NFC_NAME.'1', self::NFC_NAME.'2'],
156
+			[self::NFD_NAME.'1', self::NFC_NAME.'2'],
157
+			[self::NFC_NAME.'1', self::NFD_NAME.'2'],
158
+			[self::NFD_NAME.'1', self::NFD_NAME.'2'],
159 159
 		];
160 160
 	}
161 161
 
@@ -165,18 +165,18 @@  discard block
 block discarded – undo
165 165
 	public function testCopyAndMoveEncodedFolder($sourceDir, $targetDir): void {
166 166
 		$this->sourceStorage->mkdir($sourceDir);
167 167
 		$this->sourceStorage->mkdir($targetDir);
168
-		$this->sourceStorage->file_put_contents($sourceDir . '/test.txt', 'bar');
169
-		$this->assertTrue($this->instance->copy(self::NFC_NAME . '1/test.txt', self::NFC_NAME . '2/test.txt'));
168
+		$this->sourceStorage->file_put_contents($sourceDir.'/test.txt', 'bar');
169
+		$this->assertTrue($this->instance->copy(self::NFC_NAME.'1/test.txt', self::NFC_NAME.'2/test.txt'));
170 170
 
171
-		$this->assertTrue($this->instance->file_exists(self::NFC_NAME . '1/test.txt'));
172
-		$this->assertTrue($this->instance->file_exists(self::NFC_NAME . '2/test.txt'));
173
-		$this->assertEquals('bar', $this->instance->file_get_contents(self::NFC_NAME . '2/test.txt'));
171
+		$this->assertTrue($this->instance->file_exists(self::NFC_NAME.'1/test.txt'));
172
+		$this->assertTrue($this->instance->file_exists(self::NFC_NAME.'2/test.txt'));
173
+		$this->assertEquals('bar', $this->instance->file_get_contents(self::NFC_NAME.'2/test.txt'));
174 174
 
175
-		$this->assertTrue($this->instance->rename(self::NFC_NAME . '1/test.txt', self::NFC_NAME . '2/test2.txt'));
176
-		$this->assertFalse($this->instance->file_exists(self::NFC_NAME . '1/test.txt'));
177
-		$this->assertTrue($this->instance->file_exists(self::NFC_NAME . '2/test2.txt'));
175
+		$this->assertTrue($this->instance->rename(self::NFC_NAME.'1/test.txt', self::NFC_NAME.'2/test2.txt'));
176
+		$this->assertFalse($this->instance->file_exists(self::NFC_NAME.'1/test.txt'));
177
+		$this->assertTrue($this->instance->file_exists(self::NFC_NAME.'2/test2.txt'));
178 178
 
179
-		$this->assertEquals('bar', $this->instance->file_get_contents(self::NFC_NAME . '2/test2.txt'));
179
+		$this->assertEquals('bar', $this->instance->file_get_contents(self::NFC_NAME.'2/test2.txt'));
180 180
 	}
181 181
 
182 182
 	/**
@@ -185,26 +185,26 @@  discard block
 block discarded – undo
185 185
 	public function testCopyAndMoveFromStorageEncodedFolder($sourceDir, $targetDir): void {
186 186
 		$this->sourceStorage->mkdir($sourceDir);
187 187
 		$this->sourceStorage->mkdir($targetDir);
188
-		$this->sourceStorage->file_put_contents($sourceDir . '/test.txt', 'bar');
189
-		$this->assertTrue($this->instance->copyFromStorage($this->instance, self::NFC_NAME . '1/test.txt', self::NFC_NAME . '2/test.txt'));
188
+		$this->sourceStorage->file_put_contents($sourceDir.'/test.txt', 'bar');
189
+		$this->assertTrue($this->instance->copyFromStorage($this->instance, self::NFC_NAME.'1/test.txt', self::NFC_NAME.'2/test.txt'));
190 190
 
191
-		$this->assertTrue($this->instance->file_exists(self::NFC_NAME . '1/test.txt'));
192
-		$this->assertTrue($this->instance->file_exists(self::NFC_NAME . '2/test.txt'));
193
-		$this->assertEquals('bar', $this->instance->file_get_contents(self::NFC_NAME . '2/test.txt'));
191
+		$this->assertTrue($this->instance->file_exists(self::NFC_NAME.'1/test.txt'));
192
+		$this->assertTrue($this->instance->file_exists(self::NFC_NAME.'2/test.txt'));
193
+		$this->assertEquals('bar', $this->instance->file_get_contents(self::NFC_NAME.'2/test.txt'));
194 194
 
195
-		$this->assertTrue($this->instance->moveFromStorage($this->instance, self::NFC_NAME . '1/test.txt', self::NFC_NAME . '2/test2.txt'));
196
-		$this->assertFalse($this->instance->file_exists(self::NFC_NAME . '1/test.txt'));
197
-		$this->assertTrue($this->instance->file_exists(self::NFC_NAME . '2/test2.txt'));
195
+		$this->assertTrue($this->instance->moveFromStorage($this->instance, self::NFC_NAME.'1/test.txt', self::NFC_NAME.'2/test2.txt'));
196
+		$this->assertFalse($this->instance->file_exists(self::NFC_NAME.'1/test.txt'));
197
+		$this->assertTrue($this->instance->file_exists(self::NFC_NAME.'2/test2.txt'));
198 198
 
199
-		$this->assertEquals('bar', $this->instance->file_get_contents(self::NFC_NAME . '2/test2.txt'));
199
+		$this->assertEquals('bar', $this->instance->file_get_contents(self::NFC_NAME.'2/test2.txt'));
200 200
 	}
201 201
 
202 202
 	public function testNormalizedDirectoryEntriesOpenDir(): void {
203 203
 		$this->sourceStorage->mkdir('/test');
204
-		$this->sourceStorage->mkdir('/test/' . self::NFD_NAME);
204
+		$this->sourceStorage->mkdir('/test/'.self::NFD_NAME);
205 205
 
206
-		$this->assertTrue($this->instance->file_exists('/test/' . self::NFC_NAME));
207
-		$this->assertTrue($this->instance->file_exists('/test/' . self::NFD_NAME));
206
+		$this->assertTrue($this->instance->file_exists('/test/'.self::NFC_NAME));
207
+		$this->assertTrue($this->instance->file_exists('/test/'.self::NFD_NAME));
208 208
 
209 209
 		$dh = $this->instance->opendir('/test');
210 210
 		$content = [];
@@ -220,10 +220,10 @@  discard block
 block discarded – undo
220 220
 
221 221
 	public function testNormalizedDirectoryEntriesGetDirectoryContent(): void {
222 222
 		$this->sourceStorage->mkdir('/test');
223
-		$this->sourceStorage->mkdir('/test/' . self::NFD_NAME);
223
+		$this->sourceStorage->mkdir('/test/'.self::NFD_NAME);
224 224
 
225
-		$this->assertTrue($this->instance->file_exists('/test/' . self::NFC_NAME));
226
-		$this->assertTrue($this->instance->file_exists('/test/' . self::NFD_NAME));
225
+		$this->assertTrue($this->instance->file_exists('/test/'.self::NFC_NAME));
226
+		$this->assertTrue($this->instance->file_exists('/test/'.self::NFD_NAME));
227 227
 
228 228
 		$content = iterator_to_array($this->instance->getDirectoryContent('/test'));
229 229
 		$this->assertCount(1, $content);
@@ -232,12 +232,12 @@  discard block
 block discarded – undo
232 232
 
233 233
 	public function testNormalizedGetMetaData(): void {
234 234
 		$this->sourceStorage->mkdir('/test');
235
-		$this->sourceStorage->mkdir('/test/' . self::NFD_NAME);
235
+		$this->sourceStorage->mkdir('/test/'.self::NFD_NAME);
236 236
 
237
-		$entry = $this->instance->getMetaData('/test/' . self::NFC_NAME);
237
+		$entry = $this->instance->getMetaData('/test/'.self::NFC_NAME);
238 238
 		$this->assertEquals(self::NFC_NAME, $entry['name']);
239 239
 
240
-		$entry = $this->instance->getMetaData('/test/' . self::NFD_NAME);
240
+		$entry = $this->instance->getMetaData('/test/'.self::NFD_NAME);
241 241
 		$this->assertEquals(self::NFC_NAME, $entry['name']);
242 242
 	}
243 243
 
Please login to merge, or discard this patch.
tests/lib/Files/Storage/Wrapper/EncryptionTest.php 2 patches
Indentation   +992 added lines, -992 removed lines patch added patch discarded remove patch
@@ -33,996 +33,996 @@
 block discarded – undo
33 33
 use Test\Files\Storage\Storage;
34 34
 
35 35
 class EncryptionTest extends Storage {
36
-	/**
37
-	 * block size will always be 8192 for a PHP stream
38
-	 * @see https://bugs.php.net/bug.php?id=21641
39
-	 */
40
-	protected int $headerSize = 8192;
41
-	private Temporary $sourceStorage;
42
-	/** @var Encryption&MockObject */
43
-	protected $instance;
44
-	private \OC\Encryption\Keys\Storage&MockObject $keyStore;
45
-	private Util&MockObject $util;
46
-	private \OC\Encryption\Manager&MockObject $encryptionManager;
47
-	private IEncryptionModule&MockObject $encryptionModule;
48
-	private Cache&MockObject $cache;
49
-	private LoggerInterface&MockObject $logger;
50
-	private File&MockObject $file;
51
-	private MountPoint&MockObject $mount;
52
-	private \OC\Files\Mount\Manager&MockObject $mountManager;
53
-	private \OC\Group\Manager&MockObject $groupManager;
54
-	private IConfig&MockObject $config;
55
-	private ArrayCache&MockObject $arrayCache;
56
-	/** dummy unencrypted size */
57
-	private int $dummySize = -1;
58
-
59
-	protected function setUp(): void {
60
-		parent::setUp();
61
-
62
-		$mockModule = $this->buildMockModule();
63
-		$this->encryptionManager = $this->getMockBuilder(\OC\Encryption\Manager::class)
64
-			->disableOriginalConstructor()
65
-			->onlyMethods(['getEncryptionModule', 'isEnabled'])
66
-			->getMock();
67
-		$this->encryptionManager->expects($this->any())
68
-			->method('getEncryptionModule')
69
-			->willReturn($mockModule);
70
-
71
-		$this->arrayCache = $this->createMock(ArrayCache::class);
72
-		$this->config = $this->getMockBuilder(IConfig::class)
73
-			->disableOriginalConstructor()
74
-			->getMock();
75
-		$this->groupManager = $this->getMockBuilder('\OC\Group\Manager')
76
-			->disableOriginalConstructor()
77
-			->getMock();
78
-
79
-		$this->util = $this->getMockBuilder(Util::class)
80
-			->onlyMethods(['getUidAndFilename', 'isFile', 'isExcluded', 'stripPartialFileExtension'])
81
-			->setConstructorArgs([new View(), new Manager(
82
-				$this->config,
83
-				$this->createMock(ICacheFactory::class),
84
-				$this->createMock(IEventDispatcher::class),
85
-				$this->createMock(LoggerInterface::class),
86
-			), $this->groupManager, $this->config, $this->arrayCache])
87
-			->getMock();
88
-		$this->util->expects($this->any())
89
-			->method('getUidAndFilename')
90
-			->willReturnCallback(function ($path) {
91
-				return ['user1', $path];
92
-			});
93
-		$this->util->expects($this->any())
94
-			->method('stripPartialFileExtension')
95
-			->willReturnCallback(function ($path) {
96
-				return $path;
97
-			});
98
-
99
-		$this->file = $this->getMockBuilder(File::class)
100
-			->disableOriginalConstructor()
101
-			->onlyMethods(['getAccessList'])
102
-			->getMock();
103
-		$this->file->expects($this->any())->method('getAccessList')->willReturn([]);
104
-
105
-		$this->logger = $this->createMock(LoggerInterface::class);
106
-
107
-		$this->sourceStorage = new Temporary([]);
108
-
109
-		$this->keyStore = $this->createMock(\OC\Encryption\Keys\Storage::class);
110
-
111
-		$this->mount = $this->getMockBuilder(MountPoint::class)
112
-			->disableOriginalConstructor()
113
-			->onlyMethods(['getOption'])
114
-			->getMock();
115
-		$this->mount->expects($this->any())->method('getOption')->willReturnCallback(function ($option, $default) {
116
-			if ($option === 'encrypt' && $default === true) {
117
-				global $mockedMountPointEncryptionEnabled;
118
-				if ($mockedMountPointEncryptionEnabled !== null) {
119
-					return $mockedMountPointEncryptionEnabled;
120
-				}
121
-			}
122
-			return true;
123
-		});
124
-
125
-		$this->cache = $this->getMockBuilder('\OC\Files\Cache\Cache')
126
-			->disableOriginalConstructor()->getMock();
127
-		$this->cache->expects($this->any())
128
-			->method('get')
129
-			->willReturnCallback(function ($path) {
130
-				return ['encrypted' => false, 'path' => $path];
131
-			});
132
-
133
-		$this->mountManager = $this->createMock(\OC\Files\Mount\Manager::class);
134
-		$this->mountManager->method('findByStorageId')
135
-			->willReturn([]);
136
-
137
-		$this->instance = $this->getMockBuilder(Encryption::class)
138
-			->setConstructorArgs(
139
-				[
140
-					[
141
-						'storage' => $this->sourceStorage,
142
-						'root' => 'foo',
143
-						'mountPoint' => '/',
144
-						'mount' => $this->mount
145
-					],
146
-					$this->encryptionManager,
147
-					$this->util,
148
-					$this->logger,
149
-					$this->file,
150
-					null,
151
-					$this->keyStore,
152
-					$this->mountManager,
153
-					$this->arrayCache
154
-				]
155
-			)
156
-			->onlyMethods(['getMetaData', 'getCache', 'getEncryptionModule'])
157
-			->getMock();
158
-
159
-		$this->instance->expects($this->any())
160
-			->method('getMetaData')
161
-			->willReturnCallback(function ($path) {
162
-				return ['encrypted' => true, 'size' => $this->dummySize, 'path' => $path];
163
-			});
164
-
165
-		$this->instance->expects($this->any())
166
-			->method('getCache')
167
-			->willReturn($this->cache);
168
-
169
-		$this->instance->expects($this->any())
170
-			->method('getEncryptionModule')
171
-			->willReturn($mockModule);
172
-	}
173
-
174
-	protected function buildMockModule(): IEncryptionModule&MockObject {
175
-		$this->encryptionModule = $this->getMockBuilder('\OCP\Encryption\IEncryptionModule')
176
-			->disableOriginalConstructor()
177
-			->onlyMethods(['getId', 'getDisplayName', 'begin', 'end', 'encrypt', 'decrypt', 'update', 'shouldEncrypt', 'getUnencryptedBlockSize', 'isReadable', 'encryptAll', 'prepareDecryptAll', 'isReadyForUser', 'needDetailedAccessList'])
178
-			->getMock();
179
-
180
-		$this->encryptionModule->expects($this->any())->method('getId')->willReturn('UNIT_TEST_MODULE');
181
-		$this->encryptionModule->expects($this->any())->method('getDisplayName')->willReturn('Unit test module');
182
-		$this->encryptionModule->expects($this->any())->method('begin')->willReturn([]);
183
-		$this->encryptionModule->expects($this->any())->method('end')->willReturn('');
184
-		$this->encryptionModule->expects($this->any())->method('encrypt')->willReturnArgument(0);
185
-		$this->encryptionModule->expects($this->any())->method('decrypt')->willReturnArgument(0);
186
-		$this->encryptionModule->expects($this->any())->method('update')->willReturn(true);
187
-		$this->encryptionModule->expects($this->any())->method('shouldEncrypt')->willReturn(true);
188
-		$this->encryptionModule->expects($this->any())->method('getUnencryptedBlockSize')->willReturn(8192);
189
-		$this->encryptionModule->expects($this->any())->method('isReadable')->willReturn(true);
190
-		$this->encryptionModule->expects($this->any())->method('needDetailedAccessList')->willReturn(false);
191
-		return $this->encryptionModule;
192
-	}
193
-
194
-	/**
195
-	 * @dataProvider dataTestGetMetaData
196
-	 *
197
-	 * @param string $path
198
-	 * @param array $metaData
199
-	 * @param bool $encrypted
200
-	 * @param bool $unencryptedSizeSet
201
-	 * @param int $storedUnencryptedSize
202
-	 * @param array $expected
203
-	 */
204
-	public function testGetMetaData($path, $metaData, $encrypted, $unencryptedSizeSet, $storedUnencryptedSize, $expected): void {
205
-		$sourceStorage = $this->getMockBuilder('\OC\Files\Storage\Storage')
206
-			->disableOriginalConstructor()->getMock();
207
-
208
-		$cache = $this->getMockBuilder('\OC\Files\Cache\Cache')
209
-			->disableOriginalConstructor()->getMock();
210
-		$cache->expects($this->any())
211
-			->method('get')
212
-			->willReturnCallback(
213
-				function ($path) use ($encrypted) {
214
-					return new CacheEntry(['encrypted' => $encrypted, 'path' => $path, 'size' => 0, 'fileid' => 1]);
215
-				}
216
-			);
217
-
218
-		$this->instance = $this->getMockBuilder(Encryption::class)
219
-			->setConstructorArgs(
220
-				[
221
-					[
222
-						'storage' => $sourceStorage,
223
-						'root' => 'foo',
224
-						'mountPoint' => '/',
225
-						'mount' => $this->mount
226
-					],
227
-					$this->encryptionManager,
228
-					$this->util,
229
-					$this->logger,
230
-					$this->file,
231
-					null,
232
-					$this->keyStore,
233
-					$this->mountManager,
234
-					$this->arrayCache,
235
-				]
236
-			)
237
-			->onlyMethods(['getCache', 'verifyUnencryptedSize'])
238
-			->getMock();
239
-
240
-		if ($unencryptedSizeSet) {
241
-			$this->invokePrivate($this->instance, 'unencryptedSize', [[$path => $storedUnencryptedSize]]);
242
-		}
243
-
244
-		$fileEntry = $this->getMockBuilder('\OC\Files\Cache\Cache')
245
-			->disableOriginalConstructor()->getMock();
246
-		$sourceStorage->expects($this->once())->method('getMetaData')->with($path)
247
-			->willReturn($metaData);
248
-		$sourceStorage->expects($this->any())
249
-			->method('getCache')
250
-			->with($path)
251
-			->willReturn($fileEntry);
252
-		if ($metaData !== null) {
253
-			$fileEntry->expects($this->any())
254
-				->method('get')
255
-				->with($metaData['fileid']);
256
-		}
257
-
258
-		$this->instance->expects($this->any())->method('getCache')->willReturn($cache);
259
-		if ($expected !== null) {
260
-			$this->instance->expects($this->any())->method('verifyUnencryptedSize')
261
-				->with($path, 0)->willReturn($expected['size']);
262
-		}
263
-
264
-		$result = $this->instance->getMetaData($path);
265
-		if (isset($expected['encrypted'])) {
266
-			$this->assertSame($expected['encrypted'], (bool)$result['encrypted']);
267
-
268
-			if (isset($expected['encryptedVersion'])) {
269
-				$this->assertSame($expected['encryptedVersion'], $result['encryptedVersion']);
270
-			}
271
-		}
272
-
273
-		if ($expected !== null) {
274
-			$this->assertSame($expected['size'], $result['size']);
275
-		} else {
276
-			$this->assertSame(null, $result);
277
-		}
278
-	}
279
-
280
-	public static function dataTestGetMetaData(): array {
281
-		return [
282
-			['/test.txt', ['size' => 42, 'encrypted' => 2, 'encryptedVersion' => 2, 'fileid' => 1], true, true, 12, ['size' => 12, 'encrypted' => true, 'encryptedVersion' => 2]],
283
-			['/test.txt', null, true, true, 12, null],
284
-			['/test.txt', ['size' => 42, 'encrypted' => 0, 'fileid' => 1], false, false, 12, ['size' => 42, 'encrypted' => false]],
285
-			['/test.txt', ['size' => 42, 'encrypted' => false, 'fileid' => 1], true, false, 12, ['size' => 12, 'encrypted' => true]]
286
-		];
287
-	}
288
-
289
-	public function testFilesize(): void {
290
-		$cache = $this->getMockBuilder('\OC\Files\Cache\Cache')
291
-			->disableOriginalConstructor()->getMock();
292
-		$cache->expects($this->any())
293
-			->method('get')
294
-			->willReturn(new CacheEntry(['encrypted' => true, 'path' => '/test.txt', 'size' => 0, 'fileid' => 1]));
295
-
296
-		$this->instance = $this->getMockBuilder(Encryption::class)
297
-			->setConstructorArgs(
298
-				[
299
-					[
300
-						'storage' => $this->sourceStorage,
301
-						'root' => 'foo',
302
-						'mountPoint' => '/',
303
-						'mount' => $this->mount
304
-					],
305
-					$this->encryptionManager,
306
-					$this->util,
307
-					$this->logger,
308
-					$this->file,
309
-					null,
310
-					$this->keyStore,
311
-					$this->mountManager,
312
-					$this->arrayCache,
313
-				]
314
-			)
315
-			->onlyMethods(['getCache', 'verifyUnencryptedSize'])
316
-			->getMock();
317
-
318
-		$this->instance->expects($this->any())->method('getCache')->willReturn($cache);
319
-		$this->instance->expects($this->any())->method('verifyUnencryptedSize')
320
-			->willReturn(42);
321
-
322
-
323
-		$this->assertSame(42,
324
-			$this->instance->filesize('/test.txt')
325
-		);
326
-	}
327
-
328
-	/**
329
-	 * @dataProvider dataTestVerifyUnencryptedSize
330
-	 *
331
-	 * @param int $encryptedSize
332
-	 * @param int $unencryptedSize
333
-	 * @param bool $failure
334
-	 * @param int $expected
335
-	 */
336
-	public function testVerifyUnencryptedSize($encryptedSize, $unencryptedSize, $failure, $expected): void {
337
-		$sourceStorage = $this->getMockBuilder('\OC\Files\Storage\Storage')
338
-			->disableOriginalConstructor()->getMock();
339
-
340
-		$this->instance = $this->getMockBuilder(Encryption::class)
341
-			->setConstructorArgs(
342
-				[
343
-					[
344
-						'storage' => $sourceStorage,
345
-						'root' => 'foo',
346
-						'mountPoint' => '/',
347
-						'mount' => $this->mount
348
-					],
349
-					$this->encryptionManager,
350
-					$this->util,
351
-					$this->logger,
352
-					$this->file,
353
-					null,
354
-					$this->keyStore,
355
-					$this->mountManager,
356
-					$this->arrayCache,
357
-				]
358
-			)
359
-			->onlyMethods(['fixUnencryptedSize'])
360
-			->getMock();
361
-
362
-		$sourceStorage->expects($this->once())->method('filesize')->willReturn($encryptedSize);
363
-
364
-		$this->instance->expects($this->any())->method('fixUnencryptedSize')
365
-			->with('/test.txt', $encryptedSize, $unencryptedSize)
366
-			->willReturnCallback(
367
-				function () use ($failure, $expected) {
368
-					if ($failure) {
369
-						throw new Exception();
370
-					} else {
371
-						return $expected;
372
-					}
373
-				}
374
-			);
375
-
376
-		$this->assertSame(
377
-			$expected,
378
-			$this->invokePrivate($this->instance, 'verifyUnencryptedSize', ['/test.txt', $unencryptedSize])
379
-		);
380
-	}
381
-
382
-	public static function dataTestVerifyUnencryptedSize(): array {
383
-		return [
384
-			[120, 80, false, 80],
385
-			[120, 120, false, 80],
386
-			[120, -1, false, 80],
387
-			[120, -1, true, -1]
388
-		];
389
-	}
390
-
391
-	/**
392
-	 * @dataProvider dataTestCopyAndRename
393
-	 *
394
-	 * @param string $source
395
-	 * @param string $target
396
-	 * @param $encryptionEnabled
397
-	 * @param boolean $renameKeysReturn
398
-	 */
399
-	public function testRename($source,
400
-		$target,
401
-		$encryptionEnabled,
402
-		$renameKeysReturn): void {
403
-		if ($encryptionEnabled) {
404
-			$this->keyStore
405
-				->expects($this->once())
406
-				->method('renameKeys')
407
-				->willReturn($renameKeysReturn);
408
-		} else {
409
-			$this->keyStore
410
-				->expects($this->never())->method('renameKeys');
411
-		}
412
-		$this->util->expects($this->any())
413
-			->method('isFile')->willReturn(true);
414
-		$this->encryptionManager->expects($this->once())
415
-			->method('isEnabled')->willReturn($encryptionEnabled);
416
-
417
-		$this->instance->mkdir($source);
418
-		$this->instance->mkdir(dirname($target));
419
-		$this->instance->rename($source, $target);
420
-	}
421
-
422
-	public function testCopyEncryption(): void {
423
-		$this->instance->file_put_contents('source.txt', 'bar');
424
-		$this->instance->copy('source.txt', 'target.txt');
425
-		$this->assertSame('bar', $this->instance->file_get_contents('target.txt'));
426
-		$targetMeta = $this->instance->getMetaData('target.txt');
427
-		$sourceMeta = $this->instance->getMetaData('source.txt');
428
-		$this->assertSame($sourceMeta['encrypted'], $targetMeta['encrypted']);
429
-		$this->assertSame($sourceMeta['size'], $targetMeta['size']);
430
-	}
431
-
432
-	/**
433
-	 * data provider for testCopyTesting() and dataTestCopyAndRename()
434
-	 *
435
-	 * @return array
436
-	 */
437
-	public static function dataTestCopyAndRename(): array {
438
-		return [
439
-			['source', 'target', true, false, false],
440
-			['source', 'target', true, true, false],
441
-			['source', '/subFolder/target', true, false, false],
442
-			['source', '/subFolder/target', true, true, true],
443
-			['source', '/subFolder/target', false, true, false],
444
-		];
445
-	}
446
-
447
-	public function testIsLocal(): void {
448
-		$this->encryptionManager->expects($this->once())
449
-			->method('isEnabled')->willReturn(true);
450
-		$this->assertFalse($this->instance->isLocal());
451
-	}
452
-
453
-	/**
454
-	 * @dataProvider dataTestRmdir
455
-	 *
456
-	 * @param string $path
457
-	 * @param boolean $rmdirResult
458
-	 * @param boolean $isExcluded
459
-	 * @param boolean $encryptionEnabled
460
-	 */
461
-	public function testRmdir($path, $rmdirResult, $isExcluded, $encryptionEnabled): void {
462
-		$sourceStorage = $this->getMockBuilder('\OC\Files\Storage\Storage')
463
-			->disableOriginalConstructor()->getMock();
464
-
465
-		$util = $this->getMockBuilder('\OC\Encryption\Util')->disableOriginalConstructor()->getMock();
466
-
467
-		$sourceStorage->expects($this->once())->method('rmdir')->willReturn($rmdirResult);
468
-		$util->expects($this->any())->method('isExcluded')->willReturn($isExcluded);
469
-		$this->encryptionManager->expects($this->any())->method('isEnabled')->willReturn($encryptionEnabled);
470
-
471
-		$encryptionStorage = new Encryption(
472
-			[
473
-				'storage' => $sourceStorage,
474
-				'root' => 'foo',
475
-				'mountPoint' => '/mountPoint',
476
-				'mount' => $this->mount
477
-			],
478
-			$this->encryptionManager,
479
-			$util,
480
-			$this->logger,
481
-			$this->file,
482
-			null,
483
-			$this->keyStore,
484
-			$this->mountManager,
485
-			$this->arrayCache,
486
-		);
487
-
488
-
489
-		if ($rmdirResult === true && $isExcluded === false && $encryptionEnabled === true) {
490
-			$this->keyStore->expects($this->once())->method('deleteAllFileKeys')->with('/mountPoint' . $path);
491
-		} else {
492
-			$this->keyStore->expects($this->never())->method('deleteAllFileKeys');
493
-		}
494
-
495
-		$encryptionStorage->rmdir($path);
496
-	}
497
-
498
-	public static function dataTestRmdir(): array {
499
-		return [
500
-			['/file.txt', true, true, true],
501
-			['/file.txt', false, true, true],
502
-			['/file.txt', true, false, true],
503
-			['/file.txt', false, false, true],
504
-			['/file.txt', true, true, false],
505
-			['/file.txt', false, true, false],
506
-			['/file.txt', true, false, false],
507
-			['/file.txt', false, false, false],
508
-		];
509
-	}
510
-
511
-	/**
512
-	 * @dataProvider dataTestCopyKeys
513
-	 *
514
-	 * @param boolean $excluded
515
-	 * @param boolean $expected
516
-	 */
517
-	public function testCopyKeys($excluded, $expected): void {
518
-		$this->util->expects($this->once())
519
-			->method('isExcluded')
520
-			->willReturn($excluded);
521
-
522
-		if ($excluded) {
523
-			$this->keyStore->expects($this->never())->method('copyKeys');
524
-		} else {
525
-			$this->keyStore->expects($this->once())->method('copyKeys')->willReturn(true);
526
-		}
527
-
528
-		$this->assertSame($expected,
529
-			self::invokePrivate($this->instance, 'copyKeys', ['/source', '/target'])
530
-		);
531
-	}
532
-
533
-	public static function dataTestCopyKeys(): array {
534
-		return [
535
-			[true, false],
536
-			[false, true],
537
-		];
538
-	}
539
-
540
-	/**
541
-	 * @dataProvider dataTestGetHeader
542
-	 *
543
-	 * @param string $path
544
-	 * @param bool $strippedPathExists
545
-	 * @param string $strippedPath
546
-	 */
547
-	public function testGetHeader($path, $strippedPathExists, $strippedPath): void {
548
-		$sourceStorage = $this->getMockBuilder('\OC\Files\Storage\Storage')
549
-			->disableOriginalConstructor()->getMock();
550
-
551
-		$util = $this->getMockBuilder('\OC\Encryption\Util')
552
-			->setConstructorArgs(
553
-				[
554
-					new View(),
555
-					new Manager(
556
-						$this->config,
557
-						$this->createMock(ICacheFactory::class),
558
-						$this->createMock(IEventDispatcher::class),
559
-						$this->createMock(LoggerInterface::class),
560
-					),
561
-					$this->groupManager,
562
-					$this->config,
563
-					$this->arrayCache
564
-				]
565
-			)->getMock();
566
-
567
-		$cache = $this->getMockBuilder('\OC\Files\Cache\Cache')
568
-			->disableOriginalConstructor()->getMock();
569
-		$cache->expects($this->any())
570
-			->method('get')
571
-			->willReturnCallback(function ($path) {
572
-				return ['encrypted' => true, 'path' => $path];
573
-			});
574
-
575
-		$instance = $this->getMockBuilder(Encryption::class)
576
-			->setConstructorArgs(
577
-				[
578
-					[
579
-						'storage' => $sourceStorage,
580
-						'root' => 'foo',
581
-						'mountPoint' => '/',
582
-						'mount' => $this->mount
583
-					],
584
-					$this->encryptionManager,
585
-					$util,
586
-					$this->logger,
587
-					$this->file,
588
-					null,
589
-					$this->keyStore,
590
-					$this->mountManager,
591
-					$this->arrayCache,
592
-				]
593
-			)
594
-			->onlyMethods(['getCache', 'readFirstBlock'])
595
-			->getMock();
596
-
597
-		$instance->method('getCache')->willReturn($cache);
598
-
599
-		$util->method('parseRawHeader')
600
-			->willReturn([Util::HEADER_ENCRYPTION_MODULE_KEY => 'OC_DEFAULT_MODULE']);
601
-
602
-		if ($strippedPathExists) {
603
-			$instance->method('readFirstBlock')
604
-				->with($strippedPath)->willReturn('');
605
-		} else {
606
-			$instance->method('readFirstBlock')
607
-				->with($path)->willReturn('');
608
-		}
609
-
610
-		$util->expects($this->once())->method('stripPartialFileExtension')
611
-			->with($path)->willReturn($strippedPath);
612
-		$sourceStorage->expects($this->once())
613
-			->method('is_file')
614
-			->with($strippedPath)
615
-			->willReturn($strippedPathExists);
616
-
617
-		$this->invokePrivate($instance, 'getHeader', [$path]);
618
-	}
619
-
620
-	public static function dataTestGetHeader(): array {
621
-		return [
622
-			['/foo/bar.txt', false, '/foo/bar.txt'],
623
-			['/foo/bar.txt.part', false, '/foo/bar.txt'],
624
-			['/foo/bar.txt.ocTransferId7437493.part', false, '/foo/bar.txt'],
625
-			['/foo/bar.txt.part', true, '/foo/bar.txt'],
626
-			['/foo/bar.txt.ocTransferId7437493.part', true, '/foo/bar.txt'],
627
-		];
628
-	}
629
-
630
-	/**
631
-	 * test if getHeader adds the default module correctly to the header for
632
-	 * legacy files
633
-	 *
634
-	 * @dataProvider dataTestGetHeaderAddLegacyModule
635
-	 */
636
-	public function testGetHeaderAddLegacyModule($header, $isEncrypted, $strippedPathExists, $expected): void {
637
-		$sourceStorage = $this->getMockBuilder(\OC\Files\Storage\Storage::class)
638
-			->disableOriginalConstructor()->getMock();
639
-
640
-		$sourceStorage->expects($this->once())
641
-			->method('is_file')
642
-			->with('test.txt')
643
-			->willReturn($strippedPathExists);
644
-
645
-		$util = $this->getMockBuilder(Util::class)
646
-			->onlyMethods(['stripPartialFileExtension', 'parseRawHeader'])
647
-			->setConstructorArgs([new View(), new Manager(
648
-				$this->config,
649
-				$this->createMock(ICacheFactory::class),
650
-				$this->createMock(IEventDispatcher::class),
651
-				$this->createMock(LoggerInterface::class),
652
-			), $this->groupManager, $this->config, $this->arrayCache])
653
-			->getMock();
654
-		$util->expects($this->any())
655
-			->method('stripPartialFileExtension')
656
-			->willReturnCallback(function ($path) {
657
-				return $path;
658
-			});
659
-
660
-		$cache = $this->createMock(Cache::class);
661
-		$cache->expects($this->any())
662
-			->method('get')
663
-			->willReturnCallback(function ($path) use ($isEncrypted) {
664
-				return ['encrypted' => $isEncrypted, 'path' => $path];
665
-			});
666
-
667
-		$instance = $this->getMockBuilder(Encryption::class)
668
-			->setConstructorArgs(
669
-				[
670
-					[
671
-						'storage' => $sourceStorage,
672
-						'root' => 'foo',
673
-						'mountPoint' => '/',
674
-						'mount' => $this->mount
675
-					],
676
-					$this->encryptionManager,
677
-					$util,
678
-					$this->logger,
679
-					$this->file,
680
-					null,
681
-					$this->keyStore,
682
-					$this->mountManager,
683
-					$this->arrayCache,
684
-				]
685
-			)
686
-			->onlyMethods(['readFirstBlock', 'getCache'])
687
-			->getMock();
688
-
689
-		$instance->method('readFirstBlock')->willReturn('');
690
-
691
-		$util->method(('parseRawHeader'))->willReturn($header);
692
-		$instance->method('getCache')->willReturn($cache);
693
-
694
-		$result = $this->invokePrivate($instance, 'getHeader', ['test.txt']);
695
-		$this->assertSameSize($expected, $result);
696
-		foreach ($result as $key => $value) {
697
-			$this->assertArrayHasKey($key, $expected);
698
-			$this->assertSame($expected[$key], $value);
699
-		}
700
-	}
701
-
702
-	public static function dataTestGetHeaderAddLegacyModule(): array {
703
-		return [
704
-			[['cipher' => 'AES-128'], true, true, ['cipher' => 'AES-128', Util::HEADER_ENCRYPTION_MODULE_KEY => 'OC_DEFAULT_MODULE']],
705
-			[[], true, false, []],
706
-			[[], true, true, [Util::HEADER_ENCRYPTION_MODULE_KEY => 'OC_DEFAULT_MODULE']],
707
-			[[], false, true, []],
708
-		];
709
-	}
710
-
711
-	public static function dataCopyBetweenStorage(): array {
712
-		return [
713
-			[true, true, true],
714
-			[true, false, false],
715
-			[false, true, false],
716
-			[false, false, false],
717
-		];
718
-	}
719
-
720
-	public function testCopyBetweenStorageMinimumEncryptedVersion(): void {
721
-		$storage2 = $this->createMock(\OC\Files\Storage\Storage::class);
722
-
723
-		$sourceInternalPath = $targetInternalPath = 'file.txt';
724
-		$preserveMtime = $isRename = false;
725
-
726
-		$storage2->expects($this->any())
727
-			->method('fopen')
728
-			->willReturnCallback(function ($path, $mode) {
729
-				$temp = OC::$server->getTempManager();
730
-				return fopen($temp->getTemporaryFile(), $mode);
731
-			});
732
-		$storage2->method('getId')
733
-			->willReturn('stroage2');
734
-		$cache = $this->createMock(ICache::class);
735
-		$cache->expects($this->once())
736
-			->method('get')
737
-			->with($sourceInternalPath)
738
-			->willReturn(['encryptedVersion' => 0]);
739
-		$storage2->expects($this->once())
740
-			->method('getCache')
741
-			->willReturn($cache);
742
-		$this->encryptionManager->expects($this->any())
743
-			->method('isEnabled')
744
-			->willReturn(true);
745
-		global $mockedMountPointEncryptionEnabled;
746
-		$mockedMountPointEncryptionEnabled = true;
747
-
748
-		$expectedCachePut = [
749
-			'encrypted' => true,
750
-		];
751
-		$expectedCachePut['encryptedVersion'] = 1;
752
-
753
-		$this->cache->expects($this->once())
754
-			->method('put')
755
-			->with($sourceInternalPath, $expectedCachePut);
756
-
757
-		$this->invokePrivate($this->instance, 'copyBetweenStorage', [$storage2, $sourceInternalPath, $targetInternalPath, $preserveMtime, $isRename]);
758
-
759
-		$this->assertFalse(false);
760
-	}
761
-
762
-	/**
763
-	 * @dataProvider dataCopyBetweenStorage
764
-	 *
765
-	 * @param bool $encryptionEnabled
766
-	 * @param bool $mountPointEncryptionEnabled
767
-	 * @param bool $expectedEncrypted
768
-	 */
769
-	public function testCopyBetweenStorage($encryptionEnabled, $mountPointEncryptionEnabled, $expectedEncrypted): void {
770
-		$storage2 = $this->createMock(\OC\Files\Storage\Storage::class);
771
-
772
-		$sourceInternalPath = $targetInternalPath = 'file.txt';
773
-		$preserveMtime = $isRename = false;
774
-
775
-		$storage2->expects($this->any())
776
-			->method('fopen')
777
-			->willReturnCallback(function ($path, $mode) {
778
-				$temp = OC::$server->getTempManager();
779
-				return fopen($temp->getTemporaryFile(), $mode);
780
-			});
781
-		$storage2->method('getId')
782
-			->willReturn('stroage2');
783
-		if ($expectedEncrypted) {
784
-			$cache = $this->createMock(ICache::class);
785
-			$cache->expects($this->once())
786
-				->method('get')
787
-				->with($sourceInternalPath)
788
-				->willReturn(['encryptedVersion' => 12345]);
789
-			$storage2->expects($this->once())
790
-				->method('getCache')
791
-				->willReturn($cache);
792
-		}
793
-		$this->encryptionManager->expects($this->any())
794
-			->method('isEnabled')
795
-			->willReturn($encryptionEnabled);
796
-		// FIXME can not overwrite the return after definition
797
-		//		$this->mount->expects($this->at(0))
798
-		//			->method('getOption')
799
-		//			->with('encrypt', true)
800
-		//			->willReturn($mountPointEncryptionEnabled);
801
-		global $mockedMountPointEncryptionEnabled;
802
-		$mockedMountPointEncryptionEnabled = $mountPointEncryptionEnabled;
803
-
804
-		$expectedCachePut = [
805
-			'encrypted' => $expectedEncrypted,
806
-		];
807
-		if ($expectedEncrypted === true) {
808
-			$expectedCachePut['encryptedVersion'] = 1;
809
-		}
810
-
811
-		$this->arrayCache->expects($this->never())->method('set');
812
-
813
-		$this->cache->expects($this->once())
814
-			->method('put')
815
-			->with($sourceInternalPath, $expectedCachePut);
816
-
817
-		$this->invokePrivate($this->instance, 'copyBetweenStorage', [$storage2, $sourceInternalPath, $targetInternalPath, $preserveMtime, $isRename]);
818
-
819
-		$this->assertFalse(false);
820
-	}
821
-
822
-	/**
823
-	 * @dataProvider dataTestCopyBetweenStorageVersions
824
-	 *
825
-	 * @param string $sourceInternalPath
826
-	 * @param string $targetInternalPath
827
-	 * @param bool $copyResult
828
-	 * @param bool $encrypted
829
-	 */
830
-	public function testCopyBetweenStorageVersions($sourceInternalPath, $targetInternalPath, $copyResult, $encrypted): void {
831
-		$sourceStorage = $this->createMock(\OC\Files\Storage\Storage::class);
832
-
833
-		$targetStorage = $this->createMock(\OC\Files\Storage\Storage::class);
834
-
835
-		$cache = $this->getMockBuilder('\OC\Files\Cache\Cache')
836
-			->disableOriginalConstructor()->getMock();
837
-
838
-		$mountPoint = '/mountPoint';
839
-
840
-		/** @var Encryption |MockObject $instance */
841
-		$instance = $this->getMockBuilder(Encryption::class)
842
-			->setConstructorArgs(
843
-				[
844
-					[
845
-						'storage' => $targetStorage,
846
-						'root' => 'foo',
847
-						'mountPoint' => $mountPoint,
848
-						'mount' => $this->mount
849
-					],
850
-					$this->encryptionManager,
851
-					$this->util,
852
-					$this->logger,
853
-					$this->file,
854
-					null,
855
-					$this->keyStore,
856
-					$this->mountManager,
857
-					$this->arrayCache
858
-				]
859
-			)
860
-			->onlyMethods(['updateUnencryptedSize', 'getCache'])
861
-			->getMock();
862
-
863
-		$targetStorage->expects($this->once())->method('copyFromStorage')
864
-			->with($sourceStorage, $sourceInternalPath, $targetInternalPath)
865
-			->willReturn($copyResult);
866
-
867
-		$instance->expects($this->any())->method('getCache')
868
-			->willReturn($cache);
869
-
870
-		$this->arrayCache->expects($this->once())->method('set')
871
-			->with('encryption_copy_version_' . $sourceInternalPath, true);
872
-
873
-		if ($copyResult) {
874
-			$cache->expects($this->once())->method('get')
875
-				->with($sourceInternalPath)
876
-				->willReturn(new CacheEntry(['encrypted' => $encrypted, 'size' => 42]));
877
-			if ($encrypted) {
878
-				$instance->expects($this->once())->method('updateUnencryptedSize')
879
-					->with($mountPoint . $targetInternalPath, 42);
880
-			} else {
881
-				$instance->expects($this->never())->method('updateUnencryptedSize');
882
-			}
883
-		} else {
884
-			$instance->expects($this->never())->method('updateUnencryptedSize');
885
-		}
886
-
887
-		$result = $this->invokePrivate(
888
-			$instance,
889
-			'copyBetweenStorage',
890
-			[
891
-				$sourceStorage,
892
-				$sourceInternalPath,
893
-				$targetInternalPath,
894
-				false,
895
-				false
896
-			]
897
-		);
898
-
899
-		$this->assertSame($copyResult, $result);
900
-	}
901
-
902
-	public static function dataTestCopyBetweenStorageVersions(): array {
903
-		return [
904
-			['/files/foo.txt', '/files_versions/foo.txt.768743', true, true],
905
-			['/files/foo.txt', '/files_versions/foo.txt.768743', true, false],
906
-			['/files/foo.txt', '/files_versions/foo.txt.768743', false, true],
907
-			['/files/foo.txt', '/files_versions/foo.txt.768743', false, false],
908
-			['/files_versions/foo.txt.6487634', '/files/foo.txt', true, true],
909
-			['/files_versions/foo.txt.6487634', '/files/foo.txt', true, false],
910
-			['/files_versions/foo.txt.6487634', '/files/foo.txt', false, true],
911
-			['/files_versions/foo.txt.6487634', '/files/foo.txt', false, false],
912
-
913
-		];
914
-	}
915
-
916
-	/**
917
-	 * @dataProvider dataTestIsVersion
918
-	 * @param string $path
919
-	 * @param bool $expected
920
-	 */
921
-	public function testIsVersion($path, $expected): void {
922
-		$this->assertSame($expected,
923
-			$this->invokePrivate($this->instance, 'isVersion', [$path])
924
-		);
925
-	}
926
-
927
-	public static function dataTestIsVersion(): array {
928
-		return [
929
-			['files_versions/foo', true],
930
-			['/files_versions/foo', true],
931
-			['//files_versions/foo', true],
932
-			['files/versions/foo', false],
933
-			['files/files_versions/foo', false],
934
-			['files_versions_test/foo', false],
935
-		];
936
-	}
937
-
938
-	/**
939
-	 * @dataProvider dataTestShouldEncrypt
940
-	 *
941
-	 * @param bool $encryptMountPoint
942
-	 * @param mixed $encryptionModule
943
-	 * @param bool $encryptionModuleShouldEncrypt
944
-	 * @param bool $expected
945
-	 */
946
-	public function testShouldEncrypt(
947
-		$encryptMountPoint,
948
-		$encryptionModule,
949
-		$encryptionModuleShouldEncrypt,
950
-		$expected,
951
-	): void {
952
-		$encryptionManager = $this->createMock(\OC\Encryption\Manager::class);
953
-		$util = $this->createMock(Util::class);
954
-		$fileHelper = $this->createMock(IFile::class);
955
-		$keyStorage = $this->createMock(IStorage::class);
956
-		$mountManager = $this->createMock(\OC\Files\Mount\Manager::class);
957
-		$mount = $this->createMock(IMountPoint::class);
958
-		$arrayCache = $this->createMock(ArrayCache::class);
959
-		$path = '/welcome.txt';
960
-		$fullPath = 'admin/files/welcome.txt';
961
-		$defaultEncryptionModule = $this->createMock(IEncryptionModule::class);
962
-
963
-		$wrapper = $this->getMockBuilder(Encryption::class)
964
-			->setConstructorArgs(
965
-				[
966
-					['mountPoint' => '', 'mount' => $mount, 'storage' => ''],
967
-					$encryptionManager,
968
-					$util,
969
-					$this->logger,
970
-					$fileHelper,
971
-					null,
972
-					$keyStorage,
973
-					$mountManager,
974
-					$arrayCache
975
-				]
976
-			)
977
-			->onlyMethods(['getFullPath', 'getEncryptionModule'])
978
-			->getMock();
979
-
980
-		if ($encryptionModule === true) {
981
-			/** @var IEncryptionModule|MockObject $encryptionModule */
982
-			$encryptionModule = $this->createMock(IEncryptionModule::class);
983
-		}
984
-
985
-		$wrapper->method('getFullPath')->with($path)->willReturn($fullPath);
986
-		$wrapper->expects($encryptMountPoint ? $this->once() : $this->never())
987
-			->method('getEncryptionModule')
988
-			->with($fullPath)
989
-			->willReturnCallback(
990
-				function () use ($encryptionModule) {
991
-					if ($encryptionModule === false) {
992
-						throw new ModuleDoesNotExistsException();
993
-					}
994
-					return $encryptionModule;
995
-				}
996
-			);
997
-		$mount->expects($this->once())->method('getOption')->with('encrypt', true)
998
-			->willReturn($encryptMountPoint);
999
-
1000
-		if ($encryptionModule !== null && $encryptionModule !== false) {
1001
-			$encryptionModule
1002
-				->method('shouldEncrypt')
1003
-				->with($fullPath)
1004
-				->willReturn($encryptionModuleShouldEncrypt);
1005
-		}
1006
-
1007
-		if ($encryptionModule === null) {
1008
-			$encryptionManager->expects($this->once())
1009
-				->method('getEncryptionModule')
1010
-				->willReturn($defaultEncryptionModule);
1011
-		}
1012
-		$defaultEncryptionModule->method('shouldEncrypt')->willReturn(true);
1013
-
1014
-		$result = $this->invokePrivate($wrapper, 'shouldEncrypt', [$path]);
1015
-
1016
-		$this->assertSame($expected, $result);
1017
-	}
1018
-
1019
-	public static function dataTestShouldEncrypt(): array {
1020
-		return [
1021
-			[false, false, false, false],
1022
-			[true, false, false, false],
1023
-			[true, true, false, false],
1024
-			[true, true, true, true],
1025
-			[true, null, false, true],
1026
-		];
1027
-	}
36
+    /**
37
+     * block size will always be 8192 for a PHP stream
38
+     * @see https://bugs.php.net/bug.php?id=21641
39
+     */
40
+    protected int $headerSize = 8192;
41
+    private Temporary $sourceStorage;
42
+    /** @var Encryption&MockObject */
43
+    protected $instance;
44
+    private \OC\Encryption\Keys\Storage&MockObject $keyStore;
45
+    private Util&MockObject $util;
46
+    private \OC\Encryption\Manager&MockObject $encryptionManager;
47
+    private IEncryptionModule&MockObject $encryptionModule;
48
+    private Cache&MockObject $cache;
49
+    private LoggerInterface&MockObject $logger;
50
+    private File&MockObject $file;
51
+    private MountPoint&MockObject $mount;
52
+    private \OC\Files\Mount\Manager&MockObject $mountManager;
53
+    private \OC\Group\Manager&MockObject $groupManager;
54
+    private IConfig&MockObject $config;
55
+    private ArrayCache&MockObject $arrayCache;
56
+    /** dummy unencrypted size */
57
+    private int $dummySize = -1;
58
+
59
+    protected function setUp(): void {
60
+        parent::setUp();
61
+
62
+        $mockModule = $this->buildMockModule();
63
+        $this->encryptionManager = $this->getMockBuilder(\OC\Encryption\Manager::class)
64
+            ->disableOriginalConstructor()
65
+            ->onlyMethods(['getEncryptionModule', 'isEnabled'])
66
+            ->getMock();
67
+        $this->encryptionManager->expects($this->any())
68
+            ->method('getEncryptionModule')
69
+            ->willReturn($mockModule);
70
+
71
+        $this->arrayCache = $this->createMock(ArrayCache::class);
72
+        $this->config = $this->getMockBuilder(IConfig::class)
73
+            ->disableOriginalConstructor()
74
+            ->getMock();
75
+        $this->groupManager = $this->getMockBuilder('\OC\Group\Manager')
76
+            ->disableOriginalConstructor()
77
+            ->getMock();
78
+
79
+        $this->util = $this->getMockBuilder(Util::class)
80
+            ->onlyMethods(['getUidAndFilename', 'isFile', 'isExcluded', 'stripPartialFileExtension'])
81
+            ->setConstructorArgs([new View(), new Manager(
82
+                $this->config,
83
+                $this->createMock(ICacheFactory::class),
84
+                $this->createMock(IEventDispatcher::class),
85
+                $this->createMock(LoggerInterface::class),
86
+            ), $this->groupManager, $this->config, $this->arrayCache])
87
+            ->getMock();
88
+        $this->util->expects($this->any())
89
+            ->method('getUidAndFilename')
90
+            ->willReturnCallback(function ($path) {
91
+                return ['user1', $path];
92
+            });
93
+        $this->util->expects($this->any())
94
+            ->method('stripPartialFileExtension')
95
+            ->willReturnCallback(function ($path) {
96
+                return $path;
97
+            });
98
+
99
+        $this->file = $this->getMockBuilder(File::class)
100
+            ->disableOriginalConstructor()
101
+            ->onlyMethods(['getAccessList'])
102
+            ->getMock();
103
+        $this->file->expects($this->any())->method('getAccessList')->willReturn([]);
104
+
105
+        $this->logger = $this->createMock(LoggerInterface::class);
106
+
107
+        $this->sourceStorage = new Temporary([]);
108
+
109
+        $this->keyStore = $this->createMock(\OC\Encryption\Keys\Storage::class);
110
+
111
+        $this->mount = $this->getMockBuilder(MountPoint::class)
112
+            ->disableOriginalConstructor()
113
+            ->onlyMethods(['getOption'])
114
+            ->getMock();
115
+        $this->mount->expects($this->any())->method('getOption')->willReturnCallback(function ($option, $default) {
116
+            if ($option === 'encrypt' && $default === true) {
117
+                global $mockedMountPointEncryptionEnabled;
118
+                if ($mockedMountPointEncryptionEnabled !== null) {
119
+                    return $mockedMountPointEncryptionEnabled;
120
+                }
121
+            }
122
+            return true;
123
+        });
124
+
125
+        $this->cache = $this->getMockBuilder('\OC\Files\Cache\Cache')
126
+            ->disableOriginalConstructor()->getMock();
127
+        $this->cache->expects($this->any())
128
+            ->method('get')
129
+            ->willReturnCallback(function ($path) {
130
+                return ['encrypted' => false, 'path' => $path];
131
+            });
132
+
133
+        $this->mountManager = $this->createMock(\OC\Files\Mount\Manager::class);
134
+        $this->mountManager->method('findByStorageId')
135
+            ->willReturn([]);
136
+
137
+        $this->instance = $this->getMockBuilder(Encryption::class)
138
+            ->setConstructorArgs(
139
+                [
140
+                    [
141
+                        'storage' => $this->sourceStorage,
142
+                        'root' => 'foo',
143
+                        'mountPoint' => '/',
144
+                        'mount' => $this->mount
145
+                    ],
146
+                    $this->encryptionManager,
147
+                    $this->util,
148
+                    $this->logger,
149
+                    $this->file,
150
+                    null,
151
+                    $this->keyStore,
152
+                    $this->mountManager,
153
+                    $this->arrayCache
154
+                ]
155
+            )
156
+            ->onlyMethods(['getMetaData', 'getCache', 'getEncryptionModule'])
157
+            ->getMock();
158
+
159
+        $this->instance->expects($this->any())
160
+            ->method('getMetaData')
161
+            ->willReturnCallback(function ($path) {
162
+                return ['encrypted' => true, 'size' => $this->dummySize, 'path' => $path];
163
+            });
164
+
165
+        $this->instance->expects($this->any())
166
+            ->method('getCache')
167
+            ->willReturn($this->cache);
168
+
169
+        $this->instance->expects($this->any())
170
+            ->method('getEncryptionModule')
171
+            ->willReturn($mockModule);
172
+    }
173
+
174
+    protected function buildMockModule(): IEncryptionModule&MockObject {
175
+        $this->encryptionModule = $this->getMockBuilder('\OCP\Encryption\IEncryptionModule')
176
+            ->disableOriginalConstructor()
177
+            ->onlyMethods(['getId', 'getDisplayName', 'begin', 'end', 'encrypt', 'decrypt', 'update', 'shouldEncrypt', 'getUnencryptedBlockSize', 'isReadable', 'encryptAll', 'prepareDecryptAll', 'isReadyForUser', 'needDetailedAccessList'])
178
+            ->getMock();
179
+
180
+        $this->encryptionModule->expects($this->any())->method('getId')->willReturn('UNIT_TEST_MODULE');
181
+        $this->encryptionModule->expects($this->any())->method('getDisplayName')->willReturn('Unit test module');
182
+        $this->encryptionModule->expects($this->any())->method('begin')->willReturn([]);
183
+        $this->encryptionModule->expects($this->any())->method('end')->willReturn('');
184
+        $this->encryptionModule->expects($this->any())->method('encrypt')->willReturnArgument(0);
185
+        $this->encryptionModule->expects($this->any())->method('decrypt')->willReturnArgument(0);
186
+        $this->encryptionModule->expects($this->any())->method('update')->willReturn(true);
187
+        $this->encryptionModule->expects($this->any())->method('shouldEncrypt')->willReturn(true);
188
+        $this->encryptionModule->expects($this->any())->method('getUnencryptedBlockSize')->willReturn(8192);
189
+        $this->encryptionModule->expects($this->any())->method('isReadable')->willReturn(true);
190
+        $this->encryptionModule->expects($this->any())->method('needDetailedAccessList')->willReturn(false);
191
+        return $this->encryptionModule;
192
+    }
193
+
194
+    /**
195
+     * @dataProvider dataTestGetMetaData
196
+     *
197
+     * @param string $path
198
+     * @param array $metaData
199
+     * @param bool $encrypted
200
+     * @param bool $unencryptedSizeSet
201
+     * @param int $storedUnencryptedSize
202
+     * @param array $expected
203
+     */
204
+    public function testGetMetaData($path, $metaData, $encrypted, $unencryptedSizeSet, $storedUnencryptedSize, $expected): void {
205
+        $sourceStorage = $this->getMockBuilder('\OC\Files\Storage\Storage')
206
+            ->disableOriginalConstructor()->getMock();
207
+
208
+        $cache = $this->getMockBuilder('\OC\Files\Cache\Cache')
209
+            ->disableOriginalConstructor()->getMock();
210
+        $cache->expects($this->any())
211
+            ->method('get')
212
+            ->willReturnCallback(
213
+                function ($path) use ($encrypted) {
214
+                    return new CacheEntry(['encrypted' => $encrypted, 'path' => $path, 'size' => 0, 'fileid' => 1]);
215
+                }
216
+            );
217
+
218
+        $this->instance = $this->getMockBuilder(Encryption::class)
219
+            ->setConstructorArgs(
220
+                [
221
+                    [
222
+                        'storage' => $sourceStorage,
223
+                        'root' => 'foo',
224
+                        'mountPoint' => '/',
225
+                        'mount' => $this->mount
226
+                    ],
227
+                    $this->encryptionManager,
228
+                    $this->util,
229
+                    $this->logger,
230
+                    $this->file,
231
+                    null,
232
+                    $this->keyStore,
233
+                    $this->mountManager,
234
+                    $this->arrayCache,
235
+                ]
236
+            )
237
+            ->onlyMethods(['getCache', 'verifyUnencryptedSize'])
238
+            ->getMock();
239
+
240
+        if ($unencryptedSizeSet) {
241
+            $this->invokePrivate($this->instance, 'unencryptedSize', [[$path => $storedUnencryptedSize]]);
242
+        }
243
+
244
+        $fileEntry = $this->getMockBuilder('\OC\Files\Cache\Cache')
245
+            ->disableOriginalConstructor()->getMock();
246
+        $sourceStorage->expects($this->once())->method('getMetaData')->with($path)
247
+            ->willReturn($metaData);
248
+        $sourceStorage->expects($this->any())
249
+            ->method('getCache')
250
+            ->with($path)
251
+            ->willReturn($fileEntry);
252
+        if ($metaData !== null) {
253
+            $fileEntry->expects($this->any())
254
+                ->method('get')
255
+                ->with($metaData['fileid']);
256
+        }
257
+
258
+        $this->instance->expects($this->any())->method('getCache')->willReturn($cache);
259
+        if ($expected !== null) {
260
+            $this->instance->expects($this->any())->method('verifyUnencryptedSize')
261
+                ->with($path, 0)->willReturn($expected['size']);
262
+        }
263
+
264
+        $result = $this->instance->getMetaData($path);
265
+        if (isset($expected['encrypted'])) {
266
+            $this->assertSame($expected['encrypted'], (bool)$result['encrypted']);
267
+
268
+            if (isset($expected['encryptedVersion'])) {
269
+                $this->assertSame($expected['encryptedVersion'], $result['encryptedVersion']);
270
+            }
271
+        }
272
+
273
+        if ($expected !== null) {
274
+            $this->assertSame($expected['size'], $result['size']);
275
+        } else {
276
+            $this->assertSame(null, $result);
277
+        }
278
+    }
279
+
280
+    public static function dataTestGetMetaData(): array {
281
+        return [
282
+            ['/test.txt', ['size' => 42, 'encrypted' => 2, 'encryptedVersion' => 2, 'fileid' => 1], true, true, 12, ['size' => 12, 'encrypted' => true, 'encryptedVersion' => 2]],
283
+            ['/test.txt', null, true, true, 12, null],
284
+            ['/test.txt', ['size' => 42, 'encrypted' => 0, 'fileid' => 1], false, false, 12, ['size' => 42, 'encrypted' => false]],
285
+            ['/test.txt', ['size' => 42, 'encrypted' => false, 'fileid' => 1], true, false, 12, ['size' => 12, 'encrypted' => true]]
286
+        ];
287
+    }
288
+
289
+    public function testFilesize(): void {
290
+        $cache = $this->getMockBuilder('\OC\Files\Cache\Cache')
291
+            ->disableOriginalConstructor()->getMock();
292
+        $cache->expects($this->any())
293
+            ->method('get')
294
+            ->willReturn(new CacheEntry(['encrypted' => true, 'path' => '/test.txt', 'size' => 0, 'fileid' => 1]));
295
+
296
+        $this->instance = $this->getMockBuilder(Encryption::class)
297
+            ->setConstructorArgs(
298
+                [
299
+                    [
300
+                        'storage' => $this->sourceStorage,
301
+                        'root' => 'foo',
302
+                        'mountPoint' => '/',
303
+                        'mount' => $this->mount
304
+                    ],
305
+                    $this->encryptionManager,
306
+                    $this->util,
307
+                    $this->logger,
308
+                    $this->file,
309
+                    null,
310
+                    $this->keyStore,
311
+                    $this->mountManager,
312
+                    $this->arrayCache,
313
+                ]
314
+            )
315
+            ->onlyMethods(['getCache', 'verifyUnencryptedSize'])
316
+            ->getMock();
317
+
318
+        $this->instance->expects($this->any())->method('getCache')->willReturn($cache);
319
+        $this->instance->expects($this->any())->method('verifyUnencryptedSize')
320
+            ->willReturn(42);
321
+
322
+
323
+        $this->assertSame(42,
324
+            $this->instance->filesize('/test.txt')
325
+        );
326
+    }
327
+
328
+    /**
329
+     * @dataProvider dataTestVerifyUnencryptedSize
330
+     *
331
+     * @param int $encryptedSize
332
+     * @param int $unencryptedSize
333
+     * @param bool $failure
334
+     * @param int $expected
335
+     */
336
+    public function testVerifyUnencryptedSize($encryptedSize, $unencryptedSize, $failure, $expected): void {
337
+        $sourceStorage = $this->getMockBuilder('\OC\Files\Storage\Storage')
338
+            ->disableOriginalConstructor()->getMock();
339
+
340
+        $this->instance = $this->getMockBuilder(Encryption::class)
341
+            ->setConstructorArgs(
342
+                [
343
+                    [
344
+                        'storage' => $sourceStorage,
345
+                        'root' => 'foo',
346
+                        'mountPoint' => '/',
347
+                        'mount' => $this->mount
348
+                    ],
349
+                    $this->encryptionManager,
350
+                    $this->util,
351
+                    $this->logger,
352
+                    $this->file,
353
+                    null,
354
+                    $this->keyStore,
355
+                    $this->mountManager,
356
+                    $this->arrayCache,
357
+                ]
358
+            )
359
+            ->onlyMethods(['fixUnencryptedSize'])
360
+            ->getMock();
361
+
362
+        $sourceStorage->expects($this->once())->method('filesize')->willReturn($encryptedSize);
363
+
364
+        $this->instance->expects($this->any())->method('fixUnencryptedSize')
365
+            ->with('/test.txt', $encryptedSize, $unencryptedSize)
366
+            ->willReturnCallback(
367
+                function () use ($failure, $expected) {
368
+                    if ($failure) {
369
+                        throw new Exception();
370
+                    } else {
371
+                        return $expected;
372
+                    }
373
+                }
374
+            );
375
+
376
+        $this->assertSame(
377
+            $expected,
378
+            $this->invokePrivate($this->instance, 'verifyUnencryptedSize', ['/test.txt', $unencryptedSize])
379
+        );
380
+    }
381
+
382
+    public static function dataTestVerifyUnencryptedSize(): array {
383
+        return [
384
+            [120, 80, false, 80],
385
+            [120, 120, false, 80],
386
+            [120, -1, false, 80],
387
+            [120, -1, true, -1]
388
+        ];
389
+    }
390
+
391
+    /**
392
+     * @dataProvider dataTestCopyAndRename
393
+     *
394
+     * @param string $source
395
+     * @param string $target
396
+     * @param $encryptionEnabled
397
+     * @param boolean $renameKeysReturn
398
+     */
399
+    public function testRename($source,
400
+        $target,
401
+        $encryptionEnabled,
402
+        $renameKeysReturn): void {
403
+        if ($encryptionEnabled) {
404
+            $this->keyStore
405
+                ->expects($this->once())
406
+                ->method('renameKeys')
407
+                ->willReturn($renameKeysReturn);
408
+        } else {
409
+            $this->keyStore
410
+                ->expects($this->never())->method('renameKeys');
411
+        }
412
+        $this->util->expects($this->any())
413
+            ->method('isFile')->willReturn(true);
414
+        $this->encryptionManager->expects($this->once())
415
+            ->method('isEnabled')->willReturn($encryptionEnabled);
416
+
417
+        $this->instance->mkdir($source);
418
+        $this->instance->mkdir(dirname($target));
419
+        $this->instance->rename($source, $target);
420
+    }
421
+
422
+    public function testCopyEncryption(): void {
423
+        $this->instance->file_put_contents('source.txt', 'bar');
424
+        $this->instance->copy('source.txt', 'target.txt');
425
+        $this->assertSame('bar', $this->instance->file_get_contents('target.txt'));
426
+        $targetMeta = $this->instance->getMetaData('target.txt');
427
+        $sourceMeta = $this->instance->getMetaData('source.txt');
428
+        $this->assertSame($sourceMeta['encrypted'], $targetMeta['encrypted']);
429
+        $this->assertSame($sourceMeta['size'], $targetMeta['size']);
430
+    }
431
+
432
+    /**
433
+     * data provider for testCopyTesting() and dataTestCopyAndRename()
434
+     *
435
+     * @return array
436
+     */
437
+    public static function dataTestCopyAndRename(): array {
438
+        return [
439
+            ['source', 'target', true, false, false],
440
+            ['source', 'target', true, true, false],
441
+            ['source', '/subFolder/target', true, false, false],
442
+            ['source', '/subFolder/target', true, true, true],
443
+            ['source', '/subFolder/target', false, true, false],
444
+        ];
445
+    }
446
+
447
+    public function testIsLocal(): void {
448
+        $this->encryptionManager->expects($this->once())
449
+            ->method('isEnabled')->willReturn(true);
450
+        $this->assertFalse($this->instance->isLocal());
451
+    }
452
+
453
+    /**
454
+     * @dataProvider dataTestRmdir
455
+     *
456
+     * @param string $path
457
+     * @param boolean $rmdirResult
458
+     * @param boolean $isExcluded
459
+     * @param boolean $encryptionEnabled
460
+     */
461
+    public function testRmdir($path, $rmdirResult, $isExcluded, $encryptionEnabled): void {
462
+        $sourceStorage = $this->getMockBuilder('\OC\Files\Storage\Storage')
463
+            ->disableOriginalConstructor()->getMock();
464
+
465
+        $util = $this->getMockBuilder('\OC\Encryption\Util')->disableOriginalConstructor()->getMock();
466
+
467
+        $sourceStorage->expects($this->once())->method('rmdir')->willReturn($rmdirResult);
468
+        $util->expects($this->any())->method('isExcluded')->willReturn($isExcluded);
469
+        $this->encryptionManager->expects($this->any())->method('isEnabled')->willReturn($encryptionEnabled);
470
+
471
+        $encryptionStorage = new Encryption(
472
+            [
473
+                'storage' => $sourceStorage,
474
+                'root' => 'foo',
475
+                'mountPoint' => '/mountPoint',
476
+                'mount' => $this->mount
477
+            ],
478
+            $this->encryptionManager,
479
+            $util,
480
+            $this->logger,
481
+            $this->file,
482
+            null,
483
+            $this->keyStore,
484
+            $this->mountManager,
485
+            $this->arrayCache,
486
+        );
487
+
488
+
489
+        if ($rmdirResult === true && $isExcluded === false && $encryptionEnabled === true) {
490
+            $this->keyStore->expects($this->once())->method('deleteAllFileKeys')->with('/mountPoint' . $path);
491
+        } else {
492
+            $this->keyStore->expects($this->never())->method('deleteAllFileKeys');
493
+        }
494
+
495
+        $encryptionStorage->rmdir($path);
496
+    }
497
+
498
+    public static function dataTestRmdir(): array {
499
+        return [
500
+            ['/file.txt', true, true, true],
501
+            ['/file.txt', false, true, true],
502
+            ['/file.txt', true, false, true],
503
+            ['/file.txt', false, false, true],
504
+            ['/file.txt', true, true, false],
505
+            ['/file.txt', false, true, false],
506
+            ['/file.txt', true, false, false],
507
+            ['/file.txt', false, false, false],
508
+        ];
509
+    }
510
+
511
+    /**
512
+     * @dataProvider dataTestCopyKeys
513
+     *
514
+     * @param boolean $excluded
515
+     * @param boolean $expected
516
+     */
517
+    public function testCopyKeys($excluded, $expected): void {
518
+        $this->util->expects($this->once())
519
+            ->method('isExcluded')
520
+            ->willReturn($excluded);
521
+
522
+        if ($excluded) {
523
+            $this->keyStore->expects($this->never())->method('copyKeys');
524
+        } else {
525
+            $this->keyStore->expects($this->once())->method('copyKeys')->willReturn(true);
526
+        }
527
+
528
+        $this->assertSame($expected,
529
+            self::invokePrivate($this->instance, 'copyKeys', ['/source', '/target'])
530
+        );
531
+    }
532
+
533
+    public static function dataTestCopyKeys(): array {
534
+        return [
535
+            [true, false],
536
+            [false, true],
537
+        ];
538
+    }
539
+
540
+    /**
541
+     * @dataProvider dataTestGetHeader
542
+     *
543
+     * @param string $path
544
+     * @param bool $strippedPathExists
545
+     * @param string $strippedPath
546
+     */
547
+    public function testGetHeader($path, $strippedPathExists, $strippedPath): void {
548
+        $sourceStorage = $this->getMockBuilder('\OC\Files\Storage\Storage')
549
+            ->disableOriginalConstructor()->getMock();
550
+
551
+        $util = $this->getMockBuilder('\OC\Encryption\Util')
552
+            ->setConstructorArgs(
553
+                [
554
+                    new View(),
555
+                    new Manager(
556
+                        $this->config,
557
+                        $this->createMock(ICacheFactory::class),
558
+                        $this->createMock(IEventDispatcher::class),
559
+                        $this->createMock(LoggerInterface::class),
560
+                    ),
561
+                    $this->groupManager,
562
+                    $this->config,
563
+                    $this->arrayCache
564
+                ]
565
+            )->getMock();
566
+
567
+        $cache = $this->getMockBuilder('\OC\Files\Cache\Cache')
568
+            ->disableOriginalConstructor()->getMock();
569
+        $cache->expects($this->any())
570
+            ->method('get')
571
+            ->willReturnCallback(function ($path) {
572
+                return ['encrypted' => true, 'path' => $path];
573
+            });
574
+
575
+        $instance = $this->getMockBuilder(Encryption::class)
576
+            ->setConstructorArgs(
577
+                [
578
+                    [
579
+                        'storage' => $sourceStorage,
580
+                        'root' => 'foo',
581
+                        'mountPoint' => '/',
582
+                        'mount' => $this->mount
583
+                    ],
584
+                    $this->encryptionManager,
585
+                    $util,
586
+                    $this->logger,
587
+                    $this->file,
588
+                    null,
589
+                    $this->keyStore,
590
+                    $this->mountManager,
591
+                    $this->arrayCache,
592
+                ]
593
+            )
594
+            ->onlyMethods(['getCache', 'readFirstBlock'])
595
+            ->getMock();
596
+
597
+        $instance->method('getCache')->willReturn($cache);
598
+
599
+        $util->method('parseRawHeader')
600
+            ->willReturn([Util::HEADER_ENCRYPTION_MODULE_KEY => 'OC_DEFAULT_MODULE']);
601
+
602
+        if ($strippedPathExists) {
603
+            $instance->method('readFirstBlock')
604
+                ->with($strippedPath)->willReturn('');
605
+        } else {
606
+            $instance->method('readFirstBlock')
607
+                ->with($path)->willReturn('');
608
+        }
609
+
610
+        $util->expects($this->once())->method('stripPartialFileExtension')
611
+            ->with($path)->willReturn($strippedPath);
612
+        $sourceStorage->expects($this->once())
613
+            ->method('is_file')
614
+            ->with($strippedPath)
615
+            ->willReturn($strippedPathExists);
616
+
617
+        $this->invokePrivate($instance, 'getHeader', [$path]);
618
+    }
619
+
620
+    public static function dataTestGetHeader(): array {
621
+        return [
622
+            ['/foo/bar.txt', false, '/foo/bar.txt'],
623
+            ['/foo/bar.txt.part', false, '/foo/bar.txt'],
624
+            ['/foo/bar.txt.ocTransferId7437493.part', false, '/foo/bar.txt'],
625
+            ['/foo/bar.txt.part', true, '/foo/bar.txt'],
626
+            ['/foo/bar.txt.ocTransferId7437493.part', true, '/foo/bar.txt'],
627
+        ];
628
+    }
629
+
630
+    /**
631
+     * test if getHeader adds the default module correctly to the header for
632
+     * legacy files
633
+     *
634
+     * @dataProvider dataTestGetHeaderAddLegacyModule
635
+     */
636
+    public function testGetHeaderAddLegacyModule($header, $isEncrypted, $strippedPathExists, $expected): void {
637
+        $sourceStorage = $this->getMockBuilder(\OC\Files\Storage\Storage::class)
638
+            ->disableOriginalConstructor()->getMock();
639
+
640
+        $sourceStorage->expects($this->once())
641
+            ->method('is_file')
642
+            ->with('test.txt')
643
+            ->willReturn($strippedPathExists);
644
+
645
+        $util = $this->getMockBuilder(Util::class)
646
+            ->onlyMethods(['stripPartialFileExtension', 'parseRawHeader'])
647
+            ->setConstructorArgs([new View(), new Manager(
648
+                $this->config,
649
+                $this->createMock(ICacheFactory::class),
650
+                $this->createMock(IEventDispatcher::class),
651
+                $this->createMock(LoggerInterface::class),
652
+            ), $this->groupManager, $this->config, $this->arrayCache])
653
+            ->getMock();
654
+        $util->expects($this->any())
655
+            ->method('stripPartialFileExtension')
656
+            ->willReturnCallback(function ($path) {
657
+                return $path;
658
+            });
659
+
660
+        $cache = $this->createMock(Cache::class);
661
+        $cache->expects($this->any())
662
+            ->method('get')
663
+            ->willReturnCallback(function ($path) use ($isEncrypted) {
664
+                return ['encrypted' => $isEncrypted, 'path' => $path];
665
+            });
666
+
667
+        $instance = $this->getMockBuilder(Encryption::class)
668
+            ->setConstructorArgs(
669
+                [
670
+                    [
671
+                        'storage' => $sourceStorage,
672
+                        'root' => 'foo',
673
+                        'mountPoint' => '/',
674
+                        'mount' => $this->mount
675
+                    ],
676
+                    $this->encryptionManager,
677
+                    $util,
678
+                    $this->logger,
679
+                    $this->file,
680
+                    null,
681
+                    $this->keyStore,
682
+                    $this->mountManager,
683
+                    $this->arrayCache,
684
+                ]
685
+            )
686
+            ->onlyMethods(['readFirstBlock', 'getCache'])
687
+            ->getMock();
688
+
689
+        $instance->method('readFirstBlock')->willReturn('');
690
+
691
+        $util->method(('parseRawHeader'))->willReturn($header);
692
+        $instance->method('getCache')->willReturn($cache);
693
+
694
+        $result = $this->invokePrivate($instance, 'getHeader', ['test.txt']);
695
+        $this->assertSameSize($expected, $result);
696
+        foreach ($result as $key => $value) {
697
+            $this->assertArrayHasKey($key, $expected);
698
+            $this->assertSame($expected[$key], $value);
699
+        }
700
+    }
701
+
702
+    public static function dataTestGetHeaderAddLegacyModule(): array {
703
+        return [
704
+            [['cipher' => 'AES-128'], true, true, ['cipher' => 'AES-128', Util::HEADER_ENCRYPTION_MODULE_KEY => 'OC_DEFAULT_MODULE']],
705
+            [[], true, false, []],
706
+            [[], true, true, [Util::HEADER_ENCRYPTION_MODULE_KEY => 'OC_DEFAULT_MODULE']],
707
+            [[], false, true, []],
708
+        ];
709
+    }
710
+
711
+    public static function dataCopyBetweenStorage(): array {
712
+        return [
713
+            [true, true, true],
714
+            [true, false, false],
715
+            [false, true, false],
716
+            [false, false, false],
717
+        ];
718
+    }
719
+
720
+    public function testCopyBetweenStorageMinimumEncryptedVersion(): void {
721
+        $storage2 = $this->createMock(\OC\Files\Storage\Storage::class);
722
+
723
+        $sourceInternalPath = $targetInternalPath = 'file.txt';
724
+        $preserveMtime = $isRename = false;
725
+
726
+        $storage2->expects($this->any())
727
+            ->method('fopen')
728
+            ->willReturnCallback(function ($path, $mode) {
729
+                $temp = OC::$server->getTempManager();
730
+                return fopen($temp->getTemporaryFile(), $mode);
731
+            });
732
+        $storage2->method('getId')
733
+            ->willReturn('stroage2');
734
+        $cache = $this->createMock(ICache::class);
735
+        $cache->expects($this->once())
736
+            ->method('get')
737
+            ->with($sourceInternalPath)
738
+            ->willReturn(['encryptedVersion' => 0]);
739
+        $storage2->expects($this->once())
740
+            ->method('getCache')
741
+            ->willReturn($cache);
742
+        $this->encryptionManager->expects($this->any())
743
+            ->method('isEnabled')
744
+            ->willReturn(true);
745
+        global $mockedMountPointEncryptionEnabled;
746
+        $mockedMountPointEncryptionEnabled = true;
747
+
748
+        $expectedCachePut = [
749
+            'encrypted' => true,
750
+        ];
751
+        $expectedCachePut['encryptedVersion'] = 1;
752
+
753
+        $this->cache->expects($this->once())
754
+            ->method('put')
755
+            ->with($sourceInternalPath, $expectedCachePut);
756
+
757
+        $this->invokePrivate($this->instance, 'copyBetweenStorage', [$storage2, $sourceInternalPath, $targetInternalPath, $preserveMtime, $isRename]);
758
+
759
+        $this->assertFalse(false);
760
+    }
761
+
762
+    /**
763
+     * @dataProvider dataCopyBetweenStorage
764
+     *
765
+     * @param bool $encryptionEnabled
766
+     * @param bool $mountPointEncryptionEnabled
767
+     * @param bool $expectedEncrypted
768
+     */
769
+    public function testCopyBetweenStorage($encryptionEnabled, $mountPointEncryptionEnabled, $expectedEncrypted): void {
770
+        $storage2 = $this->createMock(\OC\Files\Storage\Storage::class);
771
+
772
+        $sourceInternalPath = $targetInternalPath = 'file.txt';
773
+        $preserveMtime = $isRename = false;
774
+
775
+        $storage2->expects($this->any())
776
+            ->method('fopen')
777
+            ->willReturnCallback(function ($path, $mode) {
778
+                $temp = OC::$server->getTempManager();
779
+                return fopen($temp->getTemporaryFile(), $mode);
780
+            });
781
+        $storage2->method('getId')
782
+            ->willReturn('stroage2');
783
+        if ($expectedEncrypted) {
784
+            $cache = $this->createMock(ICache::class);
785
+            $cache->expects($this->once())
786
+                ->method('get')
787
+                ->with($sourceInternalPath)
788
+                ->willReturn(['encryptedVersion' => 12345]);
789
+            $storage2->expects($this->once())
790
+                ->method('getCache')
791
+                ->willReturn($cache);
792
+        }
793
+        $this->encryptionManager->expects($this->any())
794
+            ->method('isEnabled')
795
+            ->willReturn($encryptionEnabled);
796
+        // FIXME can not overwrite the return after definition
797
+        //		$this->mount->expects($this->at(0))
798
+        //			->method('getOption')
799
+        //			->with('encrypt', true)
800
+        //			->willReturn($mountPointEncryptionEnabled);
801
+        global $mockedMountPointEncryptionEnabled;
802
+        $mockedMountPointEncryptionEnabled = $mountPointEncryptionEnabled;
803
+
804
+        $expectedCachePut = [
805
+            'encrypted' => $expectedEncrypted,
806
+        ];
807
+        if ($expectedEncrypted === true) {
808
+            $expectedCachePut['encryptedVersion'] = 1;
809
+        }
810
+
811
+        $this->arrayCache->expects($this->never())->method('set');
812
+
813
+        $this->cache->expects($this->once())
814
+            ->method('put')
815
+            ->with($sourceInternalPath, $expectedCachePut);
816
+
817
+        $this->invokePrivate($this->instance, 'copyBetweenStorage', [$storage2, $sourceInternalPath, $targetInternalPath, $preserveMtime, $isRename]);
818
+
819
+        $this->assertFalse(false);
820
+    }
821
+
822
+    /**
823
+     * @dataProvider dataTestCopyBetweenStorageVersions
824
+     *
825
+     * @param string $sourceInternalPath
826
+     * @param string $targetInternalPath
827
+     * @param bool $copyResult
828
+     * @param bool $encrypted
829
+     */
830
+    public function testCopyBetweenStorageVersions($sourceInternalPath, $targetInternalPath, $copyResult, $encrypted): void {
831
+        $sourceStorage = $this->createMock(\OC\Files\Storage\Storage::class);
832
+
833
+        $targetStorage = $this->createMock(\OC\Files\Storage\Storage::class);
834
+
835
+        $cache = $this->getMockBuilder('\OC\Files\Cache\Cache')
836
+            ->disableOriginalConstructor()->getMock();
837
+
838
+        $mountPoint = '/mountPoint';
839
+
840
+        /** @var Encryption |MockObject $instance */
841
+        $instance = $this->getMockBuilder(Encryption::class)
842
+            ->setConstructorArgs(
843
+                [
844
+                    [
845
+                        'storage' => $targetStorage,
846
+                        'root' => 'foo',
847
+                        'mountPoint' => $mountPoint,
848
+                        'mount' => $this->mount
849
+                    ],
850
+                    $this->encryptionManager,
851
+                    $this->util,
852
+                    $this->logger,
853
+                    $this->file,
854
+                    null,
855
+                    $this->keyStore,
856
+                    $this->mountManager,
857
+                    $this->arrayCache
858
+                ]
859
+            )
860
+            ->onlyMethods(['updateUnencryptedSize', 'getCache'])
861
+            ->getMock();
862
+
863
+        $targetStorage->expects($this->once())->method('copyFromStorage')
864
+            ->with($sourceStorage, $sourceInternalPath, $targetInternalPath)
865
+            ->willReturn($copyResult);
866
+
867
+        $instance->expects($this->any())->method('getCache')
868
+            ->willReturn($cache);
869
+
870
+        $this->arrayCache->expects($this->once())->method('set')
871
+            ->with('encryption_copy_version_' . $sourceInternalPath, true);
872
+
873
+        if ($copyResult) {
874
+            $cache->expects($this->once())->method('get')
875
+                ->with($sourceInternalPath)
876
+                ->willReturn(new CacheEntry(['encrypted' => $encrypted, 'size' => 42]));
877
+            if ($encrypted) {
878
+                $instance->expects($this->once())->method('updateUnencryptedSize')
879
+                    ->with($mountPoint . $targetInternalPath, 42);
880
+            } else {
881
+                $instance->expects($this->never())->method('updateUnencryptedSize');
882
+            }
883
+        } else {
884
+            $instance->expects($this->never())->method('updateUnencryptedSize');
885
+        }
886
+
887
+        $result = $this->invokePrivate(
888
+            $instance,
889
+            'copyBetweenStorage',
890
+            [
891
+                $sourceStorage,
892
+                $sourceInternalPath,
893
+                $targetInternalPath,
894
+                false,
895
+                false
896
+            ]
897
+        );
898
+
899
+        $this->assertSame($copyResult, $result);
900
+    }
901
+
902
+    public static function dataTestCopyBetweenStorageVersions(): array {
903
+        return [
904
+            ['/files/foo.txt', '/files_versions/foo.txt.768743', true, true],
905
+            ['/files/foo.txt', '/files_versions/foo.txt.768743', true, false],
906
+            ['/files/foo.txt', '/files_versions/foo.txt.768743', false, true],
907
+            ['/files/foo.txt', '/files_versions/foo.txt.768743', false, false],
908
+            ['/files_versions/foo.txt.6487634', '/files/foo.txt', true, true],
909
+            ['/files_versions/foo.txt.6487634', '/files/foo.txt', true, false],
910
+            ['/files_versions/foo.txt.6487634', '/files/foo.txt', false, true],
911
+            ['/files_versions/foo.txt.6487634', '/files/foo.txt', false, false],
912
+
913
+        ];
914
+    }
915
+
916
+    /**
917
+     * @dataProvider dataTestIsVersion
918
+     * @param string $path
919
+     * @param bool $expected
920
+     */
921
+    public function testIsVersion($path, $expected): void {
922
+        $this->assertSame($expected,
923
+            $this->invokePrivate($this->instance, 'isVersion', [$path])
924
+        );
925
+    }
926
+
927
+    public static function dataTestIsVersion(): array {
928
+        return [
929
+            ['files_versions/foo', true],
930
+            ['/files_versions/foo', true],
931
+            ['//files_versions/foo', true],
932
+            ['files/versions/foo', false],
933
+            ['files/files_versions/foo', false],
934
+            ['files_versions_test/foo', false],
935
+        ];
936
+    }
937
+
938
+    /**
939
+     * @dataProvider dataTestShouldEncrypt
940
+     *
941
+     * @param bool $encryptMountPoint
942
+     * @param mixed $encryptionModule
943
+     * @param bool $encryptionModuleShouldEncrypt
944
+     * @param bool $expected
945
+     */
946
+    public function testShouldEncrypt(
947
+        $encryptMountPoint,
948
+        $encryptionModule,
949
+        $encryptionModuleShouldEncrypt,
950
+        $expected,
951
+    ): void {
952
+        $encryptionManager = $this->createMock(\OC\Encryption\Manager::class);
953
+        $util = $this->createMock(Util::class);
954
+        $fileHelper = $this->createMock(IFile::class);
955
+        $keyStorage = $this->createMock(IStorage::class);
956
+        $mountManager = $this->createMock(\OC\Files\Mount\Manager::class);
957
+        $mount = $this->createMock(IMountPoint::class);
958
+        $arrayCache = $this->createMock(ArrayCache::class);
959
+        $path = '/welcome.txt';
960
+        $fullPath = 'admin/files/welcome.txt';
961
+        $defaultEncryptionModule = $this->createMock(IEncryptionModule::class);
962
+
963
+        $wrapper = $this->getMockBuilder(Encryption::class)
964
+            ->setConstructorArgs(
965
+                [
966
+                    ['mountPoint' => '', 'mount' => $mount, 'storage' => ''],
967
+                    $encryptionManager,
968
+                    $util,
969
+                    $this->logger,
970
+                    $fileHelper,
971
+                    null,
972
+                    $keyStorage,
973
+                    $mountManager,
974
+                    $arrayCache
975
+                ]
976
+            )
977
+            ->onlyMethods(['getFullPath', 'getEncryptionModule'])
978
+            ->getMock();
979
+
980
+        if ($encryptionModule === true) {
981
+            /** @var IEncryptionModule|MockObject $encryptionModule */
982
+            $encryptionModule = $this->createMock(IEncryptionModule::class);
983
+        }
984
+
985
+        $wrapper->method('getFullPath')->with($path)->willReturn($fullPath);
986
+        $wrapper->expects($encryptMountPoint ? $this->once() : $this->never())
987
+            ->method('getEncryptionModule')
988
+            ->with($fullPath)
989
+            ->willReturnCallback(
990
+                function () use ($encryptionModule) {
991
+                    if ($encryptionModule === false) {
992
+                        throw new ModuleDoesNotExistsException();
993
+                    }
994
+                    return $encryptionModule;
995
+                }
996
+            );
997
+        $mount->expects($this->once())->method('getOption')->with('encrypt', true)
998
+            ->willReturn($encryptMountPoint);
999
+
1000
+        if ($encryptionModule !== null && $encryptionModule !== false) {
1001
+            $encryptionModule
1002
+                ->method('shouldEncrypt')
1003
+                ->with($fullPath)
1004
+                ->willReturn($encryptionModuleShouldEncrypt);
1005
+        }
1006
+
1007
+        if ($encryptionModule === null) {
1008
+            $encryptionManager->expects($this->once())
1009
+                ->method('getEncryptionModule')
1010
+                ->willReturn($defaultEncryptionModule);
1011
+        }
1012
+        $defaultEncryptionModule->method('shouldEncrypt')->willReturn(true);
1013
+
1014
+        $result = $this->invokePrivate($wrapper, 'shouldEncrypt', [$path]);
1015
+
1016
+        $this->assertSame($expected, $result);
1017
+    }
1018
+
1019
+    public static function dataTestShouldEncrypt(): array {
1020
+        return [
1021
+            [false, false, false, false],
1022
+            [true, false, false, false],
1023
+            [true, true, false, false],
1024
+            [true, true, true, true],
1025
+            [true, null, false, true],
1026
+        ];
1027
+    }
1028 1028
 }
Please login to merge, or discard this patch.
Spacing   +17 added lines, -17 removed lines patch added patch discarded remove patch
@@ -87,12 +87,12 @@  discard block
 block discarded – undo
87 87
 			->getMock();
88 88
 		$this->util->expects($this->any())
89 89
 			->method('getUidAndFilename')
90
-			->willReturnCallback(function ($path) {
90
+			->willReturnCallback(function($path) {
91 91
 				return ['user1', $path];
92 92
 			});
93 93
 		$this->util->expects($this->any())
94 94
 			->method('stripPartialFileExtension')
95
-			->willReturnCallback(function ($path) {
95
+			->willReturnCallback(function($path) {
96 96
 				return $path;
97 97
 			});
98 98
 
@@ -112,7 +112,7 @@  discard block
 block discarded – undo
112 112
 			->disableOriginalConstructor()
113 113
 			->onlyMethods(['getOption'])
114 114
 			->getMock();
115
-		$this->mount->expects($this->any())->method('getOption')->willReturnCallback(function ($option, $default) {
115
+		$this->mount->expects($this->any())->method('getOption')->willReturnCallback(function($option, $default) {
116 116
 			if ($option === 'encrypt' && $default === true) {
117 117
 				global $mockedMountPointEncryptionEnabled;
118 118
 				if ($mockedMountPointEncryptionEnabled !== null) {
@@ -126,7 +126,7 @@  discard block
 block discarded – undo
126 126
 			->disableOriginalConstructor()->getMock();
127 127
 		$this->cache->expects($this->any())
128 128
 			->method('get')
129
-			->willReturnCallback(function ($path) {
129
+			->willReturnCallback(function($path) {
130 130
 				return ['encrypted' => false, 'path' => $path];
131 131
 			});
132 132
 
@@ -158,7 +158,7 @@  discard block
 block discarded – undo
158 158
 
159 159
 		$this->instance->expects($this->any())
160 160
 			->method('getMetaData')
161
-			->willReturnCallback(function ($path) {
161
+			->willReturnCallback(function($path) {
162 162
 				return ['encrypted' => true, 'size' => $this->dummySize, 'path' => $path];
163 163
 			});
164 164
 
@@ -210,7 +210,7 @@  discard block
 block discarded – undo
210 210
 		$cache->expects($this->any())
211 211
 			->method('get')
212 212
 			->willReturnCallback(
213
-				function ($path) use ($encrypted) {
213
+				function($path) use ($encrypted) {
214 214
 					return new CacheEntry(['encrypted' => $encrypted, 'path' => $path, 'size' => 0, 'fileid' => 1]);
215 215
 				}
216 216
 			);
@@ -263,7 +263,7 @@  discard block
 block discarded – undo
263 263
 
264 264
 		$result = $this->instance->getMetaData($path);
265 265
 		if (isset($expected['encrypted'])) {
266
-			$this->assertSame($expected['encrypted'], (bool)$result['encrypted']);
266
+			$this->assertSame($expected['encrypted'], (bool) $result['encrypted']);
267 267
 
268 268
 			if (isset($expected['encryptedVersion'])) {
269 269
 				$this->assertSame($expected['encryptedVersion'], $result['encryptedVersion']);
@@ -364,7 +364,7 @@  discard block
 block discarded – undo
364 364
 		$this->instance->expects($this->any())->method('fixUnencryptedSize')
365 365
 			->with('/test.txt', $encryptedSize, $unencryptedSize)
366 366
 			->willReturnCallback(
367
-				function () use ($failure, $expected) {
367
+				function() use ($failure, $expected) {
368 368
 					if ($failure) {
369 369
 						throw new Exception();
370 370
 					} else {
@@ -487,7 +487,7 @@  discard block
 block discarded – undo
487 487
 
488 488
 
489 489
 		if ($rmdirResult === true && $isExcluded === false && $encryptionEnabled === true) {
490
-			$this->keyStore->expects($this->once())->method('deleteAllFileKeys')->with('/mountPoint' . $path);
490
+			$this->keyStore->expects($this->once())->method('deleteAllFileKeys')->with('/mountPoint'.$path);
491 491
 		} else {
492 492
 			$this->keyStore->expects($this->never())->method('deleteAllFileKeys');
493 493
 		}
@@ -568,7 +568,7 @@  discard block
 block discarded – undo
568 568
 			->disableOriginalConstructor()->getMock();
569 569
 		$cache->expects($this->any())
570 570
 			->method('get')
571
-			->willReturnCallback(function ($path) {
571
+			->willReturnCallback(function($path) {
572 572
 				return ['encrypted' => true, 'path' => $path];
573 573
 			});
574 574
 
@@ -653,14 +653,14 @@  discard block
 block discarded – undo
653 653
 			->getMock();
654 654
 		$util->expects($this->any())
655 655
 			->method('stripPartialFileExtension')
656
-			->willReturnCallback(function ($path) {
656
+			->willReturnCallback(function($path) {
657 657
 				return $path;
658 658
 			});
659 659
 
660 660
 		$cache = $this->createMock(Cache::class);
661 661
 		$cache->expects($this->any())
662 662
 			->method('get')
663
-			->willReturnCallback(function ($path) use ($isEncrypted) {
663
+			->willReturnCallback(function($path) use ($isEncrypted) {
664 664
 				return ['encrypted' => $isEncrypted, 'path' => $path];
665 665
 			});
666 666
 
@@ -725,7 +725,7 @@  discard block
 block discarded – undo
725 725
 
726 726
 		$storage2->expects($this->any())
727 727
 			->method('fopen')
728
-			->willReturnCallback(function ($path, $mode) {
728
+			->willReturnCallback(function($path, $mode) {
729 729
 				$temp = OC::$server->getTempManager();
730 730
 				return fopen($temp->getTemporaryFile(), $mode);
731 731
 			});
@@ -774,7 +774,7 @@  discard block
 block discarded – undo
774 774
 
775 775
 		$storage2->expects($this->any())
776 776
 			->method('fopen')
777
-			->willReturnCallback(function ($path, $mode) {
777
+			->willReturnCallback(function($path, $mode) {
778 778
 				$temp = OC::$server->getTempManager();
779 779
 				return fopen($temp->getTemporaryFile(), $mode);
780 780
 			});
@@ -868,7 +868,7 @@  discard block
 block discarded – undo
868 868
 			->willReturn($cache);
869 869
 
870 870
 		$this->arrayCache->expects($this->once())->method('set')
871
-			->with('encryption_copy_version_' . $sourceInternalPath, true);
871
+			->with('encryption_copy_version_'.$sourceInternalPath, true);
872 872
 
873 873
 		if ($copyResult) {
874 874
 			$cache->expects($this->once())->method('get')
@@ -876,7 +876,7 @@  discard block
 block discarded – undo
876 876
 				->willReturn(new CacheEntry(['encrypted' => $encrypted, 'size' => 42]));
877 877
 			if ($encrypted) {
878 878
 				$instance->expects($this->once())->method('updateUnencryptedSize')
879
-					->with($mountPoint . $targetInternalPath, 42);
879
+					->with($mountPoint.$targetInternalPath, 42);
880 880
 			} else {
881 881
 				$instance->expects($this->never())->method('updateUnencryptedSize');
882 882
 			}
@@ -987,7 +987,7 @@  discard block
 block discarded – undo
987 987
 			->method('getEncryptionModule')
988 988
 			->with($fullPath)
989 989
 			->willReturnCallback(
990
-				function () use ($encryptionModule) {
990
+				function() use ($encryptionModule) {
991 991
 					if ($encryptionModule === false) {
992 992
 						throw new ModuleDoesNotExistsException();
993 993
 					}
Please login to merge, or discard this patch.
tests/lib/Files/Storage/Wrapper/QuotaTest.php 1 patch
Indentation   +205 added lines, -205 removed lines patch added patch discarded remove patch
@@ -21,209 +21,209 @@
 block discarded – undo
21 21
  * @package Test\Files\Storage\Wrapper
22 22
  */
23 23
 class QuotaTest extends \Test\Files\Storage\Storage {
24
-	/**
25
-	 * @var string tmpDir
26
-	 */
27
-	private $tmpDir;
28
-
29
-	protected function setUp(): void {
30
-		parent::setUp();
31
-
32
-		$this->tmpDir = \OC::$server->getTempManager()->getTemporaryFolder();
33
-		$storage = new \OC\Files\Storage\Local(['datadir' => $this->tmpDir]);
34
-		$this->instance = new \OC\Files\Storage\Wrapper\Quota(['storage' => $storage, 'quota' => 10000000]);
35
-	}
36
-
37
-	protected function tearDown(): void {
38
-		\OC_Helper::rmdirr($this->tmpDir);
39
-		parent::tearDown();
40
-	}
41
-
42
-	/**
43
-	 * @param integer $limit
44
-	 */
45
-	protected function getLimitedStorage($limit) {
46
-		$storage = new \OC\Files\Storage\Local(['datadir' => $this->tmpDir]);
47
-		$storage->mkdir('files');
48
-		$storage->getScanner()->scan('');
49
-		return new \OC\Files\Storage\Wrapper\Quota(['storage' => $storage, 'quota' => $limit]);
50
-	}
51
-
52
-	public function testFilePutContentsNotEnoughSpace(): void {
53
-		$instance = $this->getLimitedStorage(3);
54
-		$this->assertFalse($instance->file_put_contents('files/foo', 'foobar'));
55
-	}
56
-
57
-	public function testCopyNotEnoughSpace(): void {
58
-		$instance = $this->getLimitedStorage(9);
59
-		$this->assertEquals(6, $instance->file_put_contents('files/foo', 'foobar'));
60
-		$instance->getScanner()->scan('');
61
-		$this->assertFalse($instance->copy('files/foo', 'files/bar'));
62
-	}
63
-
64
-	public function testFreeSpace(): void {
65
-		$instance = $this->getLimitedStorage(9);
66
-		$this->assertEquals(9, $instance->free_space(''));
67
-	}
68
-
69
-	public function testFreeSpaceWithUsedSpace(): void {
70
-		$instance = $this->getLimitedStorage(9);
71
-		$instance->getCache()->put(
72
-			'', ['size' => 3]
73
-		);
74
-		$this->assertEquals(6, $instance->free_space(''));
75
-	}
76
-
77
-	public function testFreeSpaceWithUnknownDiskSpace(): void {
78
-		$storage = $this->getMockBuilder(Local::class)
79
-			->onlyMethods(['free_space'])
80
-			->setConstructorArgs([['datadir' => $this->tmpDir]])
81
-			->getMock();
82
-		$storage->expects($this->any())
83
-			->method('free_space')
84
-			->willReturn(-2);
85
-		$storage->getScanner()->scan('');
86
-
87
-		$instance = new \OC\Files\Storage\Wrapper\Quota(['storage' => $storage, 'quota' => 9]);
88
-		$instance->getCache()->put(
89
-			'', ['size' => 3]
90
-		);
91
-		$this->assertEquals(6, $instance->free_space(''));
92
-	}
93
-
94
-	public function testFreeSpaceWithUsedSpaceAndEncryption(): void {
95
-		$instance = $this->getLimitedStorage(9);
96
-		$instance->getCache()->put(
97
-			'', ['size' => 7]
98
-		);
99
-		$this->assertEquals(2, $instance->free_space(''));
100
-	}
101
-
102
-	public function testFWriteNotEnoughSpace(): void {
103
-		$instance = $this->getLimitedStorage(9);
104
-		$stream = $instance->fopen('files/foo', 'w+');
105
-		$this->assertEquals(6, fwrite($stream, 'foobar'));
106
-		$this->assertEquals(3, fwrite($stream, 'qwerty'));
107
-		fclose($stream);
108
-		$this->assertEquals('foobarqwe', $instance->file_get_contents('files/foo'));
109
-	}
110
-
111
-	public function testStreamCopyWithEnoughSpace(): void {
112
-		$instance = $this->getLimitedStorage(16);
113
-		$inputStream = fopen('data://text/plain,foobarqwerty', 'r');
114
-		$outputStream = $instance->fopen('files/foo', 'w+');
115
-		[$count, $result] = \OC_Helper::streamCopy($inputStream, $outputStream);
116
-		$this->assertEquals(12, $count);
117
-		$this->assertTrue($result);
118
-		fclose($inputStream);
119
-		fclose($outputStream);
120
-	}
121
-
122
-	public function testStreamCopyNotEnoughSpace(): void {
123
-		$instance = $this->getLimitedStorage(9);
124
-		$inputStream = fopen('data://text/plain,foobarqwerty', 'r');
125
-		$outputStream = $instance->fopen('files/foo', 'w+');
126
-		[$count, $result] = \OC_Helper::streamCopy($inputStream, $outputStream);
127
-		$this->assertEquals(9, $count);
128
-		$this->assertFalse($result);
129
-		fclose($inputStream);
130
-		fclose($outputStream);
131
-	}
132
-
133
-	public function testReturnFalseWhenFopenFailed(): void {
134
-		$failStorage = $this->getMockBuilder(Local::class)
135
-			->onlyMethods(['fopen'])
136
-			->setConstructorArgs([['datadir' => $this->tmpDir]])
137
-			->getMock();
138
-		$failStorage->expects($this->any())
139
-			->method('fopen')
140
-			->willReturn(false);
141
-
142
-		$instance = new \OC\Files\Storage\Wrapper\Quota(['storage' => $failStorage, 'quota' => 1000]);
143
-
144
-		$this->assertFalse($instance->fopen('failedfopen', 'r'));
145
-	}
146
-
147
-	public function testReturnRegularStreamOnRead(): void {
148
-		$instance = $this->getLimitedStorage(9);
149
-
150
-		// create test file first
151
-		$stream = $instance->fopen('files/foo', 'w+');
152
-		fwrite($stream, 'blablacontent');
153
-		fclose($stream);
154
-
155
-		$stream = $instance->fopen('files/foo', 'r');
156
-		$meta = stream_get_meta_data($stream);
157
-		$this->assertEquals('plainfile', $meta['wrapper_type']);
158
-		fclose($stream);
159
-
160
-		$stream = $instance->fopen('files/foo', 'rb');
161
-		$meta = stream_get_meta_data($stream);
162
-		$this->assertEquals('plainfile', $meta['wrapper_type']);
163
-		fclose($stream);
164
-	}
165
-
166
-	public function testReturnRegularStreamWhenOutsideFiles(): void {
167
-		$instance = $this->getLimitedStorage(9);
168
-		$instance->mkdir('files_other');
169
-
170
-		// create test file first
171
-		$stream = $instance->fopen('files_other/foo', 'w+');
172
-		$meta = stream_get_meta_data($stream);
173
-		$this->assertEquals('plainfile', $meta['wrapper_type']);
174
-		fclose($stream);
175
-	}
176
-
177
-	public function testReturnQuotaStreamOnWrite(): void {
178
-		$instance = $this->getLimitedStorage(9);
179
-		$stream = $instance->fopen('files/foo', 'w+');
180
-		$meta = stream_get_meta_data($stream);
181
-		$expected_type = 'user-space';
182
-		$this->assertEquals($expected_type, $meta['wrapper_type']);
183
-		fclose($stream);
184
-	}
185
-
186
-	public function testSpaceRoot(): void {
187
-		$storage = $this->getMockBuilder(Local::class)->disableOriginalConstructor()->getMock();
188
-		$cache = $this->getMockBuilder('\OC\Files\Cache\Cache')->disableOriginalConstructor()->getMock();
189
-		$storage->expects($this->once())
190
-			->method('getCache')
191
-			->willReturn($cache);
192
-		$storage->expects($this->once())
193
-			->method('free_space')
194
-			->willReturn(2048);
195
-		$cache->expects($this->once())
196
-			->method('get')
197
-			->with('files')
198
-			->willReturn(new CacheEntry(['size' => 50]));
199
-
200
-		$instance = new \OC\Files\Storage\Wrapper\Quota(['storage' => $storage, 'quota' => 1024, 'root' => 'files']);
201
-
202
-		$this->assertEquals(1024 - 50, $instance->free_space(''));
203
-	}
204
-
205
-	public function testInstanceOfStorageWrapper(): void {
206
-		$this->assertTrue($this->instance->instanceOfStorage('\OC\Files\Storage\Local'));
207
-		$this->assertTrue($this->instance->instanceOfStorage('\OC\Files\Storage\Wrapper\Wrapper'));
208
-		$this->assertTrue($this->instance->instanceOfStorage('\OC\Files\Storage\Wrapper\Quota'));
209
-	}
210
-
211
-	public function testNoMkdirQuotaZero(): void {
212
-		$instance = $this->getLimitedStorage(0.0);
213
-		$this->assertFalse($instance->mkdir('files'));
214
-		$this->assertFalse($instance->mkdir('files/foobar'));
215
-	}
216
-
217
-	public function testMkdirQuotaZeroTrashbin(): void {
218
-		$instance = $this->getLimitedStorage(0.0);
219
-		$this->assertTrue($instance->mkdir('files_trashbin'));
220
-		$this->assertTrue($instance->mkdir('files_trashbin/files'));
221
-		$this->assertTrue($instance->mkdir('files_versions'));
222
-		$this->assertTrue($instance->mkdir('cache'));
223
-	}
224
-
225
-	public function testNoTouchQuotaZero(): void {
226
-		$instance = $this->getLimitedStorage(0.0);
227
-		$this->assertFalse($instance->touch('foobar'));
228
-	}
24
+    /**
25
+     * @var string tmpDir
26
+     */
27
+    private $tmpDir;
28
+
29
+    protected function setUp(): void {
30
+        parent::setUp();
31
+
32
+        $this->tmpDir = \OC::$server->getTempManager()->getTemporaryFolder();
33
+        $storage = new \OC\Files\Storage\Local(['datadir' => $this->tmpDir]);
34
+        $this->instance = new \OC\Files\Storage\Wrapper\Quota(['storage' => $storage, 'quota' => 10000000]);
35
+    }
36
+
37
+    protected function tearDown(): void {
38
+        \OC_Helper::rmdirr($this->tmpDir);
39
+        parent::tearDown();
40
+    }
41
+
42
+    /**
43
+     * @param integer $limit
44
+     */
45
+    protected function getLimitedStorage($limit) {
46
+        $storage = new \OC\Files\Storage\Local(['datadir' => $this->tmpDir]);
47
+        $storage->mkdir('files');
48
+        $storage->getScanner()->scan('');
49
+        return new \OC\Files\Storage\Wrapper\Quota(['storage' => $storage, 'quota' => $limit]);
50
+    }
51
+
52
+    public function testFilePutContentsNotEnoughSpace(): void {
53
+        $instance = $this->getLimitedStorage(3);
54
+        $this->assertFalse($instance->file_put_contents('files/foo', 'foobar'));
55
+    }
56
+
57
+    public function testCopyNotEnoughSpace(): void {
58
+        $instance = $this->getLimitedStorage(9);
59
+        $this->assertEquals(6, $instance->file_put_contents('files/foo', 'foobar'));
60
+        $instance->getScanner()->scan('');
61
+        $this->assertFalse($instance->copy('files/foo', 'files/bar'));
62
+    }
63
+
64
+    public function testFreeSpace(): void {
65
+        $instance = $this->getLimitedStorage(9);
66
+        $this->assertEquals(9, $instance->free_space(''));
67
+    }
68
+
69
+    public function testFreeSpaceWithUsedSpace(): void {
70
+        $instance = $this->getLimitedStorage(9);
71
+        $instance->getCache()->put(
72
+            '', ['size' => 3]
73
+        );
74
+        $this->assertEquals(6, $instance->free_space(''));
75
+    }
76
+
77
+    public function testFreeSpaceWithUnknownDiskSpace(): void {
78
+        $storage = $this->getMockBuilder(Local::class)
79
+            ->onlyMethods(['free_space'])
80
+            ->setConstructorArgs([['datadir' => $this->tmpDir]])
81
+            ->getMock();
82
+        $storage->expects($this->any())
83
+            ->method('free_space')
84
+            ->willReturn(-2);
85
+        $storage->getScanner()->scan('');
86
+
87
+        $instance = new \OC\Files\Storage\Wrapper\Quota(['storage' => $storage, 'quota' => 9]);
88
+        $instance->getCache()->put(
89
+            '', ['size' => 3]
90
+        );
91
+        $this->assertEquals(6, $instance->free_space(''));
92
+    }
93
+
94
+    public function testFreeSpaceWithUsedSpaceAndEncryption(): void {
95
+        $instance = $this->getLimitedStorage(9);
96
+        $instance->getCache()->put(
97
+            '', ['size' => 7]
98
+        );
99
+        $this->assertEquals(2, $instance->free_space(''));
100
+    }
101
+
102
+    public function testFWriteNotEnoughSpace(): void {
103
+        $instance = $this->getLimitedStorage(9);
104
+        $stream = $instance->fopen('files/foo', 'w+');
105
+        $this->assertEquals(6, fwrite($stream, 'foobar'));
106
+        $this->assertEquals(3, fwrite($stream, 'qwerty'));
107
+        fclose($stream);
108
+        $this->assertEquals('foobarqwe', $instance->file_get_contents('files/foo'));
109
+    }
110
+
111
+    public function testStreamCopyWithEnoughSpace(): void {
112
+        $instance = $this->getLimitedStorage(16);
113
+        $inputStream = fopen('data://text/plain,foobarqwerty', 'r');
114
+        $outputStream = $instance->fopen('files/foo', 'w+');
115
+        [$count, $result] = \OC_Helper::streamCopy($inputStream, $outputStream);
116
+        $this->assertEquals(12, $count);
117
+        $this->assertTrue($result);
118
+        fclose($inputStream);
119
+        fclose($outputStream);
120
+    }
121
+
122
+    public function testStreamCopyNotEnoughSpace(): void {
123
+        $instance = $this->getLimitedStorage(9);
124
+        $inputStream = fopen('data://text/plain,foobarqwerty', 'r');
125
+        $outputStream = $instance->fopen('files/foo', 'w+');
126
+        [$count, $result] = \OC_Helper::streamCopy($inputStream, $outputStream);
127
+        $this->assertEquals(9, $count);
128
+        $this->assertFalse($result);
129
+        fclose($inputStream);
130
+        fclose($outputStream);
131
+    }
132
+
133
+    public function testReturnFalseWhenFopenFailed(): void {
134
+        $failStorage = $this->getMockBuilder(Local::class)
135
+            ->onlyMethods(['fopen'])
136
+            ->setConstructorArgs([['datadir' => $this->tmpDir]])
137
+            ->getMock();
138
+        $failStorage->expects($this->any())
139
+            ->method('fopen')
140
+            ->willReturn(false);
141
+
142
+        $instance = new \OC\Files\Storage\Wrapper\Quota(['storage' => $failStorage, 'quota' => 1000]);
143
+
144
+        $this->assertFalse($instance->fopen('failedfopen', 'r'));
145
+    }
146
+
147
+    public function testReturnRegularStreamOnRead(): void {
148
+        $instance = $this->getLimitedStorage(9);
149
+
150
+        // create test file first
151
+        $stream = $instance->fopen('files/foo', 'w+');
152
+        fwrite($stream, 'blablacontent');
153
+        fclose($stream);
154
+
155
+        $stream = $instance->fopen('files/foo', 'r');
156
+        $meta = stream_get_meta_data($stream);
157
+        $this->assertEquals('plainfile', $meta['wrapper_type']);
158
+        fclose($stream);
159
+
160
+        $stream = $instance->fopen('files/foo', 'rb');
161
+        $meta = stream_get_meta_data($stream);
162
+        $this->assertEquals('plainfile', $meta['wrapper_type']);
163
+        fclose($stream);
164
+    }
165
+
166
+    public function testReturnRegularStreamWhenOutsideFiles(): void {
167
+        $instance = $this->getLimitedStorage(9);
168
+        $instance->mkdir('files_other');
169
+
170
+        // create test file first
171
+        $stream = $instance->fopen('files_other/foo', 'w+');
172
+        $meta = stream_get_meta_data($stream);
173
+        $this->assertEquals('plainfile', $meta['wrapper_type']);
174
+        fclose($stream);
175
+    }
176
+
177
+    public function testReturnQuotaStreamOnWrite(): void {
178
+        $instance = $this->getLimitedStorage(9);
179
+        $stream = $instance->fopen('files/foo', 'w+');
180
+        $meta = stream_get_meta_data($stream);
181
+        $expected_type = 'user-space';
182
+        $this->assertEquals($expected_type, $meta['wrapper_type']);
183
+        fclose($stream);
184
+    }
185
+
186
+    public function testSpaceRoot(): void {
187
+        $storage = $this->getMockBuilder(Local::class)->disableOriginalConstructor()->getMock();
188
+        $cache = $this->getMockBuilder('\OC\Files\Cache\Cache')->disableOriginalConstructor()->getMock();
189
+        $storage->expects($this->once())
190
+            ->method('getCache')
191
+            ->willReturn($cache);
192
+        $storage->expects($this->once())
193
+            ->method('free_space')
194
+            ->willReturn(2048);
195
+        $cache->expects($this->once())
196
+            ->method('get')
197
+            ->with('files')
198
+            ->willReturn(new CacheEntry(['size' => 50]));
199
+
200
+        $instance = new \OC\Files\Storage\Wrapper\Quota(['storage' => $storage, 'quota' => 1024, 'root' => 'files']);
201
+
202
+        $this->assertEquals(1024 - 50, $instance->free_space(''));
203
+    }
204
+
205
+    public function testInstanceOfStorageWrapper(): void {
206
+        $this->assertTrue($this->instance->instanceOfStorage('\OC\Files\Storage\Local'));
207
+        $this->assertTrue($this->instance->instanceOfStorage('\OC\Files\Storage\Wrapper\Wrapper'));
208
+        $this->assertTrue($this->instance->instanceOfStorage('\OC\Files\Storage\Wrapper\Quota'));
209
+    }
210
+
211
+    public function testNoMkdirQuotaZero(): void {
212
+        $instance = $this->getLimitedStorage(0.0);
213
+        $this->assertFalse($instance->mkdir('files'));
214
+        $this->assertFalse($instance->mkdir('files/foobar'));
215
+    }
216
+
217
+    public function testMkdirQuotaZeroTrashbin(): void {
218
+        $instance = $this->getLimitedStorage(0.0);
219
+        $this->assertTrue($instance->mkdir('files_trashbin'));
220
+        $this->assertTrue($instance->mkdir('files_trashbin/files'));
221
+        $this->assertTrue($instance->mkdir('files_versions'));
222
+        $this->assertTrue($instance->mkdir('cache'));
223
+    }
224
+
225
+    public function testNoTouchQuotaZero(): void {
226
+        $instance = $this->getLimitedStorage(0.0);
227
+        $this->assertFalse($instance->touch('foobar'));
228
+    }
229 229
 }
Please login to merge, or discard this patch.
tests/lib/Files/Config/UserMountCacheTest.php 1 patch
Indentation   +397 added lines, -397 removed lines patch added patch discarded remove patch
@@ -30,519 +30,519 @@
 block discarded – undo
30 30
  * @group DB
31 31
  */
32 32
 class UserMountCacheTest extends TestCase {
33
-	/**
34
-	 * @var IDBConnection
35
-	 */
36
-	private $connection;
37
-
38
-	/**
39
-	 * @var IUserManager
40
-	 */
41
-	private $userManager;
42
-
43
-	/**
44
-	 * @var \OC\Files\Config\UserMountCache
45
-	 */
46
-	private $cache;
47
-
48
-	private $fileIds = [];
49
-
50
-	protected function setUp(): void {
51
-		parent::setUp();
52
-
53
-		$this->fileIds = [];
54
-		$this->connection = \OC::$server->getDatabaseConnection();
55
-		$config = $this->getMockBuilder(IConfig::class)
56
-			->disableOriginalConstructor()
57
-			->getMock();
58
-		$config
59
-			->expects($this->any())
60
-			->method('getUserValue')
61
-			->willReturnArgument(3);
62
-		$config
63
-			->expects($this->any())
64
-			->method('getAppValue')
65
-			->willReturnArgument(2);
66
-		$this->userManager = new Manager($config, $this->createMock(ICacheFactory::class), $this->createMock(IEventDispatcher::class), $this->createMock(LoggerInterface::class));
67
-		$userBackend = new Dummy();
68
-		$userBackend->createUser('u1', '');
69
-		$userBackend->createUser('u2', '');
70
-		$userBackend->createUser('u3', '');
71
-		$this->userManager->registerBackend($userBackend);
72
-		$this->cache = new \OC\Files\Config\UserMountCache($this->connection, $this->userManager, $this->createMock(LoggerInterface::class), $this->createMock(IEventLogger::class));
73
-	}
74
-
75
-	protected function tearDown(): void {
76
-		$builder = $this->connection->getQueryBuilder();
77
-
78
-		$builder->delete('mounts')->execute();
33
+    /**
34
+     * @var IDBConnection
35
+     */
36
+    private $connection;
37
+
38
+    /**
39
+     * @var IUserManager
40
+     */
41
+    private $userManager;
42
+
43
+    /**
44
+     * @var \OC\Files\Config\UserMountCache
45
+     */
46
+    private $cache;
47
+
48
+    private $fileIds = [];
49
+
50
+    protected function setUp(): void {
51
+        parent::setUp();
52
+
53
+        $this->fileIds = [];
54
+        $this->connection = \OC::$server->getDatabaseConnection();
55
+        $config = $this->getMockBuilder(IConfig::class)
56
+            ->disableOriginalConstructor()
57
+            ->getMock();
58
+        $config
59
+            ->expects($this->any())
60
+            ->method('getUserValue')
61
+            ->willReturnArgument(3);
62
+        $config
63
+            ->expects($this->any())
64
+            ->method('getAppValue')
65
+            ->willReturnArgument(2);
66
+        $this->userManager = new Manager($config, $this->createMock(ICacheFactory::class), $this->createMock(IEventDispatcher::class), $this->createMock(LoggerInterface::class));
67
+        $userBackend = new Dummy();
68
+        $userBackend->createUser('u1', '');
69
+        $userBackend->createUser('u2', '');
70
+        $userBackend->createUser('u3', '');
71
+        $this->userManager->registerBackend($userBackend);
72
+        $this->cache = new \OC\Files\Config\UserMountCache($this->connection, $this->userManager, $this->createMock(LoggerInterface::class), $this->createMock(IEventLogger::class));
73
+    }
74
+
75
+    protected function tearDown(): void {
76
+        $builder = $this->connection->getQueryBuilder();
77
+
78
+        $builder->delete('mounts')->execute();
79 79
 
80
-		$builder = $this->connection->getQueryBuilder();
80
+        $builder = $this->connection->getQueryBuilder();
81 81
 
82
-		foreach ($this->fileIds as $fileId) {
83
-			$builder->delete('filecache')
84
-				->where($builder->expr()->eq('fileid', new Literal($fileId)))
85
-				->execute();
86
-		}
87
-	}
82
+        foreach ($this->fileIds as $fileId) {
83
+            $builder->delete('filecache')
84
+                ->where($builder->expr()->eq('fileid', new Literal($fileId)))
85
+                ->execute();
86
+        }
87
+    }
88 88
 
89
-	private function getStorage($storageId, $rootInternalPath = '') {
90
-		$rootId = $this->createCacheEntry($rootInternalPath, $storageId);
89
+    private function getStorage($storageId, $rootInternalPath = '') {
90
+        $rootId = $this->createCacheEntry($rootInternalPath, $storageId);
91 91
 
92
-		$storageCache = $this->createMock(\OC\Files\Cache\Storage::class);
93
-		$storageCache->expects($this->any())
94
-			->method('getNumericId')
95
-			->willReturn($storageId);
92
+        $storageCache = $this->createMock(\OC\Files\Cache\Storage::class);
93
+        $storageCache->expects($this->any())
94
+            ->method('getNumericId')
95
+            ->willReturn($storageId);
96 96
 
97
-		$cache = $this->createMock(Cache::class);
98
-		$cache->expects($this->any())
99
-			->method('getId')
100
-			->willReturn($rootId);
101
-		$cache->method('getNumericStorageId')
102
-			->willReturn($storageId);
97
+        $cache = $this->createMock(Cache::class);
98
+        $cache->expects($this->any())
99
+            ->method('getId')
100
+            ->willReturn($rootId);
101
+        $cache->method('getNumericStorageId')
102
+            ->willReturn($storageId);
103 103
 
104
-		$storage = $this->createMock(Storage::class);
105
-		$storage->expects($this->any())
106
-			->method('getStorageCache')
107
-			->willReturn($storageCache);
108
-		$storage->expects($this->any())
109
-			->method('getCache')
110
-			->willReturn($cache);
104
+        $storage = $this->createMock(Storage::class);
105
+        $storage->expects($this->any())
106
+            ->method('getStorageCache')
107
+            ->willReturn($storageCache);
108
+        $storage->expects($this->any())
109
+            ->method('getCache')
110
+            ->willReturn($cache);
111 111
 
112
-		return [$storage, $rootId];
113
-	}
112
+        return [$storage, $rootId];
113
+    }
114 114
 
115
-	private function clearCache() {
116
-		$this->invokePrivate($this->cache, 'mountsForUsers', [new CappedMemoryCache()]);
117
-	}
115
+    private function clearCache() {
116
+        $this->invokePrivate($this->cache, 'mountsForUsers', [new CappedMemoryCache()]);
117
+    }
118 118
 
119
-	private function keyForMount(MountPoint $mount): string {
120
-		return $mount->getStorageRootId() . '::' . $mount->getMountPoint();
121
-	}
119
+    private function keyForMount(MountPoint $mount): string {
120
+        return $mount->getStorageRootId() . '::' . $mount->getMountPoint();
121
+    }
122 122
 
123
-	public function testNewMounts(): void {
124
-		$user = $this->userManager->get('u1');
123
+    public function testNewMounts(): void {
124
+        $user = $this->userManager->get('u1');
125 125
 
126
-		[$storage] = $this->getStorage(10);
127
-		$mount = new MountPoint($storage, '/asd/');
126
+        [$storage] = $this->getStorage(10);
127
+        $mount = new MountPoint($storage, '/asd/');
128 128
 
129
-		$this->cache->registerMounts($user, [$mount]);
129
+        $this->cache->registerMounts($user, [$mount]);
130 130
 
131
-		$this->clearCache();
131
+        $this->clearCache();
132 132
 
133
-		$cachedMounts = $this->cache->getMountsForUser($user);
133
+        $cachedMounts = $this->cache->getMountsForUser($user);
134 134
 
135
-		$this->assertCount(1, $cachedMounts);
136
-		$cachedMount = $cachedMounts[$this->keyForMount($mount)];
137
-		$this->assertEquals('/asd/', $cachedMount->getMountPoint());
138
-		$this->assertEquals($user->getUID(), $cachedMount->getUser()->getUID());
139
-		$this->assertEquals($storage->getCache()->getId(''), $cachedMount->getRootId());
140
-		$this->assertEquals($storage->getStorageCache()->getNumericId(), $cachedMount->getStorageId());
141
-	}
135
+        $this->assertCount(1, $cachedMounts);
136
+        $cachedMount = $cachedMounts[$this->keyForMount($mount)];
137
+        $this->assertEquals('/asd/', $cachedMount->getMountPoint());
138
+        $this->assertEquals($user->getUID(), $cachedMount->getUser()->getUID());
139
+        $this->assertEquals($storage->getCache()->getId(''), $cachedMount->getRootId());
140
+        $this->assertEquals($storage->getStorageCache()->getNumericId(), $cachedMount->getStorageId());
141
+    }
142 142
 
143
-	public function testSameMounts(): void {
144
-		$user = $this->userManager->get('u1');
143
+    public function testSameMounts(): void {
144
+        $user = $this->userManager->get('u1');
145 145
 
146
-		[$storage] = $this->getStorage(10);
147
-		$mount = new MountPoint($storage, '/asd/');
146
+        [$storage] = $this->getStorage(10);
147
+        $mount = new MountPoint($storage, '/asd/');
148 148
 
149
-		$this->cache->registerMounts($user, [$mount]);
149
+        $this->cache->registerMounts($user, [$mount]);
150 150
 
151
-		$this->clearCache();
151
+        $this->clearCache();
152 152
 
153
-		$this->cache->registerMounts($user, [$mount]);
153
+        $this->cache->registerMounts($user, [$mount]);
154 154
 
155
-		$this->clearCache();
155
+        $this->clearCache();
156 156
 
157
-		$cachedMounts = $this->cache->getMountsForUser($user);
157
+        $cachedMounts = $this->cache->getMountsForUser($user);
158 158
 
159
-		$this->assertCount(1, $cachedMounts);
160
-		$cachedMount = $cachedMounts[$this->keyForMount($mount)];
161
-		$this->assertEquals('/asd/', $cachedMount->getMountPoint());
162
-		$this->assertEquals($user->getUID(), $cachedMount->getUser()->getUID());
163
-		$this->assertEquals($storage->getCache()->getId(''), $cachedMount->getRootId());
164
-		$this->assertEquals($storage->getStorageCache()->getNumericId(), $cachedMount->getStorageId());
165
-	}
159
+        $this->assertCount(1, $cachedMounts);
160
+        $cachedMount = $cachedMounts[$this->keyForMount($mount)];
161
+        $this->assertEquals('/asd/', $cachedMount->getMountPoint());
162
+        $this->assertEquals($user->getUID(), $cachedMount->getUser()->getUID());
163
+        $this->assertEquals($storage->getCache()->getId(''), $cachedMount->getRootId());
164
+        $this->assertEquals($storage->getStorageCache()->getNumericId(), $cachedMount->getStorageId());
165
+    }
166 166
 
167
-	public function testRemoveMounts(): void {
168
-		$user = $this->userManager->get('u1');
167
+    public function testRemoveMounts(): void {
168
+        $user = $this->userManager->get('u1');
169 169
 
170
-		[$storage] = $this->getStorage(10);
171
-		$mount = new MountPoint($storage, '/asd/');
170
+        [$storage] = $this->getStorage(10);
171
+        $mount = new MountPoint($storage, '/asd/');
172 172
 
173
-		$this->cache->registerMounts($user, [$mount]);
173
+        $this->cache->registerMounts($user, [$mount]);
174 174
 
175
-		$this->clearCache();
175
+        $this->clearCache();
176 176
 
177
-		$this->cache->registerMounts($user, []);
177
+        $this->cache->registerMounts($user, []);
178 178
 
179
-		$this->clearCache();
179
+        $this->clearCache();
180 180
 
181
-		$cachedMounts = $this->cache->getMountsForUser($user);
181
+        $cachedMounts = $this->cache->getMountsForUser($user);
182 182
 
183
-		$this->assertCount(0, $cachedMounts);
184
-	}
183
+        $this->assertCount(0, $cachedMounts);
184
+    }
185 185
 
186
-	public function testChangeMounts(): void {
187
-		$user = $this->userManager->get('u1');
186
+    public function testChangeMounts(): void {
187
+        $user = $this->userManager->get('u1');
188 188
 
189
-		[$storage] = $this->getStorage(10);
190
-		$mount = new MountPoint($storage, '/bar/');
189
+        [$storage] = $this->getStorage(10);
190
+        $mount = new MountPoint($storage, '/bar/');
191 191
 
192
-		$this->cache->registerMounts($user, [$mount]);
192
+        $this->cache->registerMounts($user, [$mount]);
193 193
 
194
-		$this->clearCache();
194
+        $this->clearCache();
195 195
 
196
-		$mount = new MountPoint($storage, '/foo/');
196
+        $mount = new MountPoint($storage, '/foo/');
197 197
 
198
-		$this->cache->registerMounts($user, [$mount]);
198
+        $this->cache->registerMounts($user, [$mount]);
199 199
 
200
-		$this->clearCache();
200
+        $this->clearCache();
201 201
 
202
-		$cachedMounts = $this->cache->getMountsForUser($user);
202
+        $cachedMounts = $this->cache->getMountsForUser($user);
203 203
 
204
-		$this->assertCount(1, $cachedMounts);
205
-		$cachedMount = $cachedMounts[$this->keyForMount($mount)];
206
-		$this->assertEquals('/foo/', $cachedMount->getMountPoint());
207
-	}
204
+        $this->assertCount(1, $cachedMounts);
205
+        $cachedMount = $cachedMounts[$this->keyForMount($mount)];
206
+        $this->assertEquals('/foo/', $cachedMount->getMountPoint());
207
+    }
208 208
 
209
-	public function testChangeMountId(): void {
210
-		$user = $this->userManager->get('u1');
209
+    public function testChangeMountId(): void {
210
+        $user = $this->userManager->get('u1');
211 211
 
212
-		[$storage] = $this->getStorage(10);
213
-		$mount = new MountPoint($storage, '/foo/', null, null, null, null);
212
+        [$storage] = $this->getStorage(10);
213
+        $mount = new MountPoint($storage, '/foo/', null, null, null, null);
214 214
 
215
-		$this->cache->registerMounts($user, [$mount]);
215
+        $this->cache->registerMounts($user, [$mount]);
216 216
 
217
-		$this->clearCache();
217
+        $this->clearCache();
218 218
 
219
-		$mount = new MountPoint($storage, '/foo/', null, null, null, 1);
219
+        $mount = new MountPoint($storage, '/foo/', null, null, null, 1);
220 220
 
221
-		$this->cache->registerMounts($user, [$mount]);
221
+        $this->cache->registerMounts($user, [$mount]);
222 222
 
223
-		$this->clearCache();
223
+        $this->clearCache();
224 224
 
225
-		$cachedMounts = $this->cache->getMountsForUser($user);
225
+        $cachedMounts = $this->cache->getMountsForUser($user);
226 226
 
227
-		$this->assertCount(1, $cachedMounts);
228
-		$cachedMount = $cachedMounts[$this->keyForMount($mount)];
229
-		$this->assertEquals(1, $cachedMount->getMountId());
230
-	}
227
+        $this->assertCount(1, $cachedMounts);
228
+        $cachedMount = $cachedMounts[$this->keyForMount($mount)];
229
+        $this->assertEquals(1, $cachedMount->getMountId());
230
+    }
231 231
 
232
-	public function testGetMountsForUser(): void {
233
-		$user1 = $this->userManager->get('u1');
234
-		$user2 = $this->userManager->get('u2');
235
-		$user3 = $this->userManager->get('u3');
232
+    public function testGetMountsForUser(): void {
233
+        $user1 = $this->userManager->get('u1');
234
+        $user2 = $this->userManager->get('u2');
235
+        $user3 = $this->userManager->get('u3');
236 236
 
237
-		[$storage1, $id1] = $this->getStorage(1);
238
-		[$storage2, $id2] = $this->getStorage(2, 'foo/bar');
239
-		$mount1 = new MountPoint($storage1, '/foo/');
240
-		$mount2 = new MountPoint($storage2, '/bar/');
237
+        [$storage1, $id1] = $this->getStorage(1);
238
+        [$storage2, $id2] = $this->getStorage(2, 'foo/bar');
239
+        $mount1 = new MountPoint($storage1, '/foo/');
240
+        $mount2 = new MountPoint($storage2, '/bar/');
241 241
 
242
-		$this->cache->registerMounts($user1, [$mount1, $mount2]);
243
-		$this->cache->registerMounts($user2, [$mount2]);
244
-		$this->cache->registerMounts($user3, [$mount2]);
242
+        $this->cache->registerMounts($user1, [$mount1, $mount2]);
243
+        $this->cache->registerMounts($user2, [$mount2]);
244
+        $this->cache->registerMounts($user3, [$mount2]);
245 245
 
246
-		$this->clearCache();
246
+        $this->clearCache();
247 247
 
248
-		$user3->delete();
248
+        $user3->delete();
249 249
 
250
-		$cachedMounts = $this->cache->getMountsForUser($user1);
250
+        $cachedMounts = $this->cache->getMountsForUser($user1);
251 251
 
252
-		$this->assertCount(2, $cachedMounts);
253
-		$this->assertEquals('/foo/', $cachedMounts[$this->keyForMount($mount1)]->getMountPoint());
254
-		$this->assertEquals($user1->getUID(), $cachedMounts[$this->keyForMount($mount1)]->getUser()->getUID());
255
-		$this->assertEquals($id1, $cachedMounts[$this->keyForMount($mount1)]->getRootId());
256
-		$this->assertEquals(1, $cachedMounts[$this->keyForMount($mount1)]->getStorageId());
257
-		$this->assertEquals('', $cachedMounts[$this->keyForMount($mount1)]->getRootInternalPath());
252
+        $this->assertCount(2, $cachedMounts);
253
+        $this->assertEquals('/foo/', $cachedMounts[$this->keyForMount($mount1)]->getMountPoint());
254
+        $this->assertEquals($user1->getUID(), $cachedMounts[$this->keyForMount($mount1)]->getUser()->getUID());
255
+        $this->assertEquals($id1, $cachedMounts[$this->keyForMount($mount1)]->getRootId());
256
+        $this->assertEquals(1, $cachedMounts[$this->keyForMount($mount1)]->getStorageId());
257
+        $this->assertEquals('', $cachedMounts[$this->keyForMount($mount1)]->getRootInternalPath());
258 258
 
259
-		$this->assertEquals('/bar/', $cachedMounts[$this->keyForMount($mount2)]->getMountPoint());
260
-		$this->assertEquals($user1->getUID(), $cachedMounts[$this->keyForMount($mount2)]->getUser()->getUID());
261
-		$this->assertEquals($id2, $cachedMounts[$this->keyForMount($mount2)]->getRootId());
262
-		$this->assertEquals(2, $cachedMounts[$this->keyForMount($mount2)]->getStorageId());
263
-		$this->assertEquals('foo/bar', $cachedMounts[$this->keyForMount($mount2)]->getRootInternalPath());
259
+        $this->assertEquals('/bar/', $cachedMounts[$this->keyForMount($mount2)]->getMountPoint());
260
+        $this->assertEquals($user1->getUID(), $cachedMounts[$this->keyForMount($mount2)]->getUser()->getUID());
261
+        $this->assertEquals($id2, $cachedMounts[$this->keyForMount($mount2)]->getRootId());
262
+        $this->assertEquals(2, $cachedMounts[$this->keyForMount($mount2)]->getStorageId());
263
+        $this->assertEquals('foo/bar', $cachedMounts[$this->keyForMount($mount2)]->getRootInternalPath());
264 264
 
265
-		$cachedMounts = $this->cache->getMountsForUser($user3);
266
-		$this->assertEmpty($cachedMounts);
267
-	}
265
+        $cachedMounts = $this->cache->getMountsForUser($user3);
266
+        $this->assertEmpty($cachedMounts);
267
+    }
268 268
 
269
-	public function testGetMountsByStorageId(): void {
270
-		$user1 = $this->userManager->get('u1');
271
-		$user2 = $this->userManager->get('u2');
269
+    public function testGetMountsByStorageId(): void {
270
+        $user1 = $this->userManager->get('u1');
271
+        $user2 = $this->userManager->get('u2');
272 272
 
273
-		[$storage1, $id1] = $this->getStorage(1);
274
-		[$storage2, $id2] = $this->getStorage(2);
275
-		$mount1 = new MountPoint($storage1, '/foo/');
276
-		$mount2 = new MountPoint($storage2, '/bar/');
273
+        [$storage1, $id1] = $this->getStorage(1);
274
+        [$storage2, $id2] = $this->getStorage(2);
275
+        $mount1 = new MountPoint($storage1, '/foo/');
276
+        $mount2 = new MountPoint($storage2, '/bar/');
277 277
 
278
-		$this->cache->registerMounts($user1, [$mount1, $mount2]);
279
-		$this->cache->registerMounts($user2, [$mount2]);
278
+        $this->cache->registerMounts($user1, [$mount1, $mount2]);
279
+        $this->cache->registerMounts($user2, [$mount2]);
280 280
 
281
-		$this->clearCache();
281
+        $this->clearCache();
282 282
 
283
-		$cachedMounts = $this->cache->getMountsForStorageId(2);
284
-		$this->sortMounts($cachedMounts);
283
+        $cachedMounts = $this->cache->getMountsForStorageId(2);
284
+        $this->sortMounts($cachedMounts);
285 285
 
286
-		$this->assertCount(2, $cachedMounts);
286
+        $this->assertCount(2, $cachedMounts);
287 287
 
288
-		$this->assertEquals('/bar/', $cachedMounts[0]->getMountPoint());
289
-		$this->assertEquals($user1->getUID(), $cachedMounts[0]->getUser()->getUID());
290
-		$this->assertEquals($id2, $cachedMounts[0]->getRootId());
291
-		$this->assertEquals(2, $cachedMounts[0]->getStorageId());
288
+        $this->assertEquals('/bar/', $cachedMounts[0]->getMountPoint());
289
+        $this->assertEquals($user1->getUID(), $cachedMounts[0]->getUser()->getUID());
290
+        $this->assertEquals($id2, $cachedMounts[0]->getRootId());
291
+        $this->assertEquals(2, $cachedMounts[0]->getStorageId());
292 292
 
293
-		$this->assertEquals('/bar/', $cachedMounts[1]->getMountPoint());
294
-		$this->assertEquals($user2->getUID(), $cachedMounts[1]->getUser()->getUID());
295
-		$this->assertEquals($id2, $cachedMounts[1]->getRootId());
296
-		$this->assertEquals(2, $cachedMounts[1]->getStorageId());
297
-	}
298
-
299
-	public function testGetMountsByRootId(): void {
300
-		$user1 = $this->userManager->get('u1');
301
-		$user2 = $this->userManager->get('u2');
302
-
303
-		[$storage1, $id1] = $this->getStorage(1);
304
-		[$storage2, $id2] = $this->getStorage(2);
305
-		$mount1 = new MountPoint($storage1, '/foo/');
306
-		$mount2 = new MountPoint($storage2, '/bar/');
293
+        $this->assertEquals('/bar/', $cachedMounts[1]->getMountPoint());
294
+        $this->assertEquals($user2->getUID(), $cachedMounts[1]->getUser()->getUID());
295
+        $this->assertEquals($id2, $cachedMounts[1]->getRootId());
296
+        $this->assertEquals(2, $cachedMounts[1]->getStorageId());
297
+    }
298
+
299
+    public function testGetMountsByRootId(): void {
300
+        $user1 = $this->userManager->get('u1');
301
+        $user2 = $this->userManager->get('u2');
302
+
303
+        [$storage1, $id1] = $this->getStorage(1);
304
+        [$storage2, $id2] = $this->getStorage(2);
305
+        $mount1 = new MountPoint($storage1, '/foo/');
306
+        $mount2 = new MountPoint($storage2, '/bar/');
307 307
 
308
-		$this->cache->registerMounts($user1, [$mount1, $mount2]);
309
-		$this->cache->registerMounts($user2, [$mount2]);
308
+        $this->cache->registerMounts($user1, [$mount1, $mount2]);
309
+        $this->cache->registerMounts($user2, [$mount2]);
310 310
 
311
-		$this->clearCache();
312
-
313
-		$cachedMounts = $this->cache->getMountsForRootId($id2);
314
-		$this->sortMounts($cachedMounts);
315
-
316
-		$this->assertCount(2, $cachedMounts);
317
-
318
-		$this->assertEquals('/bar/', $cachedMounts[0]->getMountPoint());
319
-		$this->assertEquals($user1->getUID(), $cachedMounts[0]->getUser()->getUID());
320
-		$this->assertEquals($id2, $cachedMounts[0]->getRootId());
321
-		$this->assertEquals(2, $cachedMounts[0]->getStorageId());
322
-
323
-		$this->assertEquals('/bar/', $cachedMounts[1]->getMountPoint());
324
-		$this->assertEquals($user2->getUID(), $cachedMounts[1]->getUser()->getUID());
325
-		$this->assertEquals($id2, $cachedMounts[1]->getRootId());
326
-		$this->assertEquals(2, $cachedMounts[1]->getStorageId());
327
-	}
328
-
329
-	private function sortMounts(&$mounts) {
330
-		usort($mounts, function (ICachedMountInfo $a, ICachedMountInfo $b) {
331
-			return strcmp($a->getUser()->getUID(), $b->getUser()->getUID());
332
-		});
333
-	}
334
-
335
-	private function createCacheEntry($internalPath, $storageId, $size = 0) {
336
-		$internalPath = trim($internalPath, '/');
337
-		try {
338
-			$query = $this->connection->getQueryBuilder();
339
-			$query->insert('filecache')
340
-				->values([
341
-					'storage' => $query->createNamedParameter($storageId),
342
-					'path' => $query->createNamedParameter($internalPath),
343
-					'path_hash' => $query->createNamedParameter(md5($internalPath)),
344
-					'parent' => $query->createNamedParameter(-1, IQueryBuilder::PARAM_INT),
345
-					'name' => $query->createNamedParameter(basename($internalPath)),
346
-					'mimetype' => $query->createNamedParameter(0, IQueryBuilder::PARAM_INT),
347
-					'mimepart' => $query->createNamedParameter(0, IQueryBuilder::PARAM_INT),
348
-					'size' => $query->createNamedParameter($size),
349
-					'storage_mtime' => $query->createNamedParameter(0, IQueryBuilder::PARAM_INT),
350
-					'encrypted' => $query->createNamedParameter(0, IQueryBuilder::PARAM_INT),
351
-					'unencrypted_size' => $query->createNamedParameter(0, IQueryBuilder::PARAM_INT),
352
-					'etag' => $query->createNamedParameter(''),
353
-					'permissions' => $query->createNamedParameter(31, IQueryBuilder::PARAM_INT),
354
-				]);
355
-			$query->executeStatement();
356
-			$id = $query->getLastInsertId();
357
-			$this->fileIds[] = $id;
358
-		} catch (DbalException $e) {
359
-			if ($e->getReason() === DbalException::REASON_UNIQUE_CONSTRAINT_VIOLATION) {
360
-				$query = $this->connection->getQueryBuilder();
361
-				$query->select('fileid')
362
-					->from('filecache')
363
-					->where($query->expr()->eq('storage', $query->createNamedParameter($storageId)))
364
-					->andWhere($query->expr()->eq('path_hash', $query->createNamedParameter(md5($internalPath))));
365
-				$id = (int)$query->execute()->fetchColumn();
366
-			} else {
367
-				throw $e;
368
-			}
369
-		}
370
-		return $id;
371
-	}
311
+        $this->clearCache();
312
+
313
+        $cachedMounts = $this->cache->getMountsForRootId($id2);
314
+        $this->sortMounts($cachedMounts);
315
+
316
+        $this->assertCount(2, $cachedMounts);
317
+
318
+        $this->assertEquals('/bar/', $cachedMounts[0]->getMountPoint());
319
+        $this->assertEquals($user1->getUID(), $cachedMounts[0]->getUser()->getUID());
320
+        $this->assertEquals($id2, $cachedMounts[0]->getRootId());
321
+        $this->assertEquals(2, $cachedMounts[0]->getStorageId());
322
+
323
+        $this->assertEquals('/bar/', $cachedMounts[1]->getMountPoint());
324
+        $this->assertEquals($user2->getUID(), $cachedMounts[1]->getUser()->getUID());
325
+        $this->assertEquals($id2, $cachedMounts[1]->getRootId());
326
+        $this->assertEquals(2, $cachedMounts[1]->getStorageId());
327
+    }
328
+
329
+    private function sortMounts(&$mounts) {
330
+        usort($mounts, function (ICachedMountInfo $a, ICachedMountInfo $b) {
331
+            return strcmp($a->getUser()->getUID(), $b->getUser()->getUID());
332
+        });
333
+    }
334
+
335
+    private function createCacheEntry($internalPath, $storageId, $size = 0) {
336
+        $internalPath = trim($internalPath, '/');
337
+        try {
338
+            $query = $this->connection->getQueryBuilder();
339
+            $query->insert('filecache')
340
+                ->values([
341
+                    'storage' => $query->createNamedParameter($storageId),
342
+                    'path' => $query->createNamedParameter($internalPath),
343
+                    'path_hash' => $query->createNamedParameter(md5($internalPath)),
344
+                    'parent' => $query->createNamedParameter(-1, IQueryBuilder::PARAM_INT),
345
+                    'name' => $query->createNamedParameter(basename($internalPath)),
346
+                    'mimetype' => $query->createNamedParameter(0, IQueryBuilder::PARAM_INT),
347
+                    'mimepart' => $query->createNamedParameter(0, IQueryBuilder::PARAM_INT),
348
+                    'size' => $query->createNamedParameter($size),
349
+                    'storage_mtime' => $query->createNamedParameter(0, IQueryBuilder::PARAM_INT),
350
+                    'encrypted' => $query->createNamedParameter(0, IQueryBuilder::PARAM_INT),
351
+                    'unencrypted_size' => $query->createNamedParameter(0, IQueryBuilder::PARAM_INT),
352
+                    'etag' => $query->createNamedParameter(''),
353
+                    'permissions' => $query->createNamedParameter(31, IQueryBuilder::PARAM_INT),
354
+                ]);
355
+            $query->executeStatement();
356
+            $id = $query->getLastInsertId();
357
+            $this->fileIds[] = $id;
358
+        } catch (DbalException $e) {
359
+            if ($e->getReason() === DbalException::REASON_UNIQUE_CONSTRAINT_VIOLATION) {
360
+                $query = $this->connection->getQueryBuilder();
361
+                $query->select('fileid')
362
+                    ->from('filecache')
363
+                    ->where($query->expr()->eq('storage', $query->createNamedParameter($storageId)))
364
+                    ->andWhere($query->expr()->eq('path_hash', $query->createNamedParameter(md5($internalPath))));
365
+                $id = (int)$query->execute()->fetchColumn();
366
+            } else {
367
+                throw $e;
368
+            }
369
+        }
370
+        return $id;
371
+    }
372 372
 
373
-	public function testGetMountsForFileIdRootId(): void {
374
-		$user1 = $this->userManager->get('u1');
373
+    public function testGetMountsForFileIdRootId(): void {
374
+        $user1 = $this->userManager->get('u1');
375 375
 
376
-		[$storage1, $rootId] = $this->getStorage(2);
377
-		$mount1 = new MountPoint($storage1, '/foo/');
376
+        [$storage1, $rootId] = $this->getStorage(2);
377
+        $mount1 = new MountPoint($storage1, '/foo/');
378 378
 
379
-		$this->cache->registerMounts($user1, [$mount1]);
379
+        $this->cache->registerMounts($user1, [$mount1]);
380 380
 
381
-		$this->clearCache();
381
+        $this->clearCache();
382 382
 
383
-		$cachedMounts = $this->cache->getMountsForFileId($rootId);
383
+        $cachedMounts = $this->cache->getMountsForFileId($rootId);
384 384
 
385
-		$this->assertCount(1, $cachedMounts);
385
+        $this->assertCount(1, $cachedMounts);
386 386
 
387
-		$this->assertEquals('/foo/', $cachedMounts[0]->getMountPoint());
388
-		$this->assertEquals($user1->getUID(), $cachedMounts[0]->getUser()->getUID());
389
-		$this->assertEquals($rootId, $cachedMounts[0]->getRootId());
390
-		$this->assertEquals(2, $cachedMounts[0]->getStorageId());
391
-	}
387
+        $this->assertEquals('/foo/', $cachedMounts[0]->getMountPoint());
388
+        $this->assertEquals($user1->getUID(), $cachedMounts[0]->getUser()->getUID());
389
+        $this->assertEquals($rootId, $cachedMounts[0]->getRootId());
390
+        $this->assertEquals(2, $cachedMounts[0]->getStorageId());
391
+    }
392 392
 
393
-	public function testGetMountsForFileIdSubFolder(): void {
394
-		$user1 = $this->userManager->get('u1');
393
+    public function testGetMountsForFileIdSubFolder(): void {
394
+        $user1 = $this->userManager->get('u1');
395 395
 
396
-		$fileId = $this->createCacheEntry('/foo/bar', 2);
396
+        $fileId = $this->createCacheEntry('/foo/bar', 2);
397 397
 
398
-		[$storage1, $rootId] = $this->getStorage(2);
399
-		$mount1 = new MountPoint($storage1, '/foo/');
398
+        [$storage1, $rootId] = $this->getStorage(2);
399
+        $mount1 = new MountPoint($storage1, '/foo/');
400 400
 
401
-		$this->cache->registerMounts($user1, [$mount1]);
401
+        $this->cache->registerMounts($user1, [$mount1]);
402 402
 
403
-		$this->clearCache();
403
+        $this->clearCache();
404 404
 
405
-		$cachedMounts = $this->cache->getMountsForFileId($fileId);
406
-
407
-		$this->assertCount(1, $cachedMounts);
408
-
409
-		$this->assertEquals('/foo/', $cachedMounts[0]->getMountPoint());
410
-		$this->assertEquals($user1->getUID(), $cachedMounts[0]->getUser()->getUID());
411
-		$this->assertEquals($rootId, $cachedMounts[0]->getRootId());
412
-		$this->assertEquals(2, $cachedMounts[0]->getStorageId());
413
-		$this->assertEquals('foo/bar', $cachedMounts[0]->getInternalPath());
414
-		$this->assertEquals('/foo/foo/bar', $cachedMounts[0]->getPath());
415
-	}
416
-
417
-	public function testGetMountsForFileIdSubFolderMount(): void {
418
-		$user1 = $this->userManager->get('u1');
419
-
420
-		[$storage1, $rootId] = $this->getStorage(2);
421
-		$folderId = $this->createCacheEntry('/foo', 2);
422
-		$fileId = $this->createCacheEntry('/foo/bar', 2);
405
+        $cachedMounts = $this->cache->getMountsForFileId($fileId);
406
+
407
+        $this->assertCount(1, $cachedMounts);
408
+
409
+        $this->assertEquals('/foo/', $cachedMounts[0]->getMountPoint());
410
+        $this->assertEquals($user1->getUID(), $cachedMounts[0]->getUser()->getUID());
411
+        $this->assertEquals($rootId, $cachedMounts[0]->getRootId());
412
+        $this->assertEquals(2, $cachedMounts[0]->getStorageId());
413
+        $this->assertEquals('foo/bar', $cachedMounts[0]->getInternalPath());
414
+        $this->assertEquals('/foo/foo/bar', $cachedMounts[0]->getPath());
415
+    }
416
+
417
+    public function testGetMountsForFileIdSubFolderMount(): void {
418
+        $user1 = $this->userManager->get('u1');
419
+
420
+        [$storage1, $rootId] = $this->getStorage(2);
421
+        $folderId = $this->createCacheEntry('/foo', 2);
422
+        $fileId = $this->createCacheEntry('/foo/bar', 2);
423 423
 
424 424
 
425
-		$mount1 = $this->getMockBuilder(MountPoint::class)
426
-			->setConstructorArgs([$storage1, '/'])
427
-			->onlyMethods(['getStorageRootId'])
428
-			->getMock();
425
+        $mount1 = $this->getMockBuilder(MountPoint::class)
426
+            ->setConstructorArgs([$storage1, '/'])
427
+            ->onlyMethods(['getStorageRootId'])
428
+            ->getMock();
429 429
 
430
-		$mount1->expects($this->any())
431
-			->method('getStorageRootId')
432
-			->willReturn($folderId);
430
+        $mount1->expects($this->any())
431
+            ->method('getStorageRootId')
432
+            ->willReturn($folderId);
433 433
 
434
-		$this->cache->registerMounts($user1, [$mount1]);
434
+        $this->cache->registerMounts($user1, [$mount1]);
435 435
 
436
-		$this->clearCache();
436
+        $this->clearCache();
437 437
 
438
-		$cachedMounts = $this->cache->getMountsForFileId($fileId);
438
+        $cachedMounts = $this->cache->getMountsForFileId($fileId);
439 439
 
440
-		$this->assertCount(1, $cachedMounts);
440
+        $this->assertCount(1, $cachedMounts);
441 441
 
442
-		$this->assertEquals('/', $cachedMounts[0]->getMountPoint());
443
-		$this->assertEquals($user1->getUID(), $cachedMounts[0]->getUser()->getUID());
444
-		$this->assertEquals($folderId, $cachedMounts[0]->getRootId());
445
-		$this->assertEquals(2, $cachedMounts[0]->getStorageId());
446
-		$this->assertEquals('foo', $cachedMounts[0]->getRootInternalPath());
447
-		$this->assertEquals('bar', $cachedMounts[0]->getInternalPath());
448
-		$this->assertEquals('/bar', $cachedMounts[0]->getPath());
449
-	}
442
+        $this->assertEquals('/', $cachedMounts[0]->getMountPoint());
443
+        $this->assertEquals($user1->getUID(), $cachedMounts[0]->getUser()->getUID());
444
+        $this->assertEquals($folderId, $cachedMounts[0]->getRootId());
445
+        $this->assertEquals(2, $cachedMounts[0]->getStorageId());
446
+        $this->assertEquals('foo', $cachedMounts[0]->getRootInternalPath());
447
+        $this->assertEquals('bar', $cachedMounts[0]->getInternalPath());
448
+        $this->assertEquals('/bar', $cachedMounts[0]->getPath());
449
+    }
450 450
 
451
-	public function testGetMountsForFileIdSubFolderMountOutside(): void {
452
-		$user1 = $this->userManager->get('u1');
451
+    public function testGetMountsForFileIdSubFolderMountOutside(): void {
452
+        $user1 = $this->userManager->get('u1');
453 453
 
454
-		[$storage1, $rootId] = $this->getStorage(2);
455
-		$folderId = $this->createCacheEntry('/foo', 2);
456
-		$fileId = $this->createCacheEntry('/bar/asd', 2);
454
+        [$storage1, $rootId] = $this->getStorage(2);
455
+        $folderId = $this->createCacheEntry('/foo', 2);
456
+        $fileId = $this->createCacheEntry('/bar/asd', 2);
457 457
 
458
-		$mount1 = $this->getMockBuilder(MountPoint::class)
459
-			->setConstructorArgs([$storage1, '/foo/'])
460
-			->onlyMethods(['getStorageRootId'])
461
-			->getMock();
458
+        $mount1 = $this->getMockBuilder(MountPoint::class)
459
+            ->setConstructorArgs([$storage1, '/foo/'])
460
+            ->onlyMethods(['getStorageRootId'])
461
+            ->getMock();
462 462
 
463
-		$mount1->expects($this->any())
464
-			->method('getStorageRootId')
465
-			->willReturn($folderId);
463
+        $mount1->expects($this->any())
464
+            ->method('getStorageRootId')
465
+            ->willReturn($folderId);
466 466
 
467
-		$this->cache->registerMounts($user1, [$mount1]);
467
+        $this->cache->registerMounts($user1, [$mount1]);
468 468
 
469
-		$this->cache->registerMounts($user1, [$mount1]);
469
+        $this->cache->registerMounts($user1, [$mount1]);
470 470
 
471
-		$this->clearCache();
471
+        $this->clearCache();
472 472
 
473
-		$cachedMounts = $this->cache->getMountsForFileId($fileId);
473
+        $cachedMounts = $this->cache->getMountsForFileId($fileId);
474 474
 
475
-		$this->assertCount(0, $cachedMounts);
476
-	}
475
+        $this->assertCount(0, $cachedMounts);
476
+    }
477 477
 
478 478
 
479
-	public function testGetMountsForFileIdDeletedUser(): void {
480
-		$user1 = $this->userManager->get('u1');
479
+    public function testGetMountsForFileIdDeletedUser(): void {
480
+        $user1 = $this->userManager->get('u1');
481 481
 
482
-		[$storage1, $rootId] = $this->getStorage(2);
483
-		$rootId = $this->createCacheEntry('', 2);
484
-		$mount1 = new MountPoint($storage1, '/foo/');
485
-		$this->cache->registerMounts($user1, [$mount1]);
482
+        [$storage1, $rootId] = $this->getStorage(2);
483
+        $rootId = $this->createCacheEntry('', 2);
484
+        $mount1 = new MountPoint($storage1, '/foo/');
485
+        $this->cache->registerMounts($user1, [$mount1]);
486 486
 
487
-		$user1->delete();
488
-		$this->clearCache();
487
+        $user1->delete();
488
+        $this->clearCache();
489 489
 
490
-		$cachedMounts = $this->cache->getMountsForFileId($rootId);
491
-		$this->assertEmpty($cachedMounts);
492
-	}
490
+        $cachedMounts = $this->cache->getMountsForFileId($rootId);
491
+        $this->assertEmpty($cachedMounts);
492
+    }
493 493
 
494
-	public function testGetUsedSpaceForUsers(): void {
495
-		$user1 = $this->userManager->get('u1');
496
-		$user2 = $this->userManager->get('u2');
494
+    public function testGetUsedSpaceForUsers(): void {
495
+        $user1 = $this->userManager->get('u1');
496
+        $user2 = $this->userManager->get('u2');
497 497
 
498
-		/** @var Storage $storage1 */
499
-		[$storage1, $rootId] = $this->getStorage(2);
500
-		$folderId = $this->createCacheEntry('files', 2, 100);
501
-		$fileId = $this->createCacheEntry('files/foo', 2, 7);
502
-		$storage1->getCache()->put($folderId, ['size' => 100]);
503
-		$storage1->getCache()->update($fileId, ['size' => 70]);
498
+        /** @var Storage $storage1 */
499
+        [$storage1, $rootId] = $this->getStorage(2);
500
+        $folderId = $this->createCacheEntry('files', 2, 100);
501
+        $fileId = $this->createCacheEntry('files/foo', 2, 7);
502
+        $storage1->getCache()->put($folderId, ['size' => 100]);
503
+        $storage1->getCache()->update($fileId, ['size' => 70]);
504 504
 
505
-		$mount1 = $this->getMockBuilder(MountPoint::class)
506
-			->setConstructorArgs([$storage1, '/u1/'])
507
-			->onlyMethods(['getStorageRootId', 'getNumericStorageId'])
508
-			->getMock();
505
+        $mount1 = $this->getMockBuilder(MountPoint::class)
506
+            ->setConstructorArgs([$storage1, '/u1/'])
507
+            ->onlyMethods(['getStorageRootId', 'getNumericStorageId'])
508
+            ->getMock();
509 509
 
510
-		$mount1->expects($this->any())
511
-			->method('getStorageRootId')
512
-			->willReturn($rootId);
510
+        $mount1->expects($this->any())
511
+            ->method('getStorageRootId')
512
+            ->willReturn($rootId);
513 513
 
514
-		$mount1->expects($this->any())
515
-			->method('getNumericStorageId')
516
-			->willReturn(2);
514
+        $mount1->expects($this->any())
515
+            ->method('getNumericStorageId')
516
+            ->willReturn(2);
517 517
 
518
-		$this->cache->registerMounts($user1, [$mount1]);
518
+        $this->cache->registerMounts($user1, [$mount1]);
519 519
 
520
-		$result = $this->cache->getUsedSpaceForUsers([$user1, $user2]);
521
-		$this->assertEquals(['u1' => 100], $result);
522
-	}
520
+        $result = $this->cache->getUsedSpaceForUsers([$user1, $user2]);
521
+        $this->assertEquals(['u1' => 100], $result);
522
+    }
523 523
 
524 524
 
525
-	public function testMigrateMountProvider(): void {
526
-		$user1 = $this->userManager->get('u1');
525
+    public function testMigrateMountProvider(): void {
526
+        $user1 = $this->userManager->get('u1');
527 527
 
528
-		[$storage1, $rootId] = $this->getStorage(2);
529
-		$rootId = $this->createCacheEntry('', 2);
530
-		$mount1 = new MountPoint($storage1, '/foo/');
531
-		$this->cache->registerMounts($user1, [$mount1]);
528
+        [$storage1, $rootId] = $this->getStorage(2);
529
+        $rootId = $this->createCacheEntry('', 2);
530
+        $mount1 = new MountPoint($storage1, '/foo/');
531
+        $this->cache->registerMounts($user1, [$mount1]);
532 532
 
533
-		$this->clearCache();
533
+        $this->clearCache();
534 534
 
535
-		$cachedMounts = $this->cache->getMountsForUser($user1);
536
-		$this->assertCount(1, $cachedMounts);
537
-		$this->assertEquals('', $cachedMounts[$this->keyForMount($mount1)]->getMountProvider());
535
+        $cachedMounts = $this->cache->getMountsForUser($user1);
536
+        $this->assertCount(1, $cachedMounts);
537
+        $this->assertEquals('', $cachedMounts[$this->keyForMount($mount1)]->getMountProvider());
538 538
 
539
-		$mount1 = new MountPoint($storage1, '/foo/', null, null, null, null, 'dummy');
540
-		$this->cache->registerMounts($user1, [$mount1], ['dummy']);
539
+        $mount1 = new MountPoint($storage1, '/foo/', null, null, null, null, 'dummy');
540
+        $this->cache->registerMounts($user1, [$mount1], ['dummy']);
541 541
 
542
-		$this->clearCache();
542
+        $this->clearCache();
543 543
 
544
-		$cachedMounts = $this->cache->getMountsForUser($user1);
545
-		$this->assertCount(1, $cachedMounts);
546
-		$this->assertEquals('dummy', $cachedMounts[$this->keyForMount($mount1)]->getMountProvider());
547
-	}
544
+        $cachedMounts = $this->cache->getMountsForUser($user1);
545
+        $this->assertCount(1, $cachedMounts);
546
+        $this->assertEquals('dummy', $cachedMounts[$this->keyForMount($mount1)]->getMountProvider());
547
+    }
548 548
 }
Please login to merge, or discard this patch.