123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610 |
- <?php
- namespace Test;
- use DOMDocument;
- use DOMNode;
- use OC\Command\QueueBus;
- use OC\Files\Config\MountProviderCollection;
- use OC\Files\Filesystem;
- use OC\Files\Mount\CacheMountProvider;
- use OC\Files\Mount\LocalHomeMountProvider;
- use OC\Files\Mount\RootMountProvider;
- use OC\Files\SetupManager;
- use OC\Template\Base;
- use OCP\Command\IBus;
- use OCP\DB\QueryBuilder\IQueryBuilder;
- use OCP\Defaults;
- use OCP\IConfig;
- use OCP\IDBConnection;
- use OCP\IL10N;
- use OCP\Lock\ILockingProvider;
- use OCP\Security\ISecureRandom;
- use Psr\Log\LoggerInterface;
- if (version_compare(\PHPUnit\Runner\Version::id(), 10, '>=')) {
- trait OnNotSuccessfulTestTrait {
- protected function onNotSuccessfulTest(\Throwable $t): never {
- $this->restoreAllServices();
-
- if (!$this->IsDatabaseAccessAllowed()) {
- \OC::$server->registerService(IDBConnection::class, function () {
- return self::$realDatabase;
- });
- }
- parent::onNotSuccessfulTest($t);
- }
- }
- } else {
- trait OnNotSuccessfulTestTrait {
- protected function onNotSuccessfulTest(\Throwable $t): void {
- $this->restoreAllServices();
-
- if (!$this->IsDatabaseAccessAllowed()) {
- \OC::$server->registerService(IDBConnection::class, function () {
- return self::$realDatabase;
- });
- }
- parent::onNotSuccessfulTest($t);
- }
- }
- }
- abstract class TestCase extends \PHPUnit\Framework\TestCase {
-
- private $commandBus;
-
- protected static $realDatabase = null;
-
- private static $wasDatabaseAllowed = false;
-
- protected $services = [];
- use OnNotSuccessfulTestTrait;
-
- public function overwriteService(string $name, $newService): bool {
- if (isset($this->services[$name])) {
- return false;
- }
- $this->services[$name] = \OC::$server->query($name);
- $container = \OC::$server->getAppContainerForService($name);
- $container = $container ?? \OC::$server;
- $container->registerService($name, function () use ($newService) {
- return $newService;
- });
- return true;
- }
-
- public function restoreService(string $name): bool {
- if (isset($this->services[$name])) {
- $oldService = $this->services[$name];
- $container = \OC::$server->getAppContainerForService($name);
- $container = $container ?? \OC::$server;
- $container->registerService($name, function () use ($oldService) {
- return $oldService;
- });
- unset($this->services[$name]);
- return true;
- }
- return false;
- }
- public function restoreAllServices() {
- if (!empty($this->services)) {
- if (!empty($this->services)) {
- foreach ($this->services as $name => $service) {
- $this->restoreService($name);
- }
- }
- }
- }
- protected function getTestTraits() {
- $traits = [];
- $class = $this;
- do {
- $traits = array_merge(class_uses($class), $traits);
- } while ($class = get_parent_class($class));
- foreach ($traits as $trait => $same) {
- $traits = array_merge(class_uses($trait), $traits);
- }
- $traits = array_unique($traits);
- return array_filter($traits, function ($trait) {
- return substr($trait, 0, 5) === 'Test\\';
- });
- }
- protected function setUp(): void {
-
- $this->commandBus = new QueueBus();
- $this->overwriteService('AsyncCommandBus', $this->commandBus);
- $this->overwriteService(IBus::class, $this->commandBus);
-
- self::$wasDatabaseAllowed = true;
- if (!$this->IsDatabaseAccessAllowed()) {
- self::$wasDatabaseAllowed = false;
- if (is_null(self::$realDatabase)) {
- self::$realDatabase = \OC::$server->getDatabaseConnection();
- }
- \OC::$server->registerService(IDBConnection::class, function () {
- $this->fail('Your test case is not allowed to access the database.');
- });
- }
- $traits = $this->getTestTraits();
- foreach ($traits as $trait) {
- $methodName = 'setUp' . basename(str_replace('\\', '/', $trait));
- if (method_exists($this, $methodName)) {
- call_user_func([$this, $methodName]);
- }
- }
- }
- protected function tearDown(): void {
- $this->restoreAllServices();
-
- if (!$this->IsDatabaseAccessAllowed()) {
- \OC::$server->registerService(IDBConnection::class, function () {
- return self::$realDatabase;
- });
- }
-
- $hookExceptions = \OC_Hook::$thrownExceptions;
- \OC_Hook::$thrownExceptions = [];
- \OC::$server->get(ILockingProvider::class)->releaseAll();
- if (!empty($hookExceptions)) {
- throw $hookExceptions[0];
- }
-
- $errors = libxml_get_errors();
- libxml_clear_errors();
- if (!empty($errors)) {
- self::assertEquals([], $errors, 'There have been xml parsing errors');
- }
- if ($this->IsDatabaseAccessAllowed()) {
- \OC\Files\Cache\Storage::getGlobalCache()->clearCache();
- }
-
- $traits = $this->getTestTraits();
- foreach ($traits as $trait) {
- $methodName = 'tearDown' . basename(str_replace('\\', '/', $trait));
- if (method_exists($this, $methodName)) {
- call_user_func([$this, $methodName]);
- }
- }
- }
-
- protected static function invokePrivate($object, $methodName, array $parameters = []) {
- if (is_string($object)) {
- $className = $object;
- } else {
- $className = get_class($object);
- }
- $reflection = new \ReflectionClass($className);
- if ($reflection->hasMethod($methodName)) {
- $method = $reflection->getMethod($methodName);
- $method->setAccessible(true);
- return $method->invokeArgs($object, $parameters);
- } elseif ($reflection->hasProperty($methodName)) {
- $property = $reflection->getProperty($methodName);
- $property->setAccessible(true);
- if (!empty($parameters)) {
- if ($property->isStatic()) {
- $property->setValue(null, array_pop($parameters));
- } else {
- $property->setValue($object, array_pop($parameters));
- }
- }
- if (is_object($object)) {
- return $property->getValue($object);
- }
- return $property->getValue();
- } elseif ($reflection->hasConstant($methodName)) {
- return $reflection->getConstant($methodName);
- }
- return false;
- }
-
- protected static function getUniqueID($prefix = '', $length = 13) {
- return $prefix . \OC::$server->get(ISecureRandom::class)->generate(
- $length,
-
- ISecureRandom::CHAR_DIGITS . ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_UPPER
- );
- }
-
- public function filterClassMethods(string $className, array $filterMethods): array {
- $class = new \ReflectionClass($className);
- $methods = [];
- foreach ($class->getMethods() as $method) {
- if (($method->isPublic() || $method->isAbstract()) && !in_array($method->getName(), $filterMethods, true)) {
- $methods[] = $method->getName();
- }
- }
- return $methods;
- }
- public static function tearDownAfterClass(): void {
- if (!self::$wasDatabaseAllowed && self::$realDatabase !== null) {
-
-
- \OC::$server->registerService(IDBConnection::class, function () {
- return self::$realDatabase;
- });
- }
- $dataDir = \OC::$server->getConfig()->getSystemValueString('datadirectory', \OC::$SERVERROOT . '/data-autotest');
- if (self::$wasDatabaseAllowed && \OC::$server->getDatabaseConnection()) {
- $db = \OC::$server->getDatabaseConnection();
- if ($db->inTransaction()) {
- $db->rollBack();
- throw new \Exception('There was a transaction still in progress and needed to be rolled back. Please fix this in your test.');
- }
- $queryBuilder = $db->getQueryBuilder();
- self::tearDownAfterClassCleanShares($queryBuilder);
- self::tearDownAfterClassCleanStorages($queryBuilder);
- self::tearDownAfterClassCleanFileCache($queryBuilder);
- }
- self::tearDownAfterClassCleanStrayDataFiles($dataDir);
- self::tearDownAfterClassCleanStrayHooks();
- self::tearDownAfterClassCleanStrayLocks();
-
- $setupManager = \OC::$server->get(SetupManager::class);
- $setupManager->tearDown();
-
- $mountProviderCollection = \OC::$server->get(MountProviderCollection::class);
- $mountProviderCollection->clearProviders();
-
- $config = \OC::$server->get(IConfig::class);
- $mountProviderCollection->registerProvider(new CacheMountProvider($config));
- $mountProviderCollection->registerHomeProvider(new LocalHomeMountProvider());
- $mountProviderCollection->registerRootProvider(new RootMountProvider($config, \OC::$server->get(LoggerInterface::class)));
- $setupManager->setupRoot();
- parent::tearDownAfterClass();
- }
-
- protected static function tearDownAfterClassCleanShares(IQueryBuilder $queryBuilder) {
- $queryBuilder->delete('share')
- ->execute();
- }
-
- protected static function tearDownAfterClassCleanStorages(IQueryBuilder $queryBuilder) {
- $queryBuilder->delete('storages')
- ->execute();
- }
-
- protected static function tearDownAfterClassCleanFileCache(IQueryBuilder $queryBuilder) {
- $queryBuilder->delete('filecache')
- ->runAcrossAllShards()
- ->execute();
- }
-
- protected static function tearDownAfterClassCleanStrayDataFiles($dataDir) {
- $knownEntries = [
- 'nextcloud.log' => true,
- 'audit.log' => true,
- 'owncloud.db' => true,
- '.ocdata' => true,
- '..' => true,
- '.' => true,
- ];
- if ($dh = opendir($dataDir)) {
- while (($file = readdir($dh)) !== false) {
- if (!isset($knownEntries[$file])) {
- self::tearDownAfterClassCleanStrayDataUnlinkDir($dataDir . '/' . $file);
- }
- }
- closedir($dh);
- }
- }
-
- protected static function tearDownAfterClassCleanStrayDataUnlinkDir($dir) {
- if ($dh = @opendir($dir)) {
- while (($file = readdir($dh)) !== false) {
- if (\OC\Files\Filesystem::isIgnoredDir($file)) {
- continue;
- }
- $path = $dir . '/' . $file;
- if (is_dir($path)) {
- self::tearDownAfterClassCleanStrayDataUnlinkDir($path);
- } else {
- @unlink($path);
- }
- }
- closedir($dh);
- }
- @rmdir($dir);
- }
-
- protected static function tearDownAfterClassCleanStrayHooks() {
- \OC_Hook::clear();
- }
-
- protected static function tearDownAfterClassCleanStrayLocks() {
- \OC::$server->get(ILockingProvider::class)->releaseAll();
- }
-
- protected static function loginAsUser($user = '') {
- self::logout();
- \OC\Files\Filesystem::tearDown();
- \OC_User::setUserId($user);
- $userObject = \OC::$server->getUserManager()->get($user);
- if (!is_null($userObject)) {
- $userObject->updateLastLoginTimestamp();
- }
- \OC_Util::setupFS($user);
- if (\OC::$server->getUserManager()->userExists($user)) {
- \OC::$server->getUserFolder($user);
- }
- }
-
- protected static function logout() {
- \OC_Util::tearDownFS();
- \OC_User::setUserId('');
-
- \OC::$server->getUserSession()->setUser(null);
- }
-
- protected function runCommands() {
-
- $view = Filesystem::getView();
- if ($view) {
- [, $user] = explode('/', $view->getRoot());
- } else {
- $user = null;
- }
- \OC_Util::tearDownFS();
- $this->commandBus->run();
- \OC_Util::tearDownFS();
- if ($user) {
- \OC_Util::setupFS($user);
- }
- }
-
- protected function isFileLocked($view, $path, $type, $onMountPoint = false) {
-
-
-
- if ($type === \OCP\Lock\ILockingProvider::LOCK_SHARED) {
-
- $checkType = \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE;
- } else {
-
- $checkType = \OCP\Lock\ILockingProvider::LOCK_SHARED;
- }
- try {
- $view->lockFile($path, $checkType, $onMountPoint);
-
-
- $view->unlockFile($path, $checkType, $onMountPoint);
- return false;
- } catch (\OCP\Lock\LockedException $e) {
-
-
- return true;
- }
- }
- protected function getGroupAnnotations(): array {
- if (method_exists($this, 'getAnnotations')) {
- $annotations = $this->getAnnotations();
- return $annotations['class']['group'] ?? [];
- }
- $r = new \ReflectionClass($this);
- $doc = $r->getDocComment();
- preg_match_all('#@group\s+(.*?)\n#s', $doc, $annotations);
- return $annotations[1] ?? [];
- }
- protected function IsDatabaseAccessAllowed() {
- $annotations = $this->getGroupAnnotations();
- if (isset($annotations)) {
- if (in_array('DB', $annotations) || in_array('SLOWDB', $annotations)) {
- return true;
- }
- }
- return false;
- }
-
- protected function assertTemplate($expectedHtml, $template, $vars = []) {
- require_once __DIR__ . '/../../lib/private/legacy/template/functions.php';
- $requestToken = 12345;
-
- $theme = $this->getMockBuilder('\OCP\Defaults')
- ->disableOriginalConstructor()->getMock();
- $theme->expects($this->any())
- ->method('getName')
- ->willReturn('Nextcloud');
-
- $l10n = $this->getMockBuilder(IL10N::class)
- ->disableOriginalConstructor()->getMock();
- $l10n
- ->expects($this->any())
- ->method('t')
- ->willReturnCallback(function ($text, $parameters = []) {
- return vsprintf($text, $parameters);
- });
- $t = new Base($template, $requestToken, $l10n, $theme);
- $buf = $t->fetchPage($vars);
- $this->assertHtmlStringEqualsHtmlString($expectedHtml, $buf);
- }
-
- protected function assertHtmlStringEqualsHtmlString($expectedHtml, $actualHtml, $message = '') {
- $expected = new DOMDocument();
- $expected->preserveWhiteSpace = false;
- $expected->formatOutput = true;
- $expected->loadHTML($expectedHtml);
- $actual = new DOMDocument();
- $actual->preserveWhiteSpace = false;
- $actual->formatOutput = true;
- $actual->loadHTML($actualHtml);
- $this->removeWhitespaces($actual);
- $expectedHtml1 = $expected->saveHTML();
- $actualHtml1 = $actual->saveHTML();
- self::assertEquals($expectedHtml1, $actualHtml1, $message);
- }
- private function removeWhitespaces(DOMNode $domNode) {
- foreach ($domNode->childNodes as $node) {
- if ($node->hasChildNodes()) {
- $this->removeWhitespaces($node);
- } else {
- if ($node instanceof \DOMText && $node->isWhitespaceInElementContent()) {
- $domNode->removeChild($node);
- }
- }
- }
- }
- }
|