TestCase.php 14 KB

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