PageRenderTime 62ms CodeModel.GetById 34ms RepoModel.GetById 0ms app.codeStats 0ms

/tests/lib/testcase.php

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