TestCase.php 14 KB

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