TestCase.php 14 KB

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