TestCase.php 13 KB

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