1
0

TestCase.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  5. * SPDX-License-Identifier: AGPL-3.0-or-later
  6. */
  7. namespace Test;
  8. use DOMDocument;
  9. use DOMNode;
  10. use OC\Command\QueueBus;
  11. use OC\Files\Config\MountProviderCollection;
  12. use OC\Files\Filesystem;
  13. use OC\Files\Mount\CacheMountProvider;
  14. use OC\Files\Mount\LocalHomeMountProvider;
  15. use OC\Files\Mount\RootMountProvider;
  16. use OC\Files\SetupManager;
  17. use OC\Template\Base;
  18. use OCP\Command\IBus;
  19. use OCP\DB\QueryBuilder\IQueryBuilder;
  20. use OCP\Defaults;
  21. use OCP\IConfig;
  22. use OCP\IDBConnection;
  23. use OCP\IL10N;
  24. use OCP\Lock\ILockingProvider;
  25. use OCP\Security\ISecureRandom;
  26. use Psr\Log\LoggerInterface;
  27. if (version_compare(\PHPUnit\Runner\Version::id(), 10, '>=')) {
  28. trait OnNotSuccessfulTestTrait {
  29. protected function onNotSuccessfulTest(\Throwable $t): never {
  30. $this->restoreAllServices();
  31. // restore database connection
  32. if (!$this->IsDatabaseAccessAllowed()) {
  33. \OC::$server->registerService(IDBConnection::class, function () {
  34. return self::$realDatabase;
  35. });
  36. }
  37. parent::onNotSuccessfulTest($t);
  38. }
  39. }
  40. } else {
  41. trait OnNotSuccessfulTestTrait {
  42. protected function onNotSuccessfulTest(\Throwable $t): void {
  43. $this->restoreAllServices();
  44. // restore database connection
  45. if (!$this->IsDatabaseAccessAllowed()) {
  46. \OC::$server->registerService(IDBConnection::class, function () {
  47. return self::$realDatabase;
  48. });
  49. }
  50. parent::onNotSuccessfulTest($t);
  51. }
  52. }
  53. }
  54. abstract class TestCase extends \PHPUnit\Framework\TestCase {
  55. /** @var \OC\Command\QueueBus */
  56. private $commandBus;
  57. /** @var IDBConnection */
  58. protected static $realDatabase = null;
  59. /** @var bool */
  60. private static $wasDatabaseAllowed = false;
  61. /** @var array */
  62. protected $services = [];
  63. use OnNotSuccessfulTestTrait;
  64. /**
  65. * @param string $name
  66. * @param mixed $newService
  67. * @return bool
  68. */
  69. public function overwriteService(string $name, $newService): bool {
  70. if (isset($this->services[$name])) {
  71. return false;
  72. }
  73. $this->services[$name] = \OC::$server->query($name);
  74. $container = \OC::$server->getAppContainerForService($name);
  75. $container = $container ?? \OC::$server;
  76. $container->registerService($name, function () use ($newService) {
  77. return $newService;
  78. });
  79. return true;
  80. }
  81. /**
  82. * @param string $name
  83. * @return bool
  84. */
  85. public function restoreService(string $name): bool {
  86. if (isset($this->services[$name])) {
  87. $oldService = $this->services[$name];
  88. $container = \OC::$server->getAppContainerForService($name);
  89. $container = $container ?? \OC::$server;
  90. $container->registerService($name, function () use ($oldService) {
  91. return $oldService;
  92. });
  93. unset($this->services[$name]);
  94. return true;
  95. }
  96. return false;
  97. }
  98. public function restoreAllServices() {
  99. if (!empty($this->services)) {
  100. if (!empty($this->services)) {
  101. foreach ($this->services as $name => $service) {
  102. $this->restoreService($name);
  103. }
  104. }
  105. }
  106. }
  107. protected function getTestTraits() {
  108. $traits = [];
  109. $class = $this;
  110. do {
  111. $traits = array_merge(class_uses($class), $traits);
  112. } while ($class = get_parent_class($class));
  113. foreach ($traits as $trait => $same) {
  114. $traits = array_merge(class_uses($trait), $traits);
  115. }
  116. $traits = array_unique($traits);
  117. return array_filter($traits, function ($trait) {
  118. return substr($trait, 0, 5) === 'Test\\';
  119. });
  120. }
  121. protected function setUp(): void {
  122. // overwrite the command bus with one we can run ourselves
  123. $this->commandBus = new QueueBus();
  124. $this->overwriteService('AsyncCommandBus', $this->commandBus);
  125. $this->overwriteService(IBus::class, $this->commandBus);
  126. // detect database access
  127. self::$wasDatabaseAllowed = true;
  128. if (!$this->IsDatabaseAccessAllowed()) {
  129. self::$wasDatabaseAllowed = false;
  130. if (is_null(self::$realDatabase)) {
  131. self::$realDatabase = \OC::$server->getDatabaseConnection();
  132. }
  133. \OC::$server->registerService(IDBConnection::class, function () {
  134. $this->fail('Your test case is not allowed to access the database.');
  135. });
  136. }
  137. $traits = $this->getTestTraits();
  138. foreach ($traits as $trait) {
  139. $methodName = 'setUp' . basename(str_replace('\\', '/', $trait));
  140. if (method_exists($this, $methodName)) {
  141. call_user_func([$this, $methodName]);
  142. }
  143. }
  144. }
  145. protected function tearDown(): void {
  146. $this->restoreAllServices();
  147. // restore database connection
  148. if (!$this->IsDatabaseAccessAllowed()) {
  149. \OC::$server->registerService(IDBConnection::class, function () {
  150. return self::$realDatabase;
  151. });
  152. }
  153. // further cleanup
  154. $hookExceptions = \OC_Hook::$thrownExceptions;
  155. \OC_Hook::$thrownExceptions = [];
  156. \OC::$server->get(ILockingProvider::class)->releaseAll();
  157. if (!empty($hookExceptions)) {
  158. throw $hookExceptions[0];
  159. }
  160. // fail hard if xml errors have not been cleaned up
  161. $errors = libxml_get_errors();
  162. libxml_clear_errors();
  163. if (!empty($errors)) {
  164. self::assertEquals([], $errors, 'There have been xml parsing errors');
  165. }
  166. if ($this->IsDatabaseAccessAllowed()) {
  167. \OC\Files\Cache\Storage::getGlobalCache()->clearCache();
  168. }
  169. // tearDown the traits
  170. $traits = $this->getTestTraits();
  171. foreach ($traits as $trait) {
  172. $methodName = 'tearDown' . basename(str_replace('\\', '/', $trait));
  173. if (method_exists($this, $methodName)) {
  174. call_user_func([$this, $methodName]);
  175. }
  176. }
  177. }
  178. /**
  179. * Allows us to test private methods/properties
  180. *
  181. * @param $object
  182. * @param $methodName
  183. * @param array $parameters
  184. * @return mixed
  185. */
  186. protected static function invokePrivate($object, $methodName, array $parameters = []) {
  187. if (is_string($object)) {
  188. $className = $object;
  189. } else {
  190. $className = get_class($object);
  191. }
  192. $reflection = new \ReflectionClass($className);
  193. if ($reflection->hasMethod($methodName)) {
  194. $method = $reflection->getMethod($methodName);
  195. $method->setAccessible(true);
  196. return $method->invokeArgs($object, $parameters);
  197. } elseif ($reflection->hasProperty($methodName)) {
  198. $property = $reflection->getProperty($methodName);
  199. $property->setAccessible(true);
  200. if (!empty($parameters)) {
  201. if ($property->isStatic()) {
  202. $property->setValue(null, array_pop($parameters));
  203. } else {
  204. $property->setValue($object, array_pop($parameters));
  205. }
  206. }
  207. if (is_object($object)) {
  208. return $property->getValue($object);
  209. }
  210. return $property->getValue();
  211. } elseif ($reflection->hasConstant($methodName)) {
  212. return $reflection->getConstant($methodName);
  213. }
  214. return false;
  215. }
  216. /**
  217. * Returns a unique identifier as uniqid() is not reliable sometimes
  218. *
  219. * @param string $prefix
  220. * @param int $length
  221. * @return string
  222. */
  223. protected static function getUniqueID($prefix = '', $length = 13) {
  224. return $prefix . \OC::$server->get(ISecureRandom::class)->generate(
  225. $length,
  226. // Do not use dots and slashes as we use the value for file names
  227. ISecureRandom::CHAR_DIGITS . ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_UPPER
  228. );
  229. }
  230. /**
  231. * Filter methods
  232. *
  233. * Returns all methods of the given class,
  234. * that are public or abstract and not in the ignoreMethods list,
  235. * to be able to fill onlyMethods() with an inverted list.
  236. *
  237. * @param string $className
  238. * @param string[] $filterMethods
  239. * @return string[]
  240. */
  241. public function filterClassMethods(string $className, array $filterMethods): array {
  242. $class = new \ReflectionClass($className);
  243. $methods = [];
  244. foreach ($class->getMethods() as $method) {
  245. if (($method->isPublic() || $method->isAbstract()) && !in_array($method->getName(), $filterMethods, true)) {
  246. $methods[] = $method->getName();
  247. }
  248. }
  249. return $methods;
  250. }
  251. public static function tearDownAfterClass(): void {
  252. if (!self::$wasDatabaseAllowed && self::$realDatabase !== null) {
  253. // in case an error is thrown in a test, PHPUnit jumps straight to tearDownAfterClass,
  254. // so we need the database again
  255. \OC::$server->registerService(IDBConnection::class, function () {
  256. return self::$realDatabase;
  257. });
  258. }
  259. $dataDir = \OC::$server->getConfig()->getSystemValueString('datadirectory', \OC::$SERVERROOT . '/data-autotest');
  260. if (self::$wasDatabaseAllowed && \OC::$server->getDatabaseConnection()) {
  261. $db = \OC::$server->getDatabaseConnection();
  262. if ($db->inTransaction()) {
  263. $db->rollBack();
  264. throw new \Exception('There was a transaction still in progress and needed to be rolled back. Please fix this in your test.');
  265. }
  266. $queryBuilder = $db->getQueryBuilder();
  267. self::tearDownAfterClassCleanShares($queryBuilder);
  268. self::tearDownAfterClassCleanStorages($queryBuilder);
  269. self::tearDownAfterClassCleanFileCache($queryBuilder);
  270. }
  271. self::tearDownAfterClassCleanStrayDataFiles($dataDir);
  272. self::tearDownAfterClassCleanStrayHooks();
  273. self::tearDownAfterClassCleanStrayLocks();
  274. /** @var SetupManager $setupManager */
  275. $setupManager = \OC::$server->get(SetupManager::class);
  276. $setupManager->tearDown();
  277. /** @var MountProviderCollection $mountProviderCollection */
  278. $mountProviderCollection = \OC::$server->get(MountProviderCollection::class);
  279. $mountProviderCollection->clearProviders();
  280. /** @var IConfig $config */
  281. $config = \OC::$server->get(IConfig::class);
  282. $mountProviderCollection->registerProvider(new CacheMountProvider($config));
  283. $mountProviderCollection->registerHomeProvider(new LocalHomeMountProvider());
  284. $mountProviderCollection->registerRootProvider(new RootMountProvider($config, \OC::$server->get(LoggerInterface::class)));
  285. $setupManager->setupRoot();
  286. parent::tearDownAfterClass();
  287. }
  288. /**
  289. * Remove all entries from the share table
  290. *
  291. * @param IQueryBuilder $queryBuilder
  292. */
  293. protected static function tearDownAfterClassCleanShares(IQueryBuilder $queryBuilder) {
  294. $queryBuilder->delete('share')
  295. ->execute();
  296. }
  297. /**
  298. * Remove all entries from the storages table
  299. *
  300. * @param IQueryBuilder $queryBuilder
  301. */
  302. protected static function tearDownAfterClassCleanStorages(IQueryBuilder $queryBuilder) {
  303. $queryBuilder->delete('storages')
  304. ->execute();
  305. }
  306. /**
  307. * Remove all entries from the filecache table
  308. *
  309. * @param IQueryBuilder $queryBuilder
  310. */
  311. protected static function tearDownAfterClassCleanFileCache(IQueryBuilder $queryBuilder) {
  312. $queryBuilder->delete('filecache')
  313. ->runAcrossAllShards()
  314. ->execute();
  315. }
  316. /**
  317. * Remove all unused files from the data dir
  318. *
  319. * @param string $dataDir
  320. */
  321. protected static function tearDownAfterClassCleanStrayDataFiles($dataDir) {
  322. $knownEntries = [
  323. 'nextcloud.log' => true,
  324. 'audit.log' => true,
  325. 'owncloud.db' => true,
  326. '.ocdata' => true,
  327. '..' => true,
  328. '.' => true,
  329. ];
  330. if ($dh = opendir($dataDir)) {
  331. while (($file = readdir($dh)) !== false) {
  332. if (!isset($knownEntries[$file])) {
  333. self::tearDownAfterClassCleanStrayDataUnlinkDir($dataDir . '/' . $file);
  334. }
  335. }
  336. closedir($dh);
  337. }
  338. }
  339. /**
  340. * Recursive delete files and folders from a given directory
  341. *
  342. * @param string $dir
  343. */
  344. protected static function tearDownAfterClassCleanStrayDataUnlinkDir($dir) {
  345. if ($dh = @opendir($dir)) {
  346. while (($file = readdir($dh)) !== false) {
  347. if (\OC\Files\Filesystem::isIgnoredDir($file)) {
  348. continue;
  349. }
  350. $path = $dir . '/' . $file;
  351. if (is_dir($path)) {
  352. self::tearDownAfterClassCleanStrayDataUnlinkDir($path);
  353. } else {
  354. @unlink($path);
  355. }
  356. }
  357. closedir($dh);
  358. }
  359. @rmdir($dir);
  360. }
  361. /**
  362. * Clean up the list of hooks
  363. */
  364. protected static function tearDownAfterClassCleanStrayHooks() {
  365. \OC_Hook::clear();
  366. }
  367. /**
  368. * Clean up the list of locks
  369. */
  370. protected static function tearDownAfterClassCleanStrayLocks() {
  371. \OC::$server->get(ILockingProvider::class)->releaseAll();
  372. }
  373. /**
  374. * Login and setup FS as a given user,
  375. * sets the given user as the current user.
  376. *
  377. * @param string $user user id or empty for a generic FS
  378. */
  379. protected static function loginAsUser($user = '') {
  380. self::logout();
  381. \OC\Files\Filesystem::tearDown();
  382. \OC_User::setUserId($user);
  383. $userObject = \OC::$server->getUserManager()->get($user);
  384. if (!is_null($userObject)) {
  385. $userObject->updateLastLoginTimestamp();
  386. }
  387. \OC_Util::setupFS($user);
  388. if (\OC::$server->getUserManager()->userExists($user)) {
  389. \OC::$server->getUserFolder($user);
  390. }
  391. }
  392. /**
  393. * Logout the current user and tear down the filesystem.
  394. */
  395. protected static function logout() {
  396. \OC_Util::tearDownFS();
  397. \OC_User::setUserId('');
  398. // needed for fully logout
  399. \OC::$server->getUserSession()->setUser(null);
  400. }
  401. /**
  402. * Run all commands pushed to the bus
  403. */
  404. protected function runCommands() {
  405. // get the user for which the fs is setup
  406. $view = Filesystem::getView();
  407. if ($view) {
  408. [, $user] = explode('/', $view->getRoot());
  409. } else {
  410. $user = null;
  411. }
  412. \OC_Util::tearDownFS(); // command can't reply on the fs being setup
  413. $this->commandBus->run();
  414. \OC_Util::tearDownFS();
  415. if ($user) {
  416. \OC_Util::setupFS($user);
  417. }
  418. }
  419. /**
  420. * Check if the given path is locked with a given type
  421. *
  422. * @param \OC\Files\View $view view
  423. * @param string $path path to check
  424. * @param int $type lock type
  425. * @param bool $onMountPoint true to check the mount point instead of the
  426. * mounted storage
  427. *
  428. * @return boolean true if the file is locked with the
  429. * given type, false otherwise
  430. */
  431. protected function isFileLocked($view, $path, $type, $onMountPoint = false) {
  432. // Note: this seems convoluted but is necessary because
  433. // the format of the lock key depends on the storage implementation
  434. // (in our case mostly md5)
  435. if ($type === \OCP\Lock\ILockingProvider::LOCK_SHARED) {
  436. // to check if the file has a shared lock, try acquiring an exclusive lock
  437. $checkType = \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE;
  438. } else {
  439. // a shared lock cannot be set if exclusive lock is in place
  440. $checkType = \OCP\Lock\ILockingProvider::LOCK_SHARED;
  441. }
  442. try {
  443. $view->lockFile($path, $checkType, $onMountPoint);
  444. // no exception, which means the lock of $type is not set
  445. // clean up
  446. $view->unlockFile($path, $checkType, $onMountPoint);
  447. return false;
  448. } catch (\OCP\Lock\LockedException $e) {
  449. // we could not acquire the counter-lock, which means
  450. // the lock of $type was in place
  451. return true;
  452. }
  453. }
  454. protected function getGroupAnnotations(): array {
  455. if (method_exists($this, 'getAnnotations')) {
  456. $annotations = $this->getAnnotations();
  457. return $annotations['class']['group'] ?? [];
  458. }
  459. $r = new \ReflectionClass($this);
  460. $doc = $r->getDocComment();
  461. preg_match_all('#@group\s+(.*?)\n#s', $doc, $annotations);
  462. return $annotations[1] ?? [];
  463. }
  464. protected function IsDatabaseAccessAllowed() {
  465. $annotations = $this->getGroupAnnotations();
  466. if (isset($annotations)) {
  467. if (in_array('DB', $annotations) || in_array('SLOWDB', $annotations)) {
  468. return true;
  469. }
  470. }
  471. return false;
  472. }
  473. /**
  474. * @param string $expectedHtml
  475. * @param string $template
  476. * @param array $vars
  477. */
  478. protected function assertTemplate($expectedHtml, $template, $vars = []) {
  479. require_once __DIR__ . '/../../lib/private/legacy/template/functions.php';
  480. $requestToken = 12345;
  481. /** @var Defaults|\PHPUnit\Framework\MockObject\MockObject $l10n */
  482. $theme = $this->getMockBuilder('\OCP\Defaults')
  483. ->disableOriginalConstructor()->getMock();
  484. $theme->expects($this->any())
  485. ->method('getName')
  486. ->willReturn('Nextcloud');
  487. /** @var IL10N|\PHPUnit\Framework\MockObject\MockObject $l10n */
  488. $l10n = $this->getMockBuilder(IL10N::class)
  489. ->disableOriginalConstructor()->getMock();
  490. $l10n
  491. ->expects($this->any())
  492. ->method('t')
  493. ->willReturnCallback(function ($text, $parameters = []) {
  494. return vsprintf($text, $parameters);
  495. });
  496. $t = new Base($template, $requestToken, $l10n, $theme);
  497. $buf = $t->fetchPage($vars);
  498. $this->assertHtmlStringEqualsHtmlString($expectedHtml, $buf);
  499. }
  500. /**
  501. * @param string $expectedHtml
  502. * @param string $actualHtml
  503. * @param string $message
  504. */
  505. protected function assertHtmlStringEqualsHtmlString($expectedHtml, $actualHtml, $message = '') {
  506. $expected = new DOMDocument();
  507. $expected->preserveWhiteSpace = false;
  508. $expected->formatOutput = true;
  509. $expected->loadHTML($expectedHtml);
  510. $actual = new DOMDocument();
  511. $actual->preserveWhiteSpace = false;
  512. $actual->formatOutput = true;
  513. $actual->loadHTML($actualHtml);
  514. $this->removeWhitespaces($actual);
  515. $expectedHtml1 = $expected->saveHTML();
  516. $actualHtml1 = $actual->saveHTML();
  517. self::assertEquals($expectedHtml1, $actualHtml1, $message);
  518. }
  519. private function removeWhitespaces(DOMNode $domNode) {
  520. foreach ($domNode->childNodes as $node) {
  521. if ($node->hasChildNodes()) {
  522. $this->removeWhitespaces($node);
  523. } else {
  524. if ($node instanceof \DOMText && $node->isWhitespaceInElementContent()) {
  525. $domNode->removeChild($node);
  526. }
  527. }
  528. }
  529. }
  530. }