TestCase.php 14 KB

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