1
0

TestCase.php 16 KB

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