aboutsummaryrefslogtreecommitdiffstats
path: root/tests/lib/TestCase.php
blob: 96ee0f06f8ca673ebb0ffea8875bf022f2cc2c0f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
<?php
/**
 * ownCloud
 *
 * @author Joas Schilling
 * @copyright 2014 Joas Schilling nickvergessen@owncloud.com
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
 * License as published by the Free Software Foundation; either
 * version 3 of the License, or any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU AFFERO GENERAL PUBLIC LICENSE for more details.
 *
 * You should have received a copy of the GNU Affero General Public
 * License along with this library.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

namespace Test;

use DOMDocument;
use DOMNode;
use OC\Command\QueueBus;
use OC\Files\Filesystem;
use OC\Template\Base;
use OCP\DB\QueryBuilder\IQueryBuilder;
use OCP\Defaults;
use OCP\IDBConnection;
use OCP\IL10N;
use OCP\Security\ISecureRandom;

abstract class TestCase extends \PHPUnit\Framework\TestCase {
	/** @var \OC\Command\QueueBus */
	private $commandBus;

	/** @var IDBConnection */
	static protected $realDatabase = null;

	/** @var bool */
	static private $wasDatabaseAllowed = false;

	/** @var array */
	protected $services = [];

	/**
	 * @param string $name
	 * @param mixed $newService
	 * @return bool
	 */
	public function overwriteService($name, $newService) {
		if (isset($this->services[$name])) {
			return false;
		}

		$this->services[$name] = \OC::$server->query($name);
		\OC::$server->registerService($name, function () use ($newService) {
			return $newService;
		});

		return true;
	}

	/**
	 * @param string $name
	 * @return bool
	 */
	public function restoreService($name) {
		if (isset($this->services[$name])) {
			$oldService = $this->services[$name];
			\OC::$server->registerService($name, function () use ($oldService) {
				return $oldService;
			});


			unset($this->services[$name]);
			return true;
		}

		return false;
	}

	public function restoreAllServices() {
		if (!empty($this->services)) {
			if (!empty($this->services)) {
				foreach ($this->services as $name => $service) {
					$this->restoreService($name);
				}
			}
		}
	}

	protected function getTestTraits() {
		$traits = [];
		$class = $this;
		do {
			$traits = array_merge(class_uses($class), $traits);
		} while ($class = get_parent_class($class));
		foreach ($traits as $trait => $same) {
			$traits = array_merge(class_uses($trait), $traits);
		}
		$traits = array_unique($traits);
		return array_filter($traits, function ($trait) {
			return substr($trait, 0, 5) === 'Test\\';
		});
	}

	protected function setUp() {
		// overwrite the command bus with one we can run ourselves
		$this->commandBus = new QueueBus();
		$this->overwriteService('AsyncCommandBus', $this->commandBus);

		// detect database access
		self::$wasDatabaseAllowed = true;
		if (!$this->IsDatabaseAccessAllowed()) {
			self::$wasDatabaseAllowed = false;
			if (is_null(self::$realDatabase)) {
				self::$realDatabase = \OC::$server->getDatabaseConnection();
			}
			\OC::$server->registerService(IDBConnection::class, function () {
				$this->fail('Your test case is not allowed to access the database.');
			});
		}

		$traits = $this->getTestTraits();
		foreach ($traits as $trait) {
			$methodName = 'setUp' . basename(str_replace('\\', '/', $trait));
			if (method_exists($this, $methodName)) {
				call_user_func([$this, $methodName]);
			}
		}
	}

	protected function onNotSuccessfulTest(\Throwable $t) {
		$this->restoreAllServices();

		// restore database connection
		if (!$this->IsDatabaseAccessAllowed()) {
			\OC::$server->registerService(IDBConnection::class, function () {
				return self::$realDatabase;
			});
		}

		parent::onNotSuccessfulTest($t);
	}

	protected function tearDown() {
		$this->restoreAllServices();

		// restore database connection
		if (!$this->IsDatabaseAccessAllowed()) {
			\OC::$server->registerService(IDBConnection::class, function () {
				return self::$realDatabase;
			});
		}

		// further cleanup
		$hookExceptions = \OC_Hook::$thrownExceptions;
		\OC_Hook::$thrownExceptions = [];
		\OC::$server->getLockingProvider()->releaseAll();
		if (!empty($hookExceptions)) {
			throw $hookExceptions[0];
		}

		// fail hard if xml errors have not been cleaned up
		$errors = libxml_get_errors();
		libxml_clear_errors();
		if (!empty($errors)) {
			self::assertEquals([], $errors, "There have been xml parsing errors");
		}

		if ($this->IsDatabaseAccessAllowed()) {
			\OC\Files\Cache\Storage::getGlobalCache()->clearCache();
		}

		// tearDown the traits
		$traits = $this->getTestTraits();
		foreach ($traits as $trait) {
			$methodName = 'tearDown' . basename(str_replace('\\', '/', $trait));
			if (method_exists($this, $methodName)) {
				call_user_func([$this, $methodName]);
			}
		}
	}

	/**
	 * Allows us to test private methods/properties
	 *
	 * @param $object
	 * @param $methodName
	 * @param array $parameters
	 * @return mixed
	 */
	protected static function invokePrivate($object, $methodName, array $parameters = array()) {
		if (is_string($object)) {
			$className = $object;
		} else {
			$className = get_class($object);
		}
		$reflection = new \ReflectionClass($className);

		if ($reflection->hasMethod($methodName)) {
			$method = $reflection->getMethod($methodName);

			$method->setAccessible(true);

			return $method->invokeArgs($object, $parameters);
		} elseif ($reflection->hasProperty($methodName)) {
			$property = $reflection->getProperty($methodName);

			$property->setAccessible(true);

			if (!empty($parameters)) {
				$property->setValue($object, array_pop($parameters));
			}

			return $property->getValue($object);
		}

		return false;
	}

	/**
	 * Returns a unique identifier as uniqid() is not reliable sometimes
	 *
	 * @param string $prefix
	 * @param int $length
	 * @return string
	 */
	protected static function getUniqueID($prefix = '', $length = 13) {
		return $prefix . \OC::$server->getSecureRandom()->generate(
			$length,
			// Do not use dots and slashes as we use the value for file names
			ISecureRandom::CHAR_DIGITS . ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_UPPER
		);
	}

	public static function tearDownAfterClass() {
		if (!self::$wasDatabaseAllowed && self::$realDatabase !== null) {
			// in case an error is thrown in a test, PHPUnit jumps straight to tearDownAfterClass,
			// so we need the database again
			\OC::$server->registerService(IDBConnection::class, function () {
				return self::$realDatabase;
			});
		}
		$dataDir = \OC::$server->getConfig()->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data-autotest');
		if (self::$wasDatabaseAllowed && \OC::$server->getDatabaseConnection()) {
			$queryBuilder = \OC::$server->getDatabaseConnection()->getQueryBuilder();

			self::tearDownAfterClassCleanShares($queryBuilder);
			self::tearDownAfterClassCleanStorages($queryBuilder);
			self::tearDownAfterClassCleanFileCache($queryBuilder);
		}
		self::tearDownAfterClassCleanStrayDataFiles($dataDir);
		self::tearDownAfterClassCleanStrayHooks();
		self::tearDownAfterClassCleanStrayLocks();

		parent::tearDownAfterClass();
	}

	/**
	 * Remove all entries from the share table
	 *
	 * @param IQueryBuilder $queryBuilder
	 */
	static protected function tearDownAfterClassCleanShares(IQueryBuilder $queryBuilder) {
		$queryBuilder->delete('share')
			->execute();
	}

	/**
	 * Remove all entries from the storages table
	 *
	 * @param IQueryBuilder $queryBuilder
	 */
	static protected function tearDownAfterClassCleanStorages(IQueryBuilder $queryBuilder) {
		$queryBuilder->delete('storages')
			->execute();
	}

	/**
	 * Remove all entries from the filecache table
	 *
	 * @param IQueryBuilder $queryBuilder
	 */
	static protected function tearDownAfterClassCleanFileCache(IQueryBuilder $queryBuilder) {
		$queryBuilder->delete('filecache')
			->execute();
	}

	/**
	 * Remove all unused files from the data dir
	 *
	 * @param string $dataDir
	 */
	static protected function tearDownAfterClassCleanStrayDataFiles($dataDir) {
		$knownEntries = array(
			'nextcloud.log' => true,
			'audit.log' => true,
			'owncloud.db' => true,
			'.ocdata' => true,
			'..' => true,
			'.' => true,
		);

		if ($dh = opendir($dataDir)) {
			while (($file = readdir($dh)) !== false) {
				if (!isset($knownEntries[$file])) {
					self::tearDownAfterClassCleanStrayDataUnlinkDir($dataDir . '/' . $file);
				}
			}
			closedir($dh);
		}
	}

	/**
	 * Recursive delete files and folders from a given directory
	 *
	 * @param string $dir
	 */
	static protected function tearDownAfterClassCleanStrayDataUnlinkDir($dir) {
		if ($dh = @opendir($dir)) {
			while (($file = readdir($dh)) !== false) {
				if (\OC\Files\Filesystem::isIgnoredDir($file)) {
					continue;
				}
				$path = $dir . '/' . $file;
				if (is_dir($path)) {
					self::tearDownAfterClassCleanStrayDataUnlinkDir($path);
				} else {
					@unlink($path);
				}
			}
			closedir($dh);
		}
		@rmdir($dir);
	}

	/**
	 * Clean up the list of hooks
	 */
	static protected function tearDownAfterClassCleanStrayHooks() {
		\OC_Hook::clear();
	}

	/**
	 * Clean up the list of locks
	 */
	static protected function tearDownAfterClassCleanStrayLocks() {
		\OC::$server->getLockingProvider()->releaseAll();
	}

	/**
	 * Login and setup FS as a given user,
	 * sets the given user as the current user.
	 *
	 * @param string $user user id or empty for a generic FS
	 */
	static protected function loginAsUser($user = '') {
		self::logout();
		\OC\Files\Filesystem::tearDown();
		\OC_User::setUserId($user);
		$userObject = \OC::$server->getUserManager()->get($user);
		if (!is_null($userObject)) {
			$userObject->updateLastLoginTimestamp();
		}
		\OC_Util::setupFS($user);
		if (\OC::$server->getUserManager()->userExists($user)) {
			\OC::$server->getUserFolder($user);
		}
	}

	/**
	 * Logout the current user and tear down the filesystem.
	 */
	static protected function logout() {
		\OC_Util::tearDownFS();
		\OC_User::setUserId('');
		// needed for fully logout
		\OC::$server->getUserSession()->setUser(null);
	}

	/**
	 * Run all commands pushed to the bus
	 */
	protected function runCommands() {
		// get the user for which the fs is setup
		$view = Filesystem::getView();
		if ($view) {
			list(, $user) = explode('/', $view->getRoot());
		} else {
			$user = null;
		}

		\OC_Util::tearDownFS(); // command can't reply on the fs being setup
		$this->commandBus->run();
		\OC_Util::tearDownFS();

		if ($user) {
			\OC_Util::setupFS($user);
		}
	}

	/**
	 * Check if the given path is locked with a given type
	 *
	 * @param \OC\Files\View $view view
	 * @param string $path path to check
	 * @param int $type lock type
	 * @param bool $onMountPoint true to check the mount point instead of the
	 * mounted storage
	 *
	 * @return boolean true if the file is locked with the
	 * given type, false otherwise
	 */
	protected function isFileLocked($view, $path, $type, $onMountPoint = false) {
		// Note: this seems convoluted but is necessary because
		// the format of the lock key depends on the storage implementation
		// (in our case mostly md5)

		if ($type === \OCP\Lock\ILockingProvider::LOCK_SHARED) {
			// to check if the file has a shared lock, try acquiring an exclusive lock
			$checkType = \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE;
		} else {
			// a shared lock cannot be set if exclusive lock is in place
			$checkType = \OCP\Lock\ILockingProvider::LOCK_SHARED;
		}
		try {
			$view->lockFile($path, $checkType, $onMountPoint);
			// no exception, which means the lock of $type is not set
			// clean up
			$view->unlockFile($path, $checkType, $onMountPoint);
			return false;
		} catch (\OCP\Lock\LockedException $e) {
			// we could not acquire the counter-lock, which means
			// the lock of $type was in place
			return true;
		}
	}

	private function IsDatabaseAccessAllowed() {
		// on travis-ci.org we allow database access in any case - otherwise
		// this will break all apps right away
		if (true == getenv('TRAVIS')) {
			return true;
		}
		$annotations = $this->getAnnotations();
		if (isset($annotations['class']['group'])) {
			if(in_array('DB', $annotations['class']['group']) || in_array('SLOWDB', $annotations['class']['group']) ) {
				return true;
			}
		}

		return false;
	}

	/**
	 * @param string $expectedHtml
	 * @param string $template
	 * @param array $vars
	 */
	protected function assertTemplate($expectedHtml, $template, $vars = []) {

		require_once __DIR__.'/../../lib/private/legacy/template/functions.php';

		$requestToken = 12345;
		/** @var Defaults|\PHPUnit_Framework_MockObject_MockObject $l10n */
		$theme = $this->getMockBuilder('\OCP\Defaults')
			->disableOriginalConstructor()->getMock();
		$theme->expects($this->any())
			->method('getName')
			->willReturn('Nextcloud');
		/** @var IL10N|\PHPUnit_Framework_MockObject_MockObject $l10n */
		$l10n = $this->getMockBuilder(IL10N::class)
			->disableOriginalConstructor()->getMock();
		$l10n
			->expects($this->any())
			->method('t')
			->will($this->returnCallback(function($text, $parameters = array()) {
				return vsprintf($text, $parameters);
			}));

		$t = new Base($template, $requestToken, $l10n, $theme);
		$buf = $t->fetchPage($vars);
		$this->assertHtmlStringEqualsHtmlString($expectedHtml, $buf);
	}

	/**
	 * @param string $expectedHtml
	 * @param string $actualHtml
	 * @param string $message
	 */
	protected function assertHtmlStringEqualsHtmlString($expectedHtml, $actualHtml, $message = '') {
		$expected = new DOMDocument();
		$expected->preserveWhiteSpace = false;
		$expected->formatOutput = true;
		$expected->loadHTML($expectedHtml);

		$actual = new DOMDocument();
		$actual->preserveWhiteSpace = false;
		$actual->formatOutput = true;
		$actual->loadHTML($actualHtml);
		$this->removeWhitespaces($actual);

		$expectedHtml1 = $expected->saveHTML();
		$actualHtml1 = $actual->saveHTML();
		self::assertEquals($expectedHtml1, $actualHtml1, $message);
	}


	private function removeWhitespaces(DOMNode $domNode) {
		foreach ($domNode->childNodes as $node) {
			if($node->hasChildNodes()) {
				$this->removeWhitespaces($node);
			} else {
				if ($node instanceof \DOMText && $node->isWhitespaceInElementContent() ) {
					$domNode->removeChild($node);
				}
			}
		}
	}
}