testcase.php 9.5 KB

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