TestCase.php 14 KB

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