TestCase.php 16 KB

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