You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

testcase.php 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  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 OC\Command\QueueBus;
  24. use OC\Files\Filesystem;
  25. use OCP\DB\QueryBuilder\IQueryBuilder;
  26. use OCP\IDBConnection;
  27. use OCP\Security\ISecureRandom;
  28. abstract class TestCase extends \PHPUnit_Framework_TestCase {
  29. /** @var \OC\Command\QueueBus */
  30. private $commandBus;
  31. /** @var IDBConnection */
  32. static protected $realDatabase = null;
  33. static private $wasDatabaseAllowed = false;
  34. protected function getTestTraits() {
  35. $traits = [];
  36. $class = $this;
  37. do {
  38. $traits = array_merge(class_uses($class), $traits);
  39. } while ($class = get_parent_class($class));
  40. foreach ($traits as $trait => $same) {
  41. $traits = array_merge(class_uses($trait), $traits);
  42. }
  43. $traits = array_unique($traits);
  44. return array_filter($traits, function ($trait) {
  45. return substr($trait, 0, 5) === 'Test\\';
  46. });
  47. }
  48. protected function setUp() {
  49. // detect database access
  50. self::$wasDatabaseAllowed = true;
  51. if (!$this->IsDatabaseAccessAllowed()) {
  52. self::$wasDatabaseAllowed = false;
  53. if (is_null(self::$realDatabase)) {
  54. self::$realDatabase = \OC::$server->getDatabaseConnection();
  55. }
  56. \OC::$server->registerService('DatabaseConnection', function () {
  57. $this->fail('Your test case is not allowed to access the database.');
  58. });
  59. }
  60. // overwrite the command bus with one we can run ourselves
  61. $this->commandBus = new QueueBus();
  62. \OC::$server->registerService('AsyncCommandBus', function () {
  63. return $this->commandBus;
  64. });
  65. $traits = $this->getTestTraits();
  66. foreach ($traits as $trait) {
  67. $methodName = 'setUp' . basename(str_replace('\\', '/', $trait));
  68. if (method_exists($this, $methodName)) {
  69. call_user_func([$this, $methodName]);
  70. }
  71. }
  72. }
  73. protected function tearDown() {
  74. // restore database connection
  75. if (!$this->IsDatabaseAccessAllowed()) {
  76. \OC::$server->registerService('DatabaseConnection', function () {
  77. return self::$realDatabase;
  78. });
  79. }
  80. // further cleanup
  81. $hookExceptions = \OC_Hook::$thrownExceptions;
  82. \OC_Hook::$thrownExceptions = [];
  83. \OC::$server->getLockingProvider()->releaseAll();
  84. if (!empty($hookExceptions)) {
  85. throw $hookExceptions[0];
  86. }
  87. // fail hard if xml errors have not been cleaned up
  88. $errors = libxml_get_errors();
  89. libxml_clear_errors();
  90. $this->assertEquals([], $errors);
  91. // tearDown the traits
  92. $traits = $this->getTestTraits();
  93. foreach ($traits as $trait) {
  94. $methodName = 'tearDown' . basename(str_replace('\\', '/', $trait));
  95. if (method_exists($this, $methodName)) {
  96. call_user_func([$this, $methodName]);
  97. }
  98. }
  99. }
  100. /**
  101. * Allows us to test private methods/properties
  102. *
  103. * @param $object
  104. * @param $methodName
  105. * @param array $parameters
  106. * @return mixed
  107. */
  108. protected static function invokePrivate($object, $methodName, array $parameters = array()) {
  109. $reflection = new \ReflectionClass(get_class($object));
  110. if ($reflection->hasMethod($methodName)) {
  111. $method = $reflection->getMethod($methodName);
  112. $method->setAccessible(true);
  113. return $method->invokeArgs($object, $parameters);
  114. } elseif ($reflection->hasProperty($methodName)) {
  115. $property = $reflection->getProperty($methodName);
  116. $property->setAccessible(true);
  117. if (!empty($parameters)) {
  118. $property->setValue($object, array_pop($parameters));
  119. }
  120. return $property->getValue($object);
  121. }
  122. return false;
  123. }
  124. /**
  125. * Returns a unique identifier as uniqid() is not reliable sometimes
  126. *
  127. * @param string $prefix
  128. * @param int $length
  129. * @return string
  130. */
  131. protected static function getUniqueID($prefix = '', $length = 13) {
  132. return $prefix . \OC::$server->getSecureRandom()->getLowStrengthGenerator()->generate(
  133. $length,
  134. // Do not use dots and slashes as we use the value for file names
  135. ISecureRandom::CHAR_DIGITS . ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_UPPER
  136. );
  137. }
  138. public static function tearDownAfterClass() {
  139. if (!self::$wasDatabaseAllowed && self::$realDatabase !== null) {
  140. // in case an error is thrown in a test, PHPUnit jumps straight to tearDownAfterClass,
  141. // so we need the database again
  142. \OC::$server->registerService('DatabaseConnection', function () {
  143. return self::$realDatabase;
  144. });
  145. }
  146. $dataDir = \OC::$server->getConfig()->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data-autotest');
  147. if (self::$wasDatabaseAllowed && \OC::$server->getDatabaseConnection()) {
  148. $queryBuilder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
  149. self::tearDownAfterClassCleanShares($queryBuilder);
  150. self::tearDownAfterClassCleanStorages($queryBuilder);
  151. self::tearDownAfterClassCleanFileCache($queryBuilder);
  152. }
  153. self::tearDownAfterClassCleanStrayDataFiles($dataDir);
  154. self::tearDownAfterClassCleanStrayHooks();
  155. self::tearDownAfterClassCleanStrayLocks();
  156. parent::tearDownAfterClass();
  157. }
  158. /**
  159. * Remove all entries from the share table
  160. *
  161. * @param IQueryBuilder $queryBuilder
  162. */
  163. static protected function tearDownAfterClassCleanShares(IQueryBuilder $queryBuilder) {
  164. $queryBuilder->delete('share')
  165. ->execute();
  166. }
  167. /**
  168. * Remove all entries from the storages table
  169. *
  170. * @param IQueryBuilder $queryBuilder
  171. */
  172. static protected function tearDownAfterClassCleanStorages(IQueryBuilder $queryBuilder) {
  173. $queryBuilder->delete('storages')
  174. ->execute();
  175. }
  176. /**
  177. * Remove all entries from the filecache table
  178. *
  179. * @param IQueryBuilder $queryBuilder
  180. */
  181. static protected function tearDownAfterClassCleanFileCache(IQueryBuilder $queryBuilder) {
  182. $queryBuilder->delete('filecache')
  183. ->execute();
  184. }
  185. /**
  186. * Remove all unused files from the data dir
  187. *
  188. * @param string $dataDir
  189. */
  190. static protected function tearDownAfterClassCleanStrayDataFiles($dataDir) {
  191. $knownEntries = array(
  192. 'owncloud.log' => true,
  193. 'owncloud.db' => true,
  194. '.ocdata' => true,
  195. '..' => true,
  196. '.' => true,
  197. );
  198. if ($dh = opendir($dataDir)) {
  199. while (($file = readdir($dh)) !== false) {
  200. if (!isset($knownEntries[$file])) {
  201. self::tearDownAfterClassCleanStrayDataUnlinkDir($dataDir . '/' . $file);
  202. }
  203. }
  204. closedir($dh);
  205. }
  206. }
  207. /**
  208. * Recursive delete files and folders from a given directory
  209. *
  210. * @param string $dir
  211. */
  212. static protected function tearDownAfterClassCleanStrayDataUnlinkDir($dir) {
  213. if ($dh = @opendir($dir)) {
  214. while (($file = readdir($dh)) !== false) {
  215. if (\OC\Files\Filesystem::isIgnoredDir($file)) {
  216. continue;
  217. }
  218. $path = $dir . '/' . $file;
  219. if (is_dir($path)) {
  220. self::tearDownAfterClassCleanStrayDataUnlinkDir($path);
  221. } else {
  222. @unlink($path);
  223. }
  224. }
  225. closedir($dh);
  226. }
  227. @rmdir($dir);
  228. }
  229. /**
  230. * Clean up the list of hooks
  231. */
  232. static protected function tearDownAfterClassCleanStrayHooks() {
  233. \OC_Hook::clear();
  234. }
  235. /**
  236. * Clean up the list of locks
  237. */
  238. static protected function tearDownAfterClassCleanStrayLocks() {
  239. \OC::$server->getLockingProvider()->releaseAll();
  240. }
  241. /**
  242. * Login and setup FS as a given user,
  243. * sets the given user as the current user.
  244. *
  245. * @param string $user user id or empty for a generic FS
  246. */
  247. static protected function loginAsUser($user = '') {
  248. self::logout();
  249. \OC\Files\Filesystem::tearDown();
  250. \OC_User::setUserId($user);
  251. \OC_Util::setupFS($user);
  252. if (\OC_User::userExists($user)) {
  253. \OC::$server->getUserFolder($user);
  254. }
  255. }
  256. /**
  257. * Logout the current user and tear down the filesystem.
  258. */
  259. static protected function logout() {
  260. \OC_Util::tearDownFS();
  261. \OC_User::setUserId('');
  262. // needed for fully logout
  263. \OC::$server->getUserSession()->setUser(null);
  264. }
  265. /**
  266. * Run all commands pushed to the bus
  267. */
  268. protected function runCommands() {
  269. // get the user for which the fs is setup
  270. $view = Filesystem::getView();
  271. if ($view) {
  272. list(, $user) = explode('/', $view->getRoot());
  273. } else {
  274. $user = null;
  275. }
  276. \OC_Util::tearDownFS(); // command cant reply on the fs being setup
  277. $this->commandBus->run();
  278. \OC_Util::tearDownFS();
  279. if ($user) {
  280. \OC_Util::setupFS($user);
  281. }
  282. }
  283. /**
  284. * Check if the given path is locked with a given type
  285. *
  286. * @param \OC\Files\View $view view
  287. * @param string $path path to check
  288. * @param int $type lock type
  289. * @param bool $onMountPoint true to check the mount point instead of the
  290. * mounted storage
  291. *
  292. * @return boolean true if the file is locked with the
  293. * given type, false otherwise
  294. */
  295. protected function isFileLocked($view, $path, $type, $onMountPoint = false) {
  296. // Note: this seems convoluted but is necessary because
  297. // the format of the lock key depends on the storage implementation
  298. // (in our case mostly md5)
  299. if ($type === \OCP\Lock\ILockingProvider::LOCK_SHARED) {
  300. // to check if the file has a shared lock, try acquiring an exclusive lock
  301. $checkType = \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE;
  302. } else {
  303. // a shared lock cannot be set if exclusive lock is in place
  304. $checkType = \OCP\Lock\ILockingProvider::LOCK_SHARED;
  305. }
  306. try {
  307. $view->lockFile($path, $checkType, $onMountPoint);
  308. // no exception, which means the lock of $type is not set
  309. // clean up
  310. $view->unlockFile($path, $checkType, $onMountPoint);
  311. return false;
  312. } catch (\OCP\Lock\LockedException $e) {
  313. // we could not acquire the counter-lock, which means
  314. // the lock of $type was in place
  315. return true;
  316. }
  317. }
  318. private function IsDatabaseAccessAllowed() {
  319. // on travis-ci.org we allow database access in any case - otherwise
  320. // this will break all apps right away
  321. if (true == getenv('TRAVIS')) {
  322. return true;
  323. }
  324. $annotations = $this->getAnnotations();
  325. if (isset($annotations['class']['group']) && in_array('DB', $annotations['class']['group'])) {
  326. return true;
  327. }
  328. return false;
  329. }
  330. }