You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

TestCase.php 15KB

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