TestCase.php 14 KB

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