TestCase.php 14 KB

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