TestCase.php 17 KB

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