TestCase.php 17 KB

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