1
0

TestCase.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  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. $queryBuilder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
  224. self::tearDownAfterClassCleanShares($queryBuilder);
  225. self::tearDownAfterClassCleanStorages($queryBuilder);
  226. self::tearDownAfterClassCleanFileCache($queryBuilder);
  227. }
  228. self::tearDownAfterClassCleanStrayDataFiles($dataDir);
  229. self::tearDownAfterClassCleanStrayHooks();
  230. self::tearDownAfterClassCleanStrayLocks();
  231. parent::tearDownAfterClass();
  232. }
  233. /**
  234. * Remove all entries from the share table
  235. *
  236. * @param IQueryBuilder $queryBuilder
  237. */
  238. protected static function tearDownAfterClassCleanShares(IQueryBuilder $queryBuilder) {
  239. $queryBuilder->delete('share')
  240. ->execute();
  241. }
  242. /**
  243. * Remove all entries from the storages table
  244. *
  245. * @param IQueryBuilder $queryBuilder
  246. */
  247. protected static function tearDownAfterClassCleanStorages(IQueryBuilder $queryBuilder) {
  248. $queryBuilder->delete('storages')
  249. ->execute();
  250. }
  251. /**
  252. * Remove all entries from the filecache table
  253. *
  254. * @param IQueryBuilder $queryBuilder
  255. */
  256. protected static function tearDownAfterClassCleanFileCache(IQueryBuilder $queryBuilder) {
  257. $queryBuilder->delete('filecache')
  258. ->execute();
  259. }
  260. /**
  261. * Remove all unused files from the data dir
  262. *
  263. * @param string $dataDir
  264. */
  265. protected static function tearDownAfterClassCleanStrayDataFiles($dataDir) {
  266. $knownEntries = [
  267. 'nextcloud.log' => true,
  268. 'audit.log' => true,
  269. 'owncloud.db' => true,
  270. '.ocdata' => true,
  271. '..' => true,
  272. '.' => true,
  273. ];
  274. if ($dh = opendir($dataDir)) {
  275. while (($file = readdir($dh)) !== false) {
  276. if (!isset($knownEntries[$file])) {
  277. self::tearDownAfterClassCleanStrayDataUnlinkDir($dataDir . '/' . $file);
  278. }
  279. }
  280. closedir($dh);
  281. }
  282. }
  283. /**
  284. * Recursive delete files and folders from a given directory
  285. *
  286. * @param string $dir
  287. */
  288. protected static function tearDownAfterClassCleanStrayDataUnlinkDir($dir) {
  289. if ($dh = @opendir($dir)) {
  290. while (($file = readdir($dh)) !== false) {
  291. if (\OC\Files\Filesystem::isIgnoredDir($file)) {
  292. continue;
  293. }
  294. $path = $dir . '/' . $file;
  295. if (is_dir($path)) {
  296. self::tearDownAfterClassCleanStrayDataUnlinkDir($path);
  297. } else {
  298. @unlink($path);
  299. }
  300. }
  301. closedir($dh);
  302. }
  303. @rmdir($dir);
  304. }
  305. /**
  306. * Clean up the list of hooks
  307. */
  308. protected static function tearDownAfterClassCleanStrayHooks() {
  309. \OC_Hook::clear();
  310. }
  311. /**
  312. * Clean up the list of locks
  313. */
  314. protected static function tearDownAfterClassCleanStrayLocks() {
  315. \OC::$server->getLockingProvider()->releaseAll();
  316. }
  317. /**
  318. * Login and setup FS as a given user,
  319. * sets the given user as the current user.
  320. *
  321. * @param string $user user id or empty for a generic FS
  322. */
  323. protected static function loginAsUser($user = '') {
  324. self::logout();
  325. \OC\Files\Filesystem::tearDown();
  326. \OC_User::setUserId($user);
  327. $userObject = \OC::$server->getUserManager()->get($user);
  328. if (!is_null($userObject)) {
  329. $userObject->updateLastLoginTimestamp();
  330. }
  331. \OC_Util::setupFS($user);
  332. if (\OC::$server->getUserManager()->userExists($user)) {
  333. \OC::$server->getUserFolder($user);
  334. }
  335. }
  336. /**
  337. * Logout the current user and tear down the filesystem.
  338. */
  339. protected static function logout() {
  340. \OC_Util::tearDownFS();
  341. \OC_User::setUserId('');
  342. // needed for fully logout
  343. \OC::$server->getUserSession()->setUser(null);
  344. }
  345. /**
  346. * Run all commands pushed to the bus
  347. */
  348. protected function runCommands() {
  349. // get the user for which the fs is setup
  350. $view = Filesystem::getView();
  351. if ($view) {
  352. list(, $user) = explode('/', $view->getRoot());
  353. } else {
  354. $user = null;
  355. }
  356. \OC_Util::tearDownFS(); // command can't reply on the fs being setup
  357. $this->commandBus->run();
  358. \OC_Util::tearDownFS();
  359. if ($user) {
  360. \OC_Util::setupFS($user);
  361. }
  362. }
  363. /**
  364. * Check if the given path is locked with a given type
  365. *
  366. * @param \OC\Files\View $view view
  367. * @param string $path path to check
  368. * @param int $type lock type
  369. * @param bool $onMountPoint true to check the mount point instead of the
  370. * mounted storage
  371. *
  372. * @return boolean true if the file is locked with the
  373. * given type, false otherwise
  374. */
  375. protected function isFileLocked($view, $path, $type, $onMountPoint = false) {
  376. // Note: this seems convoluted but is necessary because
  377. // the format of the lock key depends on the storage implementation
  378. // (in our case mostly md5)
  379. if ($type === \OCP\Lock\ILockingProvider::LOCK_SHARED) {
  380. // to check if the file has a shared lock, try acquiring an exclusive lock
  381. $checkType = \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE;
  382. } else {
  383. // a shared lock cannot be set if exclusive lock is in place
  384. $checkType = \OCP\Lock\ILockingProvider::LOCK_SHARED;
  385. }
  386. try {
  387. $view->lockFile($path, $checkType, $onMountPoint);
  388. // no exception, which means the lock of $type is not set
  389. // clean up
  390. $view->unlockFile($path, $checkType, $onMountPoint);
  391. return false;
  392. } catch (\OCP\Lock\LockedException $e) {
  393. // we could not acquire the counter-lock, which means
  394. // the lock of $type was in place
  395. return true;
  396. }
  397. }
  398. protected function IsDatabaseAccessAllowed() {
  399. // on travis-ci.org we allow database access in any case - otherwise
  400. // this will break all apps right away
  401. if (true == getenv('TRAVIS')) {
  402. return true;
  403. }
  404. $annotations = $this->getAnnotations();
  405. if (isset($annotations['class']['group'])) {
  406. if (in_array('DB', $annotations['class']['group']) || in_array('SLOWDB', $annotations['class']['group'])) {
  407. return true;
  408. }
  409. }
  410. return false;
  411. }
  412. /**
  413. * @param string $expectedHtml
  414. * @param string $template
  415. * @param array $vars
  416. */
  417. protected function assertTemplate($expectedHtml, $template, $vars = []) {
  418. require_once __DIR__.'/../../lib/private/legacy/template/functions.php';
  419. $requestToken = 12345;
  420. /** @var Defaults|\PHPUnit\Framework\MockObject\MockObject $l10n */
  421. $theme = $this->getMockBuilder('\OCP\Defaults')
  422. ->disableOriginalConstructor()->getMock();
  423. $theme->expects($this->any())
  424. ->method('getName')
  425. ->willReturn('Nextcloud');
  426. /** @var IL10N|\PHPUnit\Framework\MockObject\MockObject $l10n */
  427. $l10n = $this->getMockBuilder(IL10N::class)
  428. ->disableOriginalConstructor()->getMock();
  429. $l10n
  430. ->expects($this->any())
  431. ->method('t')
  432. ->willReturnCallback(function ($text, $parameters = []) {
  433. return vsprintf($text, $parameters);
  434. });
  435. $t = new Base($template, $requestToken, $l10n, $theme);
  436. $buf = $t->fetchPage($vars);
  437. $this->assertHtmlStringEqualsHtmlString($expectedHtml, $buf);
  438. }
  439. /**
  440. * @param string $expectedHtml
  441. * @param string $actualHtml
  442. * @param string $message
  443. */
  444. protected function assertHtmlStringEqualsHtmlString($expectedHtml, $actualHtml, $message = '') {
  445. $expected = new DOMDocument();
  446. $expected->preserveWhiteSpace = false;
  447. $expected->formatOutput = true;
  448. $expected->loadHTML($expectedHtml);
  449. $actual = new DOMDocument();
  450. $actual->preserveWhiteSpace = false;
  451. $actual->formatOutput = true;
  452. $actual->loadHTML($actualHtml);
  453. $this->removeWhitespaces($actual);
  454. $expectedHtml1 = $expected->saveHTML();
  455. $actualHtml1 = $actual->saveHTML();
  456. self::assertEquals($expectedHtml1, $actualHtml1, $message);
  457. }
  458. private function removeWhitespaces(DOMNode $domNode) {
  459. foreach ($domNode->childNodes as $node) {
  460. if ($node->hasChildNodes()) {
  461. $this->removeWhitespaces($node);
  462. } else {
  463. if ($node instanceof \DOMText && $node->isWhitespaceInElementContent()) {
  464. $domNode->removeChild($node);
  465. }
  466. }
  467. }
  468. }
  469. }