1
0

TestCase.php 16 KB

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