1
0

testcase.php 11 KB

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