TestCase.php 14 KB

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