TestCase.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591
  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. public static function tearDownAfterClass(): void {
  231. if (!self::$wasDatabaseAllowed && self::$realDatabase !== null) {
  232. // in case an error is thrown in a test, PHPUnit jumps straight to tearDownAfterClass,
  233. // so we need the database again
  234. \OC::$server->registerService(IDBConnection::class, function () {
  235. return self::$realDatabase;
  236. });
  237. }
  238. $dataDir = \OC::$server->getConfig()->getSystemValueString('datadirectory', \OC::$SERVERROOT . '/data-autotest');
  239. if (self::$wasDatabaseAllowed && \OC::$server->getDatabaseConnection()) {
  240. $db = \OC::$server->getDatabaseConnection();
  241. if ($db->inTransaction()) {
  242. $db->rollBack();
  243. throw new \Exception('There was a transaction still in progress and needed to be rolled back. Please fix this in your test.');
  244. }
  245. $queryBuilder = $db->getQueryBuilder();
  246. self::tearDownAfterClassCleanShares($queryBuilder);
  247. self::tearDownAfterClassCleanStorages($queryBuilder);
  248. self::tearDownAfterClassCleanFileCache($queryBuilder);
  249. }
  250. self::tearDownAfterClassCleanStrayDataFiles($dataDir);
  251. self::tearDownAfterClassCleanStrayHooks();
  252. self::tearDownAfterClassCleanStrayLocks();
  253. /** @var SetupManager $setupManager */
  254. $setupManager = \OC::$server->get(SetupManager::class);
  255. $setupManager->tearDown();
  256. /** @var MountProviderCollection $mountProviderCollection */
  257. $mountProviderCollection = \OC::$server->get(MountProviderCollection::class);
  258. $mountProviderCollection->clearProviders();
  259. /** @var IConfig $config */
  260. $config = \OC::$server->get(IConfig::class);
  261. $mountProviderCollection->registerProvider(new CacheMountProvider($config));
  262. $mountProviderCollection->registerHomeProvider(new LocalHomeMountProvider());
  263. $mountProviderCollection->registerRootProvider(new RootMountProvider($config, \OC::$server->get(LoggerInterface::class)));
  264. $setupManager->setupRoot();
  265. parent::tearDownAfterClass();
  266. }
  267. /**
  268. * Remove all entries from the share table
  269. *
  270. * @param IQueryBuilder $queryBuilder
  271. */
  272. protected static function tearDownAfterClassCleanShares(IQueryBuilder $queryBuilder) {
  273. $queryBuilder->delete('share')
  274. ->execute();
  275. }
  276. /**
  277. * Remove all entries from the storages table
  278. *
  279. * @param IQueryBuilder $queryBuilder
  280. */
  281. protected static function tearDownAfterClassCleanStorages(IQueryBuilder $queryBuilder) {
  282. $queryBuilder->delete('storages')
  283. ->execute();
  284. }
  285. /**
  286. * Remove all entries from the filecache table
  287. *
  288. * @param IQueryBuilder $queryBuilder
  289. */
  290. protected static function tearDownAfterClassCleanFileCache(IQueryBuilder $queryBuilder) {
  291. $queryBuilder->delete('filecache')
  292. ->runAcrossAllShards()
  293. ->execute();
  294. }
  295. /**
  296. * Remove all unused files from the data dir
  297. *
  298. * @param string $dataDir
  299. */
  300. protected static function tearDownAfterClassCleanStrayDataFiles($dataDir) {
  301. $knownEntries = [
  302. 'nextcloud.log' => true,
  303. 'audit.log' => true,
  304. 'owncloud.db' => true,
  305. '.ocdata' => true,
  306. '..' => true,
  307. '.' => true,
  308. ];
  309. if ($dh = opendir($dataDir)) {
  310. while (($file = readdir($dh)) !== false) {
  311. if (!isset($knownEntries[$file])) {
  312. self::tearDownAfterClassCleanStrayDataUnlinkDir($dataDir . '/' . $file);
  313. }
  314. }
  315. closedir($dh);
  316. }
  317. }
  318. /**
  319. * Recursive delete files and folders from a given directory
  320. *
  321. * @param string $dir
  322. */
  323. protected static function tearDownAfterClassCleanStrayDataUnlinkDir($dir) {
  324. if ($dh = @opendir($dir)) {
  325. while (($file = readdir($dh)) !== false) {
  326. if (\OC\Files\Filesystem::isIgnoredDir($file)) {
  327. continue;
  328. }
  329. $path = $dir . '/' . $file;
  330. if (is_dir($path)) {
  331. self::tearDownAfterClassCleanStrayDataUnlinkDir($path);
  332. } else {
  333. @unlink($path);
  334. }
  335. }
  336. closedir($dh);
  337. }
  338. @rmdir($dir);
  339. }
  340. /**
  341. * Clean up the list of hooks
  342. */
  343. protected static function tearDownAfterClassCleanStrayHooks() {
  344. \OC_Hook::clear();
  345. }
  346. /**
  347. * Clean up the list of locks
  348. */
  349. protected static function tearDownAfterClassCleanStrayLocks() {
  350. \OC::$server->get(ILockingProvider::class)->releaseAll();
  351. }
  352. /**
  353. * Login and setup FS as a given user,
  354. * sets the given user as the current user.
  355. *
  356. * @param string $user user id or empty for a generic FS
  357. */
  358. protected static function loginAsUser($user = '') {
  359. self::logout();
  360. \OC\Files\Filesystem::tearDown();
  361. \OC_User::setUserId($user);
  362. $userObject = \OC::$server->getUserManager()->get($user);
  363. if (!is_null($userObject)) {
  364. $userObject->updateLastLoginTimestamp();
  365. }
  366. \OC_Util::setupFS($user);
  367. if (\OC::$server->getUserManager()->userExists($user)) {
  368. \OC::$server->getUserFolder($user);
  369. }
  370. }
  371. /**
  372. * Logout the current user and tear down the filesystem.
  373. */
  374. protected static function logout() {
  375. \OC_Util::tearDownFS();
  376. \OC_User::setUserId('');
  377. // needed for fully logout
  378. \OC::$server->getUserSession()->setUser(null);
  379. }
  380. /**
  381. * Run all commands pushed to the bus
  382. */
  383. protected function runCommands() {
  384. // get the user for which the fs is setup
  385. $view = Filesystem::getView();
  386. if ($view) {
  387. [, $user] = explode('/', $view->getRoot());
  388. } else {
  389. $user = null;
  390. }
  391. \OC_Util::tearDownFS(); // command can't reply on the fs being setup
  392. $this->commandBus->run();
  393. \OC_Util::tearDownFS();
  394. if ($user) {
  395. \OC_Util::setupFS($user);
  396. }
  397. }
  398. /**
  399. * Check if the given path is locked with a given type
  400. *
  401. * @param \OC\Files\View $view view
  402. * @param string $path path to check
  403. * @param int $type lock type
  404. * @param bool $onMountPoint true to check the mount point instead of the
  405. * mounted storage
  406. *
  407. * @return boolean true if the file is locked with the
  408. * given type, false otherwise
  409. */
  410. protected function isFileLocked($view, $path, $type, $onMountPoint = false) {
  411. // Note: this seems convoluted but is necessary because
  412. // the format of the lock key depends on the storage implementation
  413. // (in our case mostly md5)
  414. if ($type === \OCP\Lock\ILockingProvider::LOCK_SHARED) {
  415. // to check if the file has a shared lock, try acquiring an exclusive lock
  416. $checkType = \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE;
  417. } else {
  418. // a shared lock cannot be set if exclusive lock is in place
  419. $checkType = \OCP\Lock\ILockingProvider::LOCK_SHARED;
  420. }
  421. try {
  422. $view->lockFile($path, $checkType, $onMountPoint);
  423. // no exception, which means the lock of $type is not set
  424. // clean up
  425. $view->unlockFile($path, $checkType, $onMountPoint);
  426. return false;
  427. } catch (\OCP\Lock\LockedException $e) {
  428. // we could not acquire the counter-lock, which means
  429. // the lock of $type was in place
  430. return true;
  431. }
  432. }
  433. protected function getGroupAnnotations(): array {
  434. if (method_exists($this, 'getAnnotations')) {
  435. $annotations = $this->getAnnotations();
  436. return $annotations['class']['group'] ?? [];
  437. }
  438. $r = new \ReflectionClass($this);
  439. $doc = $r->getDocComment();
  440. preg_match_all('#@group\s+(.*?)\n#s', $doc, $annotations);
  441. return $annotations[1] ?? [];
  442. }
  443. protected function IsDatabaseAccessAllowed() {
  444. // on travis-ci.org we allow database access in any case - otherwise
  445. // this will break all apps right away
  446. if (getenv('TRAVIS') == true) {
  447. return true;
  448. }
  449. $annotations = $this->getGroupAnnotations();
  450. if (isset($annotations)) {
  451. if (in_array('DB', $annotations) || in_array('SLOWDB', $annotations)) {
  452. return true;
  453. }
  454. }
  455. return false;
  456. }
  457. /**
  458. * @param string $expectedHtml
  459. * @param string $template
  460. * @param array $vars
  461. */
  462. protected function assertTemplate($expectedHtml, $template, $vars = []) {
  463. require_once __DIR__.'/../../lib/private/legacy/template/functions.php';
  464. $requestToken = 12345;
  465. /** @var Defaults|\PHPUnit\Framework\MockObject\MockObject $l10n */
  466. $theme = $this->getMockBuilder('\OCP\Defaults')
  467. ->disableOriginalConstructor()->getMock();
  468. $theme->expects($this->any())
  469. ->method('getName')
  470. ->willReturn('Nextcloud');
  471. /** @var IL10N|\PHPUnit\Framework\MockObject\MockObject $l10n */
  472. $l10n = $this->getMockBuilder(IL10N::class)
  473. ->disableOriginalConstructor()->getMock();
  474. $l10n
  475. ->expects($this->any())
  476. ->method('t')
  477. ->willReturnCallback(function ($text, $parameters = []) {
  478. return vsprintf($text, $parameters);
  479. });
  480. $t = new Base($template, $requestToken, $l10n, $theme);
  481. $buf = $t->fetchPage($vars);
  482. $this->assertHtmlStringEqualsHtmlString($expectedHtml, $buf);
  483. }
  484. /**
  485. * @param string $expectedHtml
  486. * @param string $actualHtml
  487. * @param string $message
  488. */
  489. protected function assertHtmlStringEqualsHtmlString($expectedHtml, $actualHtml, $message = '') {
  490. $expected = new DOMDocument();
  491. $expected->preserveWhiteSpace = false;
  492. $expected->formatOutput = true;
  493. $expected->loadHTML($expectedHtml);
  494. $actual = new DOMDocument();
  495. $actual->preserveWhiteSpace = false;
  496. $actual->formatOutput = true;
  497. $actual->loadHTML($actualHtml);
  498. $this->removeWhitespaces($actual);
  499. $expectedHtml1 = $expected->saveHTML();
  500. $actualHtml1 = $actual->saveHTML();
  501. self::assertEquals($expectedHtml1, $actualHtml1, $message);
  502. }
  503. private function removeWhitespaces(DOMNode $domNode) {
  504. foreach ($domNode->childNodes as $node) {
  505. if ($node->hasChildNodes()) {
  506. $this->removeWhitespaces($node);
  507. } else {
  508. if ($node instanceof \DOMText && $node->isWhitespaceInElementContent()) {
  509. $domNode->removeChild($node);
  510. }
  511. }
  512. }
  513. }
  514. }