diff options
Diffstat (limited to 'tests/lib')
237 files changed, 1874 insertions, 1533 deletions
diff --git a/tests/lib/Accounts/AccountManagerTest.php b/tests/lib/Accounts/AccountManagerTest.php index 05c7efd08fb..6e2f30a2c26 100644 --- a/tests/lib/Accounts/AccountManagerTest.php +++ b/tests/lib/Accounts/AccountManagerTest.php @@ -29,6 +29,7 @@ use OCP\L10N\IFactory; use OCP\Mail\IMailer; use OCP\Security\ICrypto; use OCP\Security\VerificationToken\IVerificationToken; +use OCP\Server; use PHPUnit\Framework\MockObject\MockObject; use Psr\Log\LoggerInterface; use Test\TestCase; @@ -61,7 +62,7 @@ class AccountManagerTest extends TestCase { protected function setUp(): void { parent::setUp(); - $this->connection = \OCP\Server::get(IDBConnection::class); + $this->connection = Server::get(IDBConnection::class); $this->phoneNumberUtil = new PhoneNumberUtil(); $this->eventDispatcher = $this->createMock(IEventDispatcher::class); @@ -488,7 +489,7 @@ class AccountManagerTest extends TestCase { } else { $this->eventDispatcher->expects($this->once())->method('dispatchTyped') ->willReturnCallback( - function ($event) use ($user, $newData) { + function ($event) use ($user, $newData): void { $this->assertInstanceOf(UserUpdatedEvent::class, $event); $this->assertSame($user, $event->getUser()); $this->assertSame($newData, $event->getData()); diff --git a/tests/lib/Activity/ManagerTest.php b/tests/lib/Activity/ManagerTest.php index f42a38eab53..e895991bac7 100644 --- a/tests/lib/Activity/ManagerTest.php +++ b/tests/lib/Activity/ManagerTest.php @@ -9,6 +9,8 @@ namespace Test\Activity; use OCP\Activity\Exceptions\IncompleteActivityException; +use OCP\Activity\IConsumer; +use OCP\Activity\IEvent; use OCP\IConfig; use OCP\IL10N; use OCP\IRequest; @@ -228,7 +230,7 @@ class ManagerTest extends TestCase { $consumer->expects($this->once()) ->method('receive') ->with($event) - ->willReturnCallback(function (\OCP\Activity\IEvent $event) use ($expected) { + ->willReturnCallback(function (IEvent $event) use ($expected): void { $this->assertLessThanOrEqual(time() + 2, $event->getTimestamp(), 'Timestamp not set correctly'); $this->assertGreaterThanOrEqual(time() - 2, $event->getTimestamp(), 'Timestamp not set correctly'); $this->assertSame($expected, $event->getAuthor(), 'Author name not set correctly'); @@ -258,7 +260,7 @@ class ManagerTest extends TestCase { ->getMock(); $consumer->expects($this->once()) ->method('receive') - ->willReturnCallback(function (\OCP\Activity\IEvent $event) { + ->willReturnCallback(function (IEvent $event): void { $this->assertSame('test_app', $event->getApp(), 'App not set correctly'); $this->assertSame('test_type', $event->getType(), 'Type not set correctly'); $this->assertSame('test_affected', $event->getAffectedUser(), 'Affected user not set correctly'); @@ -281,7 +283,7 @@ class ManagerTest extends TestCase { } } -class NoOpConsumer implements \OCP\Activity\IConsumer { - public function receive(\OCP\Activity\IEvent $event) { +class NoOpConsumer implements IConsumer { + public function receive(IEvent $event) { } } diff --git a/tests/lib/AllConfigTest.php b/tests/lib/AllConfigTest.php index b4137c07ac5..ba48a078713 100644 --- a/tests/lib/AllConfigTest.php +++ b/tests/lib/AllConfigTest.php @@ -14,9 +14,11 @@ namespace Test; * * @package Test */ - +use OC\AllConfig; use OC\SystemConfig; use OCP\IDBConnection; +use OCP\PreConditionNotMetException; +use OCP\Server; class AllConfigTest extends \Test\TestCase { /** @var \OCP\IDBConnection */ @@ -24,7 +26,7 @@ class AllConfigTest extends \Test\TestCase { protected function getConfig($systemConfig = null, $connection = null) { if ($this->connection === null) { - $this->connection = \OC::$server->getDatabaseConnection(); + $this->connection = Server::get(IDBConnection::class); } if ($connection === null) { $connection = $this->connection; @@ -34,7 +36,7 @@ class AllConfigTest extends \Test\TestCase { ->disableOriginalConstructor() ->getMock(); } - return new \OC\AllConfig($systemConfig, $connection); + return new AllConfig($systemConfig, $connection); } public function testDeleteUserValue(): void { @@ -147,7 +149,7 @@ class AllConfigTest extends \Test\TestCase { public function testSetUserValueWithPreConditionFailure(): void { - $this->expectException(\OCP\PreConditionNotMetException::class); + $this->expectException(PreConditionNotMetException::class); $config = $this->getConfig(); @@ -183,7 +185,7 @@ class AllConfigTest extends \Test\TestCase { } public function testSetUserValueWithPreConditionFailureWhenResultStillMatches(): void { - $this->expectException(\OCP\PreConditionNotMetException::class); + $this->expectException(PreConditionNotMetException::class); $config = $this->getConfig(); diff --git a/tests/lib/App/AppManagerTest.php b/tests/lib/App/AppManagerTest.php index 48d722761bc..3dd5073731c 100644 --- a/tests/lib/App/AppManagerTest.php +++ b/tests/lib/App/AppManagerTest.php @@ -50,7 +50,7 @@ class AppManagerTest extends TestCase { }); $config->expects($this->any()) ->method('setValue') - ->willReturnCallback(function ($app, $key, $value) use (&$appConfig) { + ->willReturnCallback(function ($app, $key, $value) use (&$appConfig): void { if (!isset($appConfig[$app])) { $appConfig[$app] = []; } @@ -171,7 +171,7 @@ class AppManagerTest extends TestCase { } public static function dataGetAppIcon(): array { - $nothing = function ($appId) { + $nothing = function ($appId): void { self::assertEquals('test', $appId); throw new \RuntimeException(); }; diff --git a/tests/lib/App/PlatformRepositoryTest.php b/tests/lib/App/PlatformRepositoryTest.php index 8f621eebce9..01d49d84832 100644 --- a/tests/lib/App/PlatformRepositoryTest.php +++ b/tests/lib/App/PlatformRepositoryTest.php @@ -6,7 +6,7 @@ */ namespace Test\App; -use OC; +use OC\App\PlatformRepository; class PlatformRepositoryTest extends \Test\TestCase { /** @@ -15,7 +15,7 @@ class PlatformRepositoryTest extends \Test\TestCase { * @param $input */ public function testVersion($input, $expected): void { - $pr = new OC\App\PlatformRepository(); + $pr = new PlatformRepository(); $normalizedVersion = $pr->normalizeVersion($input); $this->assertEquals($expected, $normalizedVersion); } diff --git a/tests/lib/AppConfigTest.php b/tests/lib/AppConfigTest.php index 4acb83ece14..b7878c42c83 100644 --- a/tests/lib/AppConfigTest.php +++ b/tests/lib/AppConfigTest.php @@ -14,6 +14,7 @@ use OCP\Exceptions\AppConfigUnknownKeyException; use OCP\IAppConfig; use OCP\IDBConnection; use OCP\Security\ICrypto; +use OCP\Server; use Psr\Log\LoggerInterface; /** @@ -87,9 +88,9 @@ class AppConfigTest extends TestCase { protected function setUp(): void { parent::setUp(); - $this->connection = \OCP\Server::get(IDBConnection::class); - $this->logger = \OCP\Server::get(LoggerInterface::class); - $this->crypto = \OCP\Server::get(ICrypto::class); + $this->connection = Server::get(IDBConnection::class); + $this->logger = Server::get(LoggerInterface::class); + $this->crypto = Server::get(ICrypto::class); // storing current config and emptying the data table $sql = $this->connection->getQueryBuilder(); @@ -176,7 +177,7 @@ class AppConfigTest extends TestCase { */ private function generateAppConfig(bool $preLoading = true): IAppConfig { /** @var AppConfig $config */ - $config = new \OC\AppConfig( + $config = new AppConfig( $this->connection, $this->logger, $this->crypto, diff --git a/tests/lib/AppFramework/AppTest.php b/tests/lib/AppFramework/AppTest.php index 87c96fdb9a8..b44ddd6082b 100644 --- a/tests/lib/AppFramework/AppTest.php +++ b/tests/lib/AppFramework/AppTest.php @@ -9,9 +9,10 @@ namespace Test\AppFramework; use OC\AppFramework\App; +use OC\AppFramework\DependencyInjection\DIContainer; use OC\AppFramework\Http\Dispatcher; use OCP\AppFramework\Controller; -use OCP\AppFramework\Http; +use OCP\AppFramework\Http\IOutput; use OCP\AppFramework\Http\Response; function rrmdir($directory) { @@ -43,10 +44,10 @@ class AppTest extends \Test\TestCase { protected function setUp(): void { parent::setUp(); - $this->container = new \OC\AppFramework\DependencyInjection\DIContainer('test', []); + $this->container = new DIContainer('test', []); $this->controller = $this->createMock(Controller::class); $this->dispatcher = $this->createMock(Dispatcher::class); - $this->io = $this->createMock(Http\IOutput::class); + $this->io = $this->createMock(IOutput::class); $this->headers = ['key' => 'value']; $this->output = 'hi'; diff --git a/tests/lib/AppFramework/Bootstrap/CoordinatorTest.php b/tests/lib/AppFramework/Bootstrap/CoordinatorTest.php index 05e7a1b71c7..0eeddb2173a 100644 --- a/tests/lib/AppFramework/Bootstrap/CoordinatorTest.php +++ b/tests/lib/AppFramework/Bootstrap/CoordinatorTest.php @@ -11,6 +11,7 @@ namespace lib\AppFramework\Bootstrap; use OC\AppFramework\Bootstrap\Coordinator; use OC\Support\CrashReport\Registry; +use OCA\Settings\AppInfo\Application; use OCP\App\IAppManager; use OCP\AppFramework\App; use OCP\AppFramework\Bootstrap\IBootContext; @@ -76,7 +77,7 @@ class CoordinatorTest extends TestCase { $appId = 'settings'; $this->serverContainer->expects($this->once()) ->method('query') - ->with(\OCA\Settings\AppInfo\Application::class) + ->with(Application::class) ->willThrowException(new QueryException('')); $this->logger->expects($this->once()) ->method('error'); @@ -86,10 +87,10 @@ class CoordinatorTest extends TestCase { public function testBootAppNotBootable(): void { $appId = 'settings'; - $mockApp = $this->createMock(\OCA\Settings\AppInfo\Application::class); + $mockApp = $this->createMock(Application::class); $this->serverContainer->expects($this->once()) ->method('query') - ->with(\OCA\Settings\AppInfo\Application::class) + ->with(Application::class) ->willReturn($mockApp); $this->coordinator->bootApp($appId); @@ -110,7 +111,7 @@ class CoordinatorTest extends TestCase { }; $this->serverContainer->expects($this->once()) ->method('query') - ->with(\OCA\Settings\AppInfo\Application::class) + ->with(Application::class) ->willReturn($mockApp); $this->coordinator->bootApp($appId); diff --git a/tests/lib/AppFramework/Bootstrap/FunctionInjectorTest.php b/tests/lib/AppFramework/Bootstrap/FunctionInjectorTest.php index c32331e8ba1..8f6944ce34f 100644 --- a/tests/lib/AppFramework/Bootstrap/FunctionInjectorTest.php +++ b/tests/lib/AppFramework/Bootstrap/FunctionInjectorTest.php @@ -11,6 +11,7 @@ namespace lib\AppFramework\Bootstrap; use OC\AppFramework\Bootstrap\FunctionInjector; use OC\AppFramework\Utility\SimpleContainer; +use OCP\AppFramework\QueryException; use Test\TestCase; interface Foo { @@ -27,7 +28,7 @@ class FunctionInjectorTest extends TestCase { } public function testInjectFnNotRegistered(): void { - $this->expectException(\OCP\AppFramework\QueryException::class); + $this->expectException(QueryException::class); (new FunctionInjector($this->container))->injectFn(static function (Foo $p1): void { }); diff --git a/tests/lib/AppFramework/Controller/PublicShareControllerTest.php b/tests/lib/AppFramework/Controller/PublicShareControllerTest.php index 6f0e433f2fb..97216845617 100644 --- a/tests/lib/AppFramework/Controller/PublicShareControllerTest.php +++ b/tests/lib/AppFramework/Controller/PublicShareControllerTest.php @@ -11,17 +11,14 @@ use OCP\IRequest; use OCP\ISession; class TestController extends PublicShareController { - /** @var string */ - private $hash; - - /** @var bool */ - private $isProtected; - - public function __construct(string $appName, IRequest $request, ISession $session, string $hash, bool $isProtected) { + public function __construct( + string $appName, + IRequest $request, + ISession $session, + private string $hash, + private bool $isProtected, + ) { parent::__construct($appName, $request, $session); - - $this->hash = $hash; - $this->isProtected = $isProtected; } protected function getPasswordHash(): string { diff --git a/tests/lib/AppFramework/Db/EntityTest.php b/tests/lib/AppFramework/Db/EntityTest.php index ccd0ae4bbaf..4fcf126e3b1 100644 --- a/tests/lib/AppFramework/Db/EntityTest.php +++ b/tests/lib/AppFramework/Db/EntityTest.php @@ -36,7 +36,6 @@ use PHPUnit\Framework\Constraint\IsType; * @method void setDatetime(\DateTimeImmutable $datetime) */ class TestEntity extends Entity { - protected $name; protected $email; protected $testId; protected $smallInt; @@ -49,7 +48,9 @@ class TestEntity extends Entity { protected $time; protected $datetime; - public function __construct($name = null) { + public function __construct( + protected $name = null, + ) { $this->addType('testId', Types::INTEGER); $this->addType('smallInt', Types::SMALLINT); $this->addType('bigInt', Types::BIGINT); @@ -63,8 +64,6 @@ class TestEntity extends Entity { $this->addType('trueOrFalse', 'bool'); $this->addType('legacyInt', 'int'); $this->addType('doubleNowFloat', 'double'); - - $this->name = $name; } public function setAnotherBool(bool $anotherBool): void { diff --git a/tests/lib/AppFramework/Db/QBMapperDBTest.php b/tests/lib/AppFramework/Db/QBMapperDBTest.php index 72bc2d956d6..a61240fcb82 100644 --- a/tests/lib/AppFramework/Db/QBMapperDBTest.php +++ b/tests/lib/AppFramework/Db/QBMapperDBTest.php @@ -70,7 +70,7 @@ class QBMapperDBTest extends TestCase { protected function setUp(): void { parent::setUp(); - $this->connection = \OCP\Server::get(IDBConnection::class); + $this->connection = Server::get(IDBConnection::class); $this->prepareTestingTable(); } diff --git a/tests/lib/AppFramework/Db/QBMapperTest.php b/tests/lib/AppFramework/Db/QBMapperTest.php index c1d8bf07234..1fac6632b30 100644 --- a/tests/lib/AppFramework/Db/QBMapperTest.php +++ b/tests/lib/AppFramework/Db/QBMapperTest.php @@ -127,7 +127,7 @@ class QBMapperTest extends \Test\TestCase { ]; $this->qb->expects($this->exactly(6)) ->method('createNamedParameter') - ->willReturnCallback(function () use (&$createNamedParameterCalls) { + ->willReturnCallback(function () use (&$createNamedParameterCalls): void { $expected = array_shift($createNamedParameterCalls); $this->assertEquals($expected, func_get_args()); }); @@ -142,7 +142,7 @@ class QBMapperTest extends \Test\TestCase { ]; $this->qb->expects($this->exactly(6)) ->method('setValue') - ->willReturnCallback(function () use (&$setValueCalls) { + ->willReturnCallback(function () use (&$setValueCalls): void { $expected = array_shift($setValueCalls); $this->assertEquals($expected, func_get_args()); }); @@ -184,7 +184,7 @@ class QBMapperTest extends \Test\TestCase { ]; $this->qb->expects($this->exactly(8)) ->method('createNamedParameter') - ->willReturnCallback(function () use (&$createNamedParameterCalls) { + ->willReturnCallback(function () use (&$createNamedParameterCalls): void { $expected = array_shift($createNamedParameterCalls); $this->assertEquals($expected, func_get_args()); }); @@ -200,7 +200,7 @@ class QBMapperTest extends \Test\TestCase { ]; $this->qb->expects($this->exactly(7)) ->method('set') - ->willReturnCallback(function () use (&$setCalls) { + ->willReturnCallback(function () use (&$setCalls): void { $expected = array_shift($setCalls); $this->assertEquals($expected, func_get_args()); }); diff --git a/tests/lib/AppFramework/Db/TransactionalTest.php b/tests/lib/AppFramework/Db/TransactionalTest.php index a60c4386fea..bf8abcd7aa2 100644 --- a/tests/lib/AppFramework/Db/TransactionalTest.php +++ b/tests/lib/AppFramework/Db/TransactionalTest.php @@ -35,7 +35,7 @@ class TransactionalTest extends TestCase { } public function fail(): void { - $this->atomic(function () { + $this->atomic(function (): void { throw new RuntimeException('nope'); }, $this->db); } diff --git a/tests/lib/AppFramework/DependencyInjection/DIIntergrationTests.php b/tests/lib/AppFramework/DependencyInjection/DIIntergrationTests.php index 54c691d2392..8f0e60c5b3b 100644 --- a/tests/lib/AppFramework/DependencyInjection/DIIntergrationTests.php +++ b/tests/lib/AppFramework/DependencyInjection/DIIntergrationTests.php @@ -21,16 +21,14 @@ class ClassA2 implements Interface1 { } class ClassB { - /** @var Interface1 */ - public $interface1; - /** * ClassB constructor. * * @param Interface1 $interface1 */ - public function __construct(Interface1 $interface1) { - $this->interface1 = $interface1; + public function __construct( + public Interface1 $interface1, + ) { } } diff --git a/tests/lib/AppFramework/Http/DataResponseTest.php b/tests/lib/AppFramework/Http/DataResponseTest.php index 7ae19e7d5d8..e9a2c511140 100644 --- a/tests/lib/AppFramework/Http/DataResponseTest.php +++ b/tests/lib/AppFramework/Http/DataResponseTest.php @@ -11,6 +11,7 @@ namespace Test\AppFramework\Http; use OCP\AppFramework\Http; use OCP\AppFramework\Http\DataResponse; use OCP\IRequest; +use OCP\Server; class DataResponseTest extends \Test\TestCase { /** @@ -53,7 +54,7 @@ class DataResponseTest extends \Test\TestCase { 'Content-Security-Policy' => "default-src 'none';base-uri 'none';manifest-src 'self';frame-ancestors 'none'", 'Feature-Policy' => "autoplay 'none';camera 'none';fullscreen 'none';geolocation 'none';microphone 'none';payment 'none'", 'X-Robots-Tag' => 'noindex, nofollow', - 'X-Request-Id' => \OC::$server->get(IRequest::class)->getId(), + 'X-Request-Id' => Server::get(IRequest::class)->getId(), ]; $expectedHeaders = array_merge($expectedHeaders, $headers); diff --git a/tests/lib/AppFramework/Http/DispatcherTest.php b/tests/lib/AppFramework/Http/DispatcherTest.php index 404d3f4c90b..4ed6627891c 100644 --- a/tests/lib/AppFramework/Http/DispatcherTest.php +++ b/tests/lib/AppFramework/Http/DispatcherTest.php @@ -24,6 +24,7 @@ use OCP\IConfig; use OCP\IDBConnection; use OCP\IRequest; use OCP\IRequestId; +use OCP\Server; use PHPUnit\Framework\MockObject\MockObject; use Psr\Container\ContainerInterface; use Psr\Log\LoggerInterface; @@ -130,7 +131,7 @@ class DispatcherTest extends \Test\TestCase { $this->reflector, $this->request, $this->config, - \OCP\Server::get(IDBConnection::class), + Server::get(IDBConnection::class), $this->logger, $this->eventLogger, $this->container, @@ -156,7 +157,7 @@ class DispatcherTest extends \Test\TestCase { ->method('beforeController') ->with($this->equalTo($this->controller), $this->equalTo($this->controllerMethod)) - ->will($this->throwException($exception)); + ->willThrowException($exception); if ($catchEx) { $this->middlewareDispatcher->expects($this->once()) ->method('afterException') @@ -307,7 +308,7 @@ class DispatcherTest extends \Test\TestCase { $this->http, $this->middlewareDispatcher, $this->reflector, $this->request, $this->config, - \OC::$server->getDatabaseConnection(), + Server::get(IDBConnection::class), $this->logger, $this->eventLogger, $this->container @@ -340,7 +341,7 @@ class DispatcherTest extends \Test\TestCase { $this->http, $this->middlewareDispatcher, $this->reflector, $this->request, $this->config, - \OC::$server->getDatabaseConnection(), + Server::get(IDBConnection::class), $this->logger, $this->eventLogger, $this->container @@ -376,7 +377,7 @@ class DispatcherTest extends \Test\TestCase { $this->http, $this->middlewareDispatcher, $this->reflector, $this->request, $this->config, - \OC::$server->getDatabaseConnection(), + Server::get(IDBConnection::class), $this->logger, $this->eventLogger, $this->container @@ -411,7 +412,7 @@ class DispatcherTest extends \Test\TestCase { $this->http, $this->middlewareDispatcher, $this->reflector, $this->request, $this->config, - \OC::$server->getDatabaseConnection(), + Server::get(IDBConnection::class), $this->logger, $this->eventLogger, $this->container @@ -447,7 +448,7 @@ class DispatcherTest extends \Test\TestCase { $this->http, $this->middlewareDispatcher, $this->reflector, $this->request, $this->config, - \OC::$server->getDatabaseConnection(), + Server::get(IDBConnection::class), $this->logger, $this->eventLogger, $this->container @@ -482,7 +483,7 @@ class DispatcherTest extends \Test\TestCase { $this->http, $this->middlewareDispatcher, $this->reflector, $this->request, $this->config, - \OC::$server->getDatabaseConnection(), + Server::get(IDBConnection::class), $this->logger, $this->eventLogger, $this->container @@ -520,7 +521,7 @@ class DispatcherTest extends \Test\TestCase { $this->http, $this->middlewareDispatcher, $this->reflector, $this->request, $this->config, - \OC::$server->getDatabaseConnection(), + Server::get(IDBConnection::class), $this->logger, $this->eventLogger, $this->container @@ -564,7 +565,7 @@ class DispatcherTest extends \Test\TestCase { $this->reflector, $this->request, $this->config, - \OC::$server->getDatabaseConnection(), + Server::get(IDBConnection::class), $this->logger, $this->eventLogger, $this->container, diff --git a/tests/lib/AppFramework/Http/PublicTemplateResponseTest.php b/tests/lib/AppFramework/Http/PublicTemplateResponseTest.php index d963705bc24..cb7bd97f5da 100644 --- a/tests/lib/AppFramework/Http/PublicTemplateResponseTest.php +++ b/tests/lib/AppFramework/Http/PublicTemplateResponseTest.php @@ -7,8 +7,8 @@ namespace Test\AppFramework\Http; -use OCP\AppFramework\Http; use OCP\AppFramework\Http\Template\PublicTemplateResponse; +use OCP\AppFramework\Http\Template\SimpleMenuAction; use Test\TestCase; class PublicTemplateResponseTest extends TestCase { @@ -28,7 +28,7 @@ class PublicTemplateResponseTest extends TestCase { public function testActionSingle(): void { $actions = [ - new Http\Template\SimpleMenuAction('link', 'Download', 'download', 'downloadLink', 0) + new SimpleMenuAction('link', 'Download', 'download', 'downloadLink', 0) ]; $template = new PublicTemplateResponse('app', 'home', ['key' => 'value']); $template->setHeaderActions($actions); @@ -41,9 +41,9 @@ class PublicTemplateResponseTest extends TestCase { public function testActionMultiple(): void { $actions = [ - new Http\Template\SimpleMenuAction('link1', 'Download1', 'download1', 'downloadLink1', 100), - new Http\Template\SimpleMenuAction('link2', 'Download2', 'download2', 'downloadLink2', 20), - new Http\Template\SimpleMenuAction('link3', 'Download3', 'download3', 'downloadLink3', 0) + new SimpleMenuAction('link1', 'Download1', 'download1', 'downloadLink1', 100), + new SimpleMenuAction('link2', 'Download2', 'download2', 'downloadLink2', 20), + new SimpleMenuAction('link3', 'Download3', 'download3', 'downloadLink3', 0) ]; $template = new PublicTemplateResponse('app', 'home', ['key' => 'value']); $template->setHeaderActions($actions); diff --git a/tests/lib/AppFramework/Http/ResponseTest.php b/tests/lib/AppFramework/Http/ResponseTest.php index c129b5637c5..7750db921c6 100644 --- a/tests/lib/AppFramework/Http/ResponseTest.php +++ b/tests/lib/AppFramework/Http/ResponseTest.php @@ -9,6 +9,8 @@ namespace Test\AppFramework\Http; use OCP\AppFramework\Http; +use OCP\AppFramework\Http\ContentSecurityPolicy; +use OCP\AppFramework\Http\EmptyContentSecurityPolicy; use OCP\AppFramework\Http\Response; use OCP\AppFramework\Utility\ITimeFactory; @@ -54,7 +56,7 @@ class ResponseTest extends \Test\TestCase { $expected = [ 'Content-Security-Policy' => "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self' 'unsafe-inline';style-src 'self' 'unsafe-inline';img-src 'self';font-src 'self' data:;connect-src 'self';media-src 'self'", ]; - $policy = new Http\ContentSecurityPolicy(); + $policy = new ContentSecurityPolicy(); $this->childResponse->setContentSecurityPolicy($policy); $headers = $this->childResponse->getHeaders(); @@ -63,14 +65,14 @@ class ResponseTest extends \Test\TestCase { } public function testGetCsp(): void { - $policy = new Http\ContentSecurityPolicy(); + $policy = new ContentSecurityPolicy(); $this->childResponse->setContentSecurityPolicy($policy); $this->assertEquals($policy, $this->childResponse->getContentSecurityPolicy()); } public function testGetCspEmpty(): void { - $this->assertEquals(new Http\EmptyContentSecurityPolicy(), $this->childResponse->getContentSecurityPolicy()); + $this->assertEquals(new EmptyContentSecurityPolicy(), $this->childResponse->getContentSecurityPolicy()); } public function testAddHeaderValueNullDeletesIt(): void { diff --git a/tests/lib/AppFramework/Middleware/AdditionalScriptsMiddlewareTest.php b/tests/lib/AppFramework/Middleware/AdditionalScriptsMiddlewareTest.php index 22b1b13aaee..4fa5de62b0b 100644 --- a/tests/lib/AppFramework/Middleware/AdditionalScriptsMiddlewareTest.php +++ b/tests/lib/AppFramework/Middleware/AdditionalScriptsMiddlewareTest.php @@ -67,7 +67,7 @@ class AdditionalScriptsMiddlewareTest extends \Test\TestCase { ->method($this->anything()); $this->dispatcher->expects($this->once()) ->method('dispatchTyped') - ->willReturnCallback(function ($event) { + ->willReturnCallback(function ($event): void { if ($event instanceof BeforeTemplateRenderedEvent && $event->isLoggedIn() === false) { return; } @@ -83,7 +83,7 @@ class AdditionalScriptsMiddlewareTest extends \Test\TestCase { ->willReturn(false); $this->dispatcher->expects($this->once()) ->method('dispatchTyped') - ->willReturnCallback(function ($event) { + ->willReturnCallback(function ($event): void { if ($event instanceof BeforeTemplateRenderedEvent && $event->isLoggedIn() === false) { return; } @@ -101,7 +101,7 @@ class AdditionalScriptsMiddlewareTest extends \Test\TestCase { ->willReturn(true); $this->dispatcher->expects($this->once()) ->method('dispatchTyped') - ->willReturnCallback(function ($event) { + ->willReturnCallback(function ($event): void { if ($event instanceof BeforeTemplateRenderedEvent && $event->isLoggedIn() === true) { return; } diff --git a/tests/lib/AppFramework/Middleware/MiddlewareDispatcherTest.php b/tests/lib/AppFramework/Middleware/MiddlewareDispatcherTest.php index a8273be362b..aae1c53456b 100644 --- a/tests/lib/AppFramework/Middleware/MiddlewareDispatcherTest.php +++ b/tests/lib/AppFramework/Middleware/MiddlewareDispatcherTest.php @@ -34,17 +34,16 @@ class TestMiddleware extends Middleware { public $response; public $output; - private $beforeControllerThrowsEx; - /** * @param boolean $beforeControllerThrowsEx */ - public function __construct($beforeControllerThrowsEx) { + public function __construct( + private $beforeControllerThrowsEx, + ) { self::$beforeControllerCalled = 0; self::$afterControllerCalled = 0; self::$afterExceptionCalled = 0; self::$beforeOutputCalled = 0; - $this->beforeControllerThrowsEx = $beforeControllerThrowsEx; } public function beforeController($controller, $methodName) { @@ -136,13 +135,13 @@ class MiddlewareDispatcherTest extends \Test\TestCase { public function testAfterExceptionShouldReturnResponseOfMiddleware(): void { $response = new Response(); - $m1 = $this->getMockBuilder(\OCP\AppFramework\Middleware::class) + $m1 = $this->getMockBuilder(Middleware::class) ->onlyMethods(['afterException', 'beforeController']) ->getMock(); $m1->expects($this->never()) ->method('afterException'); - $m2 = $this->getMockBuilder(\OCP\AppFramework\Middleware::class) + $m2 = $this->getMockBuilder(Middleware::class) ->onlyMethods(['afterException', 'beforeController']) ->getMock(); $m2->expects($this->once()) diff --git a/tests/lib/AppFramework/Middleware/NotModifiedMiddlewareTest.php b/tests/lib/AppFramework/Middleware/NotModifiedMiddlewareTest.php index d80df1841c8..0abbd9c614c 100644 --- a/tests/lib/AppFramework/Middleware/NotModifiedMiddlewareTest.php +++ b/tests/lib/AppFramework/Middleware/NotModifiedMiddlewareTest.php @@ -11,6 +11,7 @@ namespace Test\AppFramework\Middleware; use OC\AppFramework\Middleware\NotModifiedMiddleware; use OCP\AppFramework\Controller; use OCP\AppFramework\Http; +use OCP\AppFramework\Http\Response; use OCP\IRequest; class NotModifiedMiddlewareTest extends \Test\TestCase { @@ -68,7 +69,7 @@ class NotModifiedMiddlewareTest extends \Test\TestCase { return ''; }); - $response = new Http\Response(); + $response = new Response(); if ($etag !== null) { $response->setETag($etag); } diff --git a/tests/lib/AppFramework/Middleware/OCSMiddlewareTest.php b/tests/lib/AppFramework/Middleware/OCSMiddlewareTest.php index 62e20a2dcd0..b22646b8891 100644 --- a/tests/lib/AppFramework/Middleware/OCSMiddlewareTest.php +++ b/tests/lib/AppFramework/Middleware/OCSMiddlewareTest.php @@ -12,6 +12,7 @@ use OC\AppFramework\OCS\V1Response; use OC\AppFramework\OCS\V2Response; use OCP\AppFramework\Controller; use OCP\AppFramework\Http; +use OCP\AppFramework\Http\JSONResponse; use OCP\AppFramework\Http\Response; use OCP\AppFramework\OCS\OCSBadRequestException; use OCP\AppFramework\OCS\OCSException; @@ -82,7 +83,7 @@ class OCSMiddlewareTest extends \Test\TestCase { $this->assertSame($message, $this->invokePrivate($result, 'statusMessage')); if ($exception->getCode() === 0) { - $this->assertSame(\OCP\AppFramework\OCSController::RESPOND_UNKNOWN_ERROR, $result->getOCSStatus()); + $this->assertSame(OCSController::RESPOND_UNKNOWN_ERROR, $result->getOCSStatus()); } else { $this->assertSame($code, $result->getOCSStatus()); } @@ -112,7 +113,7 @@ class OCSMiddlewareTest extends \Test\TestCase { $this->assertSame($message, $this->invokePrivate($result, 'statusMessage')); if ($exception->getCode() === 0) { - $this->assertSame(\OCP\AppFramework\OCSController::RESPOND_UNKNOWN_ERROR, $result->getOCSStatus()); + $this->assertSame(OCSController::RESPOND_UNKNOWN_ERROR, $result->getOCSStatus()); } else { $this->assertSame($code, $result->getOCSStatus()); } @@ -141,7 +142,7 @@ class OCSMiddlewareTest extends \Test\TestCase { $this->assertSame($message, $this->invokePrivate($result, 'statusMessage')); if ($exception->getCode() === 0) { - $this->assertSame(\OCP\AppFramework\OCSController::RESPOND_UNKNOWN_ERROR, $result->getOCSStatus()); + $this->assertSame(OCSController::RESPOND_UNKNOWN_ERROR, $result->getOCSStatus()); } else { $this->assertSame($code, $result->getOCSStatus()); } @@ -151,16 +152,16 @@ class OCSMiddlewareTest extends \Test\TestCase { public static function dataAfterController(): array { return [ [OCSController::class, new Response(), false], - [OCSController::class, new Http\JSONResponse(), false], - [OCSController::class, new Http\JSONResponse(['message' => 'foo']), false], - [OCSController::class, new Http\JSONResponse(['message' => 'foo'], Http::STATUS_UNAUTHORIZED), true, OCSController::RESPOND_UNAUTHORISED], - [OCSController::class, new Http\JSONResponse(['message' => 'foo'], Http::STATUS_FORBIDDEN), true], + [OCSController::class, new JSONResponse(), false], + [OCSController::class, new JSONResponse(['message' => 'foo']), false], + [OCSController::class, new JSONResponse(['message' => 'foo'], Http::STATUS_UNAUTHORIZED), true, OCSController::RESPOND_UNAUTHORISED], + [OCSController::class, new JSONResponse(['message' => 'foo'], Http::STATUS_FORBIDDEN), true], [Controller::class, new Response(), false], - [Controller::class, new Http\JSONResponse(), false], - [Controller::class, new Http\JSONResponse(['message' => 'foo']), false], - [Controller::class, new Http\JSONResponse(['message' => 'foo'], Http::STATUS_UNAUTHORIZED), false], - [Controller::class, new Http\JSONResponse(['message' => 'foo'], Http::STATUS_FORBIDDEN), false], + [Controller::class, new JSONResponse(), false], + [Controller::class, new JSONResponse(['message' => 'foo']), false], + [Controller::class, new JSONResponse(['message' => 'foo'], Http::STATUS_UNAUTHORIZED), false], + [Controller::class, new JSONResponse(['message' => 'foo'], Http::STATUS_FORBIDDEN), false], ]; } diff --git a/tests/lib/AppFramework/Middleware/Security/BruteForceMiddlewareTest.php b/tests/lib/AppFramework/Middleware/Security/BruteForceMiddlewareTest.php index c516c1e6c89..ae575fa947f 100644 --- a/tests/lib/AppFramework/Middleware/Security/BruteForceMiddlewareTest.php +++ b/tests/lib/AppFramework/Middleware/Security/BruteForceMiddlewareTest.php @@ -248,7 +248,7 @@ class BruteForceMiddlewareTest extends TestCase { $this->throttler ->expects($this->exactly(2)) ->method('registerAttempt') - ->willReturnCallback(function () use (&$attemptCalls) { + ->willReturnCallback(function () use (&$attemptCalls): void { $expected = array_shift($attemptCalls); $this->assertEquals($expected, func_get_args()); }); diff --git a/tests/lib/AppFramework/Middleware/Security/CORSMiddlewareTest.php b/tests/lib/AppFramework/Middleware/Security/CORSMiddlewareTest.php index f22933a5884..2132a4d511f 100644 --- a/tests/lib/AppFramework/Middleware/Security/CORSMiddlewareTest.php +++ b/tests/lib/AppFramework/Middleware/Security/CORSMiddlewareTest.php @@ -10,6 +10,7 @@ use OC\AppFramework\Http\Request; use OC\AppFramework\Middleware\Security\CORSMiddleware; use OC\AppFramework\Middleware\Security\Exceptions\SecurityException; use OC\AppFramework\Utility\ControllerMethodReflector; +use OC\Authentication\Exceptions\PasswordLoginForbiddenException; use OC\User\Session; use OCP\AppFramework\Http\JSONResponse; use OCP\AppFramework\Http\Response; @@ -124,7 +125,7 @@ class CORSMiddlewareTest extends \Test\TestCase { * @dataProvider dataCorsIgnoredIfWithCredentialsHeaderPresent */ public function testCorsIgnoredIfWithCredentialsHeaderPresent(string $method): void { - $this->expectException(\OC\AppFramework\Middleware\Security\Exceptions\SecurityException::class); + $this->expectException(SecurityException::class); $request = new Request( [ @@ -253,7 +254,7 @@ class CORSMiddlewareTest extends \Test\TestCase { * @dataProvider dataCORSShouldFailIfPasswordLoginIsForbidden */ public function testCORSShouldFailIfPasswordLoginIsForbidden(string $method): void { - $this->expectException(\OC\AppFramework\Middleware\Security\Exceptions\SecurityException::class); + $this->expectException(SecurityException::class); $request = new Request( ['server' => [ @@ -268,7 +269,7 @@ class CORSMiddlewareTest extends \Test\TestCase { $this->session->expects($this->once()) ->method('logClientIn') ->with($this->equalTo('user'), $this->equalTo('pass')) - ->will($this->throwException(new \OC\Authentication\Exceptions\PasswordLoginForbiddenException)); + ->willThrowException(new PasswordLoginForbiddenException); $this->reflector->reflect($this->controller, $method); $middleware = new CORSMiddleware($request, $this->reflector, $this->session, $this->throttler, $this->logger); @@ -286,7 +287,7 @@ class CORSMiddlewareTest extends \Test\TestCase { * @dataProvider dataCORSShouldNotAllowCookieAuth */ public function testCORSShouldNotAllowCookieAuth(string $method): void { - $this->expectException(\OC\AppFramework\Middleware\Security\Exceptions\SecurityException::class); + $this->expectException(SecurityException::class); $request = new Request( ['server' => [ diff --git a/tests/lib/AppFramework/Middleware/Security/Mock/CORSMiddlewareController.php b/tests/lib/AppFramework/Middleware/Security/Mock/CORSMiddlewareController.php index 769cba87207..8ab3a48b62e 100644 --- a/tests/lib/AppFramework/Middleware/Security/Mock/CORSMiddlewareController.php +++ b/tests/lib/AppFramework/Middleware/Security/Mock/CORSMiddlewareController.php @@ -9,10 +9,11 @@ declare(strict_types=1); namespace Test\AppFramework\Middleware\Security\Mock; +use OCP\AppFramework\Controller; use OCP\AppFramework\Http\Attribute\CORS; use OCP\AppFramework\Http\Attribute\PublicPage; -class CORSMiddlewareController extends \OCP\AppFramework\Controller { +class CORSMiddlewareController extends Controller { /** * @CORS */ diff --git a/tests/lib/AppFramework/Middleware/Security/Mock/NormalController.php b/tests/lib/AppFramework/Middleware/Security/Mock/NormalController.php index 99f33be1cc9..4d6778e98b9 100644 --- a/tests/lib/AppFramework/Middleware/Security/Mock/NormalController.php +++ b/tests/lib/AppFramework/Middleware/Security/Mock/NormalController.php @@ -9,7 +9,9 @@ declare(strict_types=1); namespace Test\AppFramework\Middleware\Security\Mock; -class NormalController extends \OCP\AppFramework\Controller { +use OCP\AppFramework\Controller; + +class NormalController extends Controller { public function foo() { } } diff --git a/tests/lib/AppFramework/Middleware/Security/Mock/PasswordConfirmationMiddlewareController.php b/tests/lib/AppFramework/Middleware/Security/Mock/PasswordConfirmationMiddlewareController.php index 02159661ff6..cd1cdaa49ca 100644 --- a/tests/lib/AppFramework/Middleware/Security/Mock/PasswordConfirmationMiddlewareController.php +++ b/tests/lib/AppFramework/Middleware/Security/Mock/PasswordConfirmationMiddlewareController.php @@ -9,9 +9,10 @@ declare(strict_types=1); namespace Test\AppFramework\Middleware\Security\Mock; +use OCP\AppFramework\Controller; use OCP\AppFramework\Http\Attribute\PasswordConfirmationRequired; -class PasswordConfirmationMiddlewareController extends \OCP\AppFramework\Controller { +class PasswordConfirmationMiddlewareController extends Controller { public function testNoAnnotationNorAttribute() { } diff --git a/tests/lib/AppFramework/Middleware/Security/Mock/SecurityMiddlewareController.php b/tests/lib/AppFramework/Middleware/Security/Mock/SecurityMiddlewareController.php index 7d40d587c8e..c8f9878b0c1 100644 --- a/tests/lib/AppFramework/Middleware/Security/Mock/SecurityMiddlewareController.php +++ b/tests/lib/AppFramework/Middleware/Security/Mock/SecurityMiddlewareController.php @@ -9,6 +9,7 @@ declare(strict_types=1); namespace Test\AppFramework\Middleware\Security\Mock; +use OCP\AppFramework\Controller; use OCP\AppFramework\Http\Attribute\ExAppRequired; use OCP\AppFramework\Http\Attribute\NoAdminRequired; use OCP\AppFramework\Http\Attribute\NoCSRFRequired; @@ -16,7 +17,7 @@ use OCP\AppFramework\Http\Attribute\PublicPage; use OCP\AppFramework\Http\Attribute\StrictCookiesRequired; use OCP\AppFramework\Http\Attribute\SubAdminRequired; -class SecurityMiddlewareController extends \OCP\AppFramework\Controller { +class SecurityMiddlewareController extends Controller { /** * @PublicPage * @NoCSRFRequired diff --git a/tests/lib/AppFramework/Middleware/Security/SecurityMiddlewareTest.php b/tests/lib/AppFramework/Middleware/Security/SecurityMiddlewareTest.php index 3b5861cbba9..183f1aa7477 100644 --- a/tests/lib/AppFramework/Middleware/Security/SecurityMiddlewareTest.php +++ b/tests/lib/AppFramework/Middleware/Security/SecurityMiddlewareTest.php @@ -332,7 +332,7 @@ class SecurityMiddlewareTest extends \Test\TestCase { * @dataProvider dataPublicPage */ public function testCsrfCheck(string $method): void { - $this->expectException(\OC\AppFramework\Middleware\Security\Exceptions\CrossSiteRequestForgeryException::class); + $this->expectException(CrossSiteRequestForgeryException::class); $this->request->expects($this->once()) ->method('passesCSRFCheck') @@ -375,7 +375,7 @@ class SecurityMiddlewareTest extends \Test\TestCase { * @dataProvider dataPublicPage */ public function testFailCsrfCheck(string $method): void { - $this->expectException(\OC\AppFramework\Middleware\Security\Exceptions\CrossSiteRequestForgeryException::class); + $this->expectException(CrossSiteRequestForgeryException::class); $this->request->expects($this->once()) ->method('passesCSRFCheck') diff --git a/tests/lib/AppFramework/OCS/BaseResponseTest.php b/tests/lib/AppFramework/OCS/BaseResponseTest.php index 159459a4aec..a04f517db0b 100644 --- a/tests/lib/AppFramework/OCS/BaseResponseTest.php +++ b/tests/lib/AppFramework/OCS/BaseResponseTest.php @@ -12,9 +12,9 @@ namespace Test\AppFramework\OCS; use OC\AppFramework\OCS\BaseResponse; class ArrayValue implements \JsonSerializable { - private $array; - public function __construct(array $array) { - $this->array = $array; + public function __construct( + private array $array, + ) { } public function jsonSerialize(): mixed { diff --git a/tests/lib/AppFramework/Utility/SimpleContainerTest.php b/tests/lib/AppFramework/Utility/SimpleContainerTest.php index a1cc1e76aeb..93db01d3bc8 100644 --- a/tests/lib/AppFramework/Utility/SimpleContainerTest.php +++ b/tests/lib/AppFramework/Utility/SimpleContainerTest.php @@ -11,6 +11,7 @@ declare(strict_types=1); namespace Test\AppFramework\Utility; use OC\AppFramework\Utility\SimpleContainer; +use OCP\AppFramework\QueryException; use Psr\Container\NotFoundExceptionInterface; interface TestInterface { @@ -20,42 +21,40 @@ class ClassEmptyConstructor implements IInterfaceConstructor { } class ClassSimpleConstructor implements IInterfaceConstructor { - public $test; - public function __construct($test) { - $this->test = $test; + public function __construct( + public $test, + ) { } } class ClassComplexConstructor { - public $class; - public $test; - public function __construct(ClassSimpleConstructor $class, $test) { - $this->class = $class; - $this->test = $test; + public function __construct( + public ClassSimpleConstructor $class, + public $test, + ) { } } class ClassNullableUntypedConstructorArg { - public $class; - public function __construct($class) { - $this->class = $class; + public function __construct( + public $class, + ) { } } class ClassNullableTypedConstructorArg { - public $class; - public function __construct(?\Some\Class $class) { - $this->class = $class; + public function __construct( + public ?\Some\Class $class, + ) { } } interface IInterfaceConstructor { } class ClassInterfaceConstructor { - public $class; - public $test; - public function __construct(IInterfaceConstructor $class, $test) { - $this->class = $class; - $this->test = $test; + public function __construct( + public IInterfaceConstructor $class, + public $test, + ) { } } @@ -83,7 +82,7 @@ class SimpleContainerTest extends \Test\TestCase { $this->container->query('something really hard', false); $this->fail('Expected `QueryException` exception was not thrown'); } catch (\Throwable $exception) { - $this->assertInstanceOf(\OCP\AppFramework\QueryException::class, $exception); + $this->assertInstanceOf(QueryException::class, $exception); $this->assertInstanceOf(NotFoundExceptionInterface::class, $exception); } } @@ -97,7 +96,7 @@ class SimpleContainerTest extends \Test\TestCase { $this->container->query('something really hard'); $this->fail('Expected `QueryException` exception was not thrown'); } catch (\Throwable $exception) { - $this->assertInstanceOf(\OCP\AppFramework\QueryException::class, $exception); + $this->assertInstanceOf(QueryException::class, $exception); $this->assertInstanceOf(NotFoundExceptionInterface::class, $exception); } } @@ -105,7 +104,7 @@ class SimpleContainerTest extends \Test\TestCase { public function testNotAClass(): void { - $this->expectException(\OCP\AppFramework\QueryException::class); + $this->expectException(QueryException::class); $this->container->query('Test\AppFramework\Utility\TestInterface'); } @@ -214,7 +213,7 @@ class SimpleContainerTest extends \Test\TestCase { public function testConstructorComplexNoTestParameterFound(): void { - $this->expectException(\OCP\AppFramework\QueryException::class); + $this->expectException(QueryException::class); $object = $this->container->query( 'Test\AppFramework\Utility\ClassComplexConstructor' @@ -245,7 +244,7 @@ class SimpleContainerTest extends \Test\TestCase { } public function testQueryUntypedNullable(): void { - $this->expectException(\OCP\AppFramework\QueryException::class); + $this->expectException(QueryException::class); $object = $this->container->query( ClassNullableUntypedConstructorArg::class diff --git a/tests/lib/AppTest.php b/tests/lib/AppTest.php index cd33be9378d..4813ea8c839 100644 --- a/tests/lib/AppTest.php +++ b/tests/lib/AppTest.php @@ -18,6 +18,7 @@ use OCP\IDBConnection; use OCP\IGroupManager; use OCP\IUserManager; use OCP\IUserSession; +use OCP\Server; use OCP\ServerVersion; use PHPUnit\Framework\MockObject\MockObject; use Psr\Log\LoggerInterface; @@ -469,8 +470,8 @@ class AppTest extends \Test\TestCase { * @dataProvider appConfigValuesProvider */ public function testEnabledApps($user, $expectedApps, $forceAll): void { - $userManager = \OCP\Server::get(IUserManager::class); - $groupManager = \OCP\Server::get(IGroupManager::class); + $userManager = Server::get(IUserManager::class); + $groupManager = Server::get(IGroupManager::class); $user1 = $userManager->createUser(self::TEST_USER1, 'NotAnEasyPassword123456+'); $user2 = $userManager->createUser(self::TEST_USER2, 'NotAnEasyPassword123456_'); $user3 = $userManager->createUser(self::TEST_USER3, 'NotAnEasyPassword123456?'); @@ -517,7 +518,7 @@ class AppTest extends \Test\TestCase { * enabled apps more than once when a user is set. */ public function testEnabledAppsCache(): void { - $userManager = \OCP\Server::get(IUserManager::class); + $userManager = Server::get(IUserManager::class); $user1 = $userManager->createUser(self::TEST_USER1, 'NotAnEasyPassword123456+'); \OC_User::setUserId(self::TEST_USER1); @@ -549,7 +550,7 @@ class AppTest extends \Test\TestCase { /** @var AppConfig|MockObject */ $appConfig = $this->getMockBuilder(AppConfig::class) ->onlyMethods(['searchValues']) - ->setConstructorArgs([\OCP\Server::get(IDBConnection::class)]) + ->setConstructorArgs([Server::get(IDBConnection::class)]) ->disableOriginalConstructor() ->getMock(); @@ -565,13 +566,13 @@ class AppTest extends \Test\TestCase { private function registerAppConfig(AppConfig $appConfig) { $this->overwriteService(AppConfig::class, $appConfig); $this->overwriteService(AppManager::class, new AppManager( - \OCP\Server::get(IUserSession::class), - \OCP\Server::get(IConfig::class), - \OCP\Server::get(IGroupManager::class), - \OCP\Server::get(ICacheFactory::class), - \OCP\Server::get(IEventDispatcher::class), - \OCP\Server::get(LoggerInterface::class), - \OCP\Server::get(ServerVersion::class), + Server::get(IUserSession::class), + Server::get(IConfig::class), + Server::get(IGroupManager::class), + Server::get(ICacheFactory::class), + Server::get(IEventDispatcher::class), + Server::get(LoggerInterface::class), + Server::get(ServerVersion::class), )); } diff --git a/tests/lib/Archive/TARTest.php b/tests/lib/Archive/TARTest.php index 36629a0273f..3a0a02fdbbd 100644 --- a/tests/lib/Archive/TARTest.php +++ b/tests/lib/Archive/TARTest.php @@ -8,6 +8,8 @@ namespace Test\Archive; use OC\Archive\TAR; +use OCP\ITempManager; +use OCP\Server; class TARTest extends TestBase { protected function getExisting() { @@ -16,6 +18,6 @@ class TARTest extends TestBase { } protected function getNew() { - return new TAR(\OC::$server->getTempManager()->getTemporaryFile('.tar.gz')); + return new TAR(Server::get(ITempManager::class)->getTemporaryFile('.tar.gz')); } } diff --git a/tests/lib/Archive/TestBase.php b/tests/lib/Archive/TestBase.php index fda485d2dc1..a4ff579d244 100644 --- a/tests/lib/Archive/TestBase.php +++ b/tests/lib/Archive/TestBase.php @@ -7,6 +7,10 @@ namespace Test\Archive; +use OCP\Files; +use OCP\ITempManager; +use OCP\Server; + abstract class TestBase extends \Test\TestCase { /** * @var \OC\Archive\Archive @@ -56,7 +60,7 @@ abstract class TestBase extends \Test\TestCase { $textFile = $dir . '/lorem.txt'; $this->assertEquals(file_get_contents($textFile), $this->instance->getFile('lorem.txt')); - $tmpFile = \OC::$server->getTempManager()->getTemporaryFile('.txt'); + $tmpFile = Server::get(ITempManager::class)->getTemporaryFile('.txt'); $this->instance->extractFile('lorem.txt', $tmpFile); $this->assertEquals(file_get_contents($textFile), file_get_contents($tmpFile)); } @@ -90,7 +94,7 @@ abstract class TestBase extends \Test\TestCase { $this->instance = $this->getNew(); $fh = $this->instance->getStream('lorem.txt', 'w'); $source = fopen($dir . '/lorem.txt', 'r'); - \OCP\Files::streamCopy($source, $fh); + Files::streamCopy($source, $fh); fclose($source); fclose($fh); $this->assertTrue($this->instance->fileExists('lorem.txt')); @@ -110,13 +114,13 @@ abstract class TestBase extends \Test\TestCase { public function testExtract(): void { $dir = \OC::$SERVERROOT . '/tests/data'; $this->instance = $this->getExisting(); - $tmpDir = \OC::$server->getTempManager()->getTemporaryFolder(); + $tmpDir = Server::get(ITempManager::class)->getTemporaryFolder(); $this->instance->extract($tmpDir); $this->assertEquals(true, file_exists($tmpDir . 'lorem.txt')); $this->assertEquals(true, file_exists($tmpDir . 'dir/lorem.txt')); $this->assertEquals(true, file_exists($tmpDir . 'logo-wide.png')); $this->assertEquals(file_get_contents($dir . '/lorem.txt'), file_get_contents($tmpDir . 'lorem.txt')); - \OCP\Files::rmdirr($tmpDir); + Files::rmdirr($tmpDir); } public function testMoveRemove(): void { $dir = \OC::$SERVERROOT . '/tests/data'; diff --git a/tests/lib/Archive/ZIPTest.php b/tests/lib/Archive/ZIPTest.php index 59fb91006a3..272824980a7 100644 --- a/tests/lib/Archive/ZIPTest.php +++ b/tests/lib/Archive/ZIPTest.php @@ -8,6 +8,8 @@ namespace Test\Archive; use OC\Archive\ZIP; +use OCP\ITempManager; +use OCP\Server; class ZIPTest extends TestBase { protected function getExisting() { @@ -16,7 +18,7 @@ class ZIPTest extends TestBase { } protected function getNew() { - $newZip = \OC::$server->getTempManager()->getTempBaseDir() . '/newArchive.zip'; + $newZip = Server::get(ITempManager::class)->getTempBaseDir() . '/newArchive.zip'; if (file_exists($newZip)) { unlink($newZip); } diff --git a/tests/lib/Authentication/Listeners/UserDeletedTokenCleanupListenerTest.php b/tests/lib/Authentication/Listeners/UserDeletedTokenCleanupListenerTest.php index a7590cdd244..1861a5b2150 100644 --- a/tests/lib/Authentication/Listeners/UserDeletedTokenCleanupListenerTest.php +++ b/tests/lib/Authentication/Listeners/UserDeletedTokenCleanupListenerTest.php @@ -91,7 +91,7 @@ class UserDeletedTokenCleanupListenerTest extends TestCase { ]; $this->manager->expects($this->exactly(3)) ->method('invalidateTokenById') - ->willReturnCallback(function () use (&$calls) { + ->willReturnCallback(function () use (&$calls): void { $expected = array_shift($calls); $this->assertEquals($expected, func_get_args()); }); diff --git a/tests/lib/Authentication/LoginCredentials/StoreTest.php b/tests/lib/Authentication/LoginCredentials/StoreTest.php index 072ec2ab571..aca586b91ec 100644 --- a/tests/lib/Authentication/LoginCredentials/StoreTest.php +++ b/tests/lib/Authentication/LoginCredentials/StoreTest.php @@ -111,7 +111,7 @@ class StoreTest extends TestCase { public function testGetLoginCredentialsSessionNotAvailable(): void { $this->session->expects($this->once()) ->method('getId') - ->will($this->throwException(new SessionNotAvailableException())); + ->willThrowException(new SessionNotAvailableException()); $this->expectException(CredentialsUnavailableException::class); $this->store->getLoginCredentials(); @@ -124,7 +124,7 @@ class StoreTest extends TestCase { $this->tokenProvider->expects($this->once()) ->method('getToken') ->with('sess2233') - ->will($this->throwException(new InvalidTokenException())); + ->willThrowException(new InvalidTokenException()); $this->expectException(CredentialsUnavailableException::class); $this->store->getLoginCredentials(); @@ -141,7 +141,7 @@ class StoreTest extends TestCase { $this->tokenProvider->expects($this->once()) ->method('getToken') ->with('sess2233') - ->will($this->throwException(new InvalidTokenException())); + ->willThrowException(new InvalidTokenException()); $this->session->expects($this->once()) ->method('exists') ->with($this->equalTo('login_credentials')) @@ -181,7 +181,7 @@ class StoreTest extends TestCase { $this->tokenProvider->expects($this->once()) ->method('getToken') ->with('sess2233') - ->will($this->throwException(new InvalidTokenException())); + ->willThrowException(new InvalidTokenException()); $this->session->expects($this->once()) ->method('exists') ->with($this->equalTo('login_credentials')) @@ -222,7 +222,7 @@ class StoreTest extends TestCase { $this->tokenProvider->expects($this->once()) ->method('getToken') ->with('sess2233') - ->will($this->throwException(new InvalidTokenException())); + ->willThrowException(new InvalidTokenException()); $this->session->expects($this->once()) ->method('exists') ->with($this->equalTo('login_credentials')) @@ -248,7 +248,7 @@ class StoreTest extends TestCase { $this->tokenProvider->expects($this->once()) ->method('getToken') ->with('sess2233') - ->will($this->throwException(new PasswordlessTokenException())); + ->willThrowException(new PasswordlessTokenException()); $this->expectException(CredentialsUnavailableException::class); $this->store->getLoginCredentials(); @@ -276,7 +276,7 @@ class StoreTest extends TestCase { $this->tokenProvider->expects($this->once()) ->method('getToken') ->with('sess2233') - ->will($this->throwException(new PasswordlessTokenException())); + ->willThrowException(new PasswordlessTokenException()); $this->session->expects($this->once()) ->method('exists') diff --git a/tests/lib/Authentication/Token/ManagerTest.php b/tests/lib/Authentication/Token/ManagerTest.php index 0f95d1d2f2c..300517fab4a 100644 --- a/tests/lib/Authentication/Token/ManagerTest.php +++ b/tests/lib/Authentication/Token/ManagerTest.php @@ -382,7 +382,7 @@ class ManagerTest extends TestCase { $this->publicKeyTokenProvider ->expects($this->exactly(2)) ->method('invalidateTokenById') - ->willReturnCallback(function () use (&$calls) { + ->willReturnCallback(function () use (&$calls): void { $expected = array_shift($calls); $this->assertEquals($expected, func_get_args()); }); diff --git a/tests/lib/Authentication/Token/PublicKeyTokenMapperTest.php b/tests/lib/Authentication/Token/PublicKeyTokenMapperTest.php index 7cc4e77ecb2..d1585dadc26 100644 --- a/tests/lib/Authentication/Token/PublicKeyTokenMapperTest.php +++ b/tests/lib/Authentication/Token/PublicKeyTokenMapperTest.php @@ -8,13 +8,14 @@ declare(strict_types=1); namespace Test\Authentication\Token; -use OC; use OC\Authentication\Token\PublicKeyToken; use OC\Authentication\Token\PublicKeyTokenMapper; +use OCP\AppFramework\Db\DoesNotExistException; use OCP\Authentication\Token\IToken; use OCP\DB\QueryBuilder\IQueryBuilder; use OCP\IDBConnection; use OCP\IUser; +use OCP\Server; use Test\TestCase; /** @@ -33,7 +34,7 @@ class PublicKeyTokenMapperTest extends TestCase { protected function setUp(): void { parent::setUp(); - $this->dbConnection = OC::$server->getDatabaseConnection(); + $this->dbConnection = Server::get(IDBConnection::class); $this->time = time(); $this->resetDatabase(); @@ -178,7 +179,7 @@ class PublicKeyTokenMapperTest extends TestCase { public function testGetInvalidToken(): void { - $this->expectException(\OCP\AppFramework\Db\DoesNotExistException::class); + $this->expectException(DoesNotExistException::class); $token = 'thisisaninvalidtokenthatisnotinthedatabase'; @@ -210,14 +211,14 @@ class PublicKeyTokenMapperTest extends TestCase { public function testGetTokenByIdNotFound(): void { - $this->expectException(\OCP\AppFramework\Db\DoesNotExistException::class); + $this->expectException(DoesNotExistException::class); $this->mapper->getTokenById(-1); } public function testGetInvalidTokenById(): void { - $this->expectException(\OCP\AppFramework\Db\DoesNotExistException::class); + $this->expectException(DoesNotExistException::class); $id = '42'; diff --git a/tests/lib/Authentication/Token/PublicKeyTokenProviderTest.php b/tests/lib/Authentication/Token/PublicKeyTokenProviderTest.php index dc6ec7c7f3e..c6c4ec4198f 100644 --- a/tests/lib/Authentication/Token/PublicKeyTokenProviderTest.php +++ b/tests/lib/Authentication/Token/PublicKeyTokenProviderTest.php @@ -23,6 +23,7 @@ use OCP\IConfig; use OCP\IDBConnection; use OCP\Security\ICrypto; use OCP\Security\IHasher; +use OCP\Server; use PHPUnit\Framework\MockObject\MockObject; use Psr\Log\LoggerInterface; use Test\TestCase; @@ -53,8 +54,8 @@ class PublicKeyTokenProviderTest extends TestCase { parent::setUp(); $this->mapper = $this->createMock(PublicKeyTokenMapper::class); - $this->hasher = \OC::$server->get(IHasher::class); - $this->crypto = \OC::$server->getCrypto(); + $this->hasher = Server::get(IHasher::class); + $this->crypto = Server::get(ICrypto::class); $this->config = $this->createMock(IConfig::class); $this->config->method('getSystemValue') ->willReturnMap([ @@ -232,7 +233,7 @@ class PublicKeyTokenProviderTest extends TestCase { public function testGetPasswordPasswordLessToken(): void { - $this->expectException(\OC\Authentication\Exceptions\PasswordlessTokenException::class); + $this->expectException(PasswordlessTokenException::class); $token = 'token1234'; $tk = new PublicKeyToken(); @@ -243,7 +244,7 @@ class PublicKeyTokenProviderTest extends TestCase { public function testGetPasswordInvalidToken(): void { - $this->expectException(\OC\Authentication\Exceptions\InvalidTokenException::class); + $this->expectException(InvalidTokenException::class); $token = 'tokentokentokentokentoken'; $uid = 'user'; @@ -294,7 +295,7 @@ class PublicKeyTokenProviderTest extends TestCase { public function testSetPasswordInvalidToken(): void { - $this->expectException(\OC\Authentication\Exceptions\InvalidTokenException::class); + $this->expectException(InvalidTokenException::class); $token = $this->createMock(IToken::class); $tokenId = 'token123'; @@ -311,7 +312,7 @@ class PublicKeyTokenProviderTest extends TestCase { $this->mapper->expects($this->exactly(2)) ->method('invalidate') - ->willReturnCallback(function () use (&$calls) { + ->willReturnCallback(function () use (&$calls): void { $expected = array_shift($calls); $this->assertEquals($expected, func_get_args()); }); @@ -350,7 +351,7 @@ class PublicKeyTokenProviderTest extends TestCase { ]; $this->mapper->expects($this->exactly(4)) ->method('invalidateOld') - ->willReturnCallback(function () use (&$calls) { + ->willReturnCallback(function () use (&$calls): void { $expected = array_shift($calls); $this->assertEquals($expected, func_get_args()); }); @@ -469,7 +470,7 @@ class PublicKeyTokenProviderTest extends TestCase { ]; $this->mapper->expects($this->exactly(2)) ->method('getToken') - ->willReturnCallback(function (string $token) use (&$calls) { + ->willReturnCallback(function (string $token) use (&$calls): void { $expected = array_shift($calls); $this->assertEquals(hash('sha512', $expected), $token); throw new DoesNotExistException('nope'); diff --git a/tests/lib/Authentication/TwoFactorAuth/Db/ProviderUserAssignmentDaoTest.php b/tests/lib/Authentication/TwoFactorAuth/Db/ProviderUserAssignmentDaoTest.php index 7a1ea64ca9a..b59ef876ffd 100644 --- a/tests/lib/Authentication/TwoFactorAuth/Db/ProviderUserAssignmentDaoTest.php +++ b/tests/lib/Authentication/TwoFactorAuth/Db/ProviderUserAssignmentDaoTest.php @@ -9,9 +9,9 @@ declare(strict_types=1); namespace Test\Authentication\TwoFactorAuth\Db; -use OC; use OC\Authentication\TwoFactorAuth\Db\ProviderUserAssignmentDao; use OCP\IDBConnection; +use OCP\Server; use Test\TestCase; /** @@ -27,7 +27,7 @@ class ProviderUserAssignmentDaoTest extends TestCase { protected function setUp(): void { parent::setUp(); - $this->dbConn = OC::$server->getDatabaseConnection(); + $this->dbConn = Server::get(IDBConnection::class); $qb = $this->dbConn->getQueryBuilder(); $q = $qb->delete(ProviderUserAssignmentDao::TABLE_NAME); $q->execute(); diff --git a/tests/lib/Authentication/TwoFactorAuth/ManagerTest.php b/tests/lib/Authentication/TwoFactorAuth/ManagerTest.php index 75691627ce7..c68d1de60c5 100644 --- a/tests/lib/Authentication/TwoFactorAuth/ManagerTest.php +++ b/tests/lib/Authentication/TwoFactorAuth/ManagerTest.php @@ -8,8 +8,9 @@ namespace Test\Authentication\TwoFactorAuth; -use OC; +use OC\Authentication\Exceptions\InvalidTokenException; use OC\Authentication\Token\IProvider as TokenProvider; +use OC\Authentication\Token\IToken; use OC\Authentication\TwoFactorAuth\Manager; use OC\Authentication\TwoFactorAuth\MandatoryTwoFactor; use OC\Authentication\TwoFactorAuth\ProviderLoader; @@ -363,7 +364,7 @@ class ManagerTest extends TestCase { ]; $this->session->expects($this->exactly(2)) ->method('remove') - ->willReturnCallback(function () use (&$calls) { + ->willReturnCallback(function () use (&$calls): void { $expected = array_shift($calls); $this->assertEquals($expected, func_get_args()); }); @@ -404,7 +405,7 @@ class ManagerTest extends TestCase { 'provider' => 'Fake 2FA', ])) ->willReturnSelf(); - $token = $this->createMock(OC\Authentication\Token\IToken::class); + $token = $this->createMock(IToken::class); $this->tokenProvider->method('getToken') ->with('mysessionid') ->willReturn($token); @@ -496,7 +497,7 @@ class ManagerTest extends TestCase { $this->session->method('getId') ->willReturn('mysessionid'); - $token = $this->createMock(OC\Authentication\Token\IToken::class); + $token = $this->createMock(IToken::class); $this->tokenProvider->method('getToken') ->with('mysessionid') ->willReturn($token); @@ -567,14 +568,14 @@ class ManagerTest extends TestCase { ]; $this->session->expects($this->exactly(2)) ->method('set') - ->willReturnCallback(function () use (&$calls) { + ->willReturnCallback(function () use (&$calls): void { $expected = array_shift($calls); $this->assertEquals($expected, func_get_args()); }); $this->session->method('getId') ->willReturn('mysessionid'); - $token = $this->createMock(OC\Authentication\Token\IToken::class); + $token = $this->createMock(IToken::class); $this->tokenProvider->method('getToken') ->with('mysessionid') ->willReturn($token); @@ -601,14 +602,14 @@ class ManagerTest extends TestCase { ]; $this->session->expects($this->exactly(2)) ->method('set') - ->willReturnCallback(function () use (&$calls) { + ->willReturnCallback(function () use (&$calls): void { $expected = array_shift($calls); $this->assertEquals($expected, func_get_args()); }); $this->session->method('getId') ->willReturn('mysessionid'); - $token = $this->createMock(OC\Authentication\Token\IToken::class); + $token = $this->createMock(IToken::class); $this->tokenProvider->method('getToken') ->with('mysessionid') ->willReturn($token); @@ -669,7 +670,7 @@ class ManagerTest extends TestCase { $this->session->method('getId') ->willReturn('mysessionid'); - $token = $this->createMock(OC\Authentication\Token\IToken::class); + $token = $this->createMock(IToken::class); $token->method('getId') ->willReturn(40); @@ -704,7 +705,7 @@ class ManagerTest extends TestCase { $this->tokenProvider->method('getToken') ->with('mysessionid') - ->willThrowException(new OC\Authentication\Exceptions\InvalidTokenException()); + ->willThrowException(new InvalidTokenException()); $this->config->method('getUserKeys')->willReturn([]); @@ -736,7 +737,7 @@ class ManagerTest extends TestCase { ]; $this->config->expects($this->exactly(3)) ->method('deleteUserValue') - ->willReturnCallback(function () use (&$deleteUserValueCalls) { + ->willReturnCallback(function () use (&$deleteUserValueCalls): void { $expected = array_shift($deleteUserValueCalls); $this->assertEquals($expected, func_get_args()); }); @@ -748,7 +749,7 @@ class ManagerTest extends TestCase { ]; $this->tokenProvider->expects($this->exactly(3)) ->method('invalidateTokenById') - ->willReturnCallback(function () use (&$invalidateCalls) { + ->willReturnCallback(function () use (&$invalidateCalls): void { $expected = array_shift($invalidateCalls); $this->assertEquals($expected, func_get_args()); }); @@ -770,7 +771,7 @@ class ManagerTest extends TestCase { ]; $this->config->expects($this->exactly(3)) ->method('deleteUserValue') - ->willReturnCallback(function () use (&$deleteUserValueCalls) { + ->willReturnCallback(function () use (&$deleteUserValueCalls): void { $expected = array_shift($deleteUserValueCalls); $this->assertEquals($expected, func_get_args()); }); @@ -782,7 +783,7 @@ class ManagerTest extends TestCase { ]; $this->tokenProvider->expects($this->exactly(3)) ->method('invalidateTokenById') - ->willReturnCallback(function ($user, $tokenId) use (&$invalidateCalls) { + ->willReturnCallback(function ($user, $tokenId) use (&$invalidateCalls): void { $expected = array_shift($invalidateCalls); $this->assertEquals($expected, func_get_args()); if ($tokenId === 43) { diff --git a/tests/lib/Authentication/TwoFactorAuth/ProviderManagerTest.php b/tests/lib/Authentication/TwoFactorAuth/ProviderManagerTest.php index 34248f11f21..6004e67603b 100644 --- a/tests/lib/Authentication/TwoFactorAuth/ProviderManagerTest.php +++ b/tests/lib/Authentication/TwoFactorAuth/ProviderManagerTest.php @@ -9,6 +9,7 @@ declare(strict_types=1); namespace lib\Authentication\TwoFactorAuth; +use OC\Authentication\Exceptions\InvalidProviderException; use OC\Authentication\TwoFactorAuth\ProviderLoader; use OC\Authentication\TwoFactorAuth\ProviderManager; use OCP\Authentication\TwoFactorAuth\IActivatableByAdmin; @@ -43,7 +44,7 @@ class ProviderManagerTest extends TestCase { public function testTryEnableInvalidProvider(): void { - $this->expectException(\OC\Authentication\Exceptions\InvalidProviderException::class); + $this->expectException(InvalidProviderException::class); $user = $this->createMock(IUser::class); $this->providerManager->tryEnableProviderFor('none', $user); @@ -89,7 +90,7 @@ class ProviderManagerTest extends TestCase { public function testTryDisableInvalidProvider(): void { - $this->expectException(\OC\Authentication\Exceptions\InvalidProviderException::class); + $this->expectException(InvalidProviderException::class); $user = $this->createMock(IUser::class); $this->providerManager->tryDisableProviderFor('none', $user); diff --git a/tests/lib/Authentication/TwoFactorAuth/RegistryTest.php b/tests/lib/Authentication/TwoFactorAuth/RegistryTest.php index 252b57e7983..2018dc1a634 100644 --- a/tests/lib/Authentication/TwoFactorAuth/RegistryTest.php +++ b/tests/lib/Authentication/TwoFactorAuth/RegistryTest.php @@ -126,7 +126,7 @@ class RegistryTest extends TestCase { ]; $this->dispatcher->expects($this->exactly(2)) ->method('dispatchTyped') - ->willReturnCallback(function () use (&$calls) { + ->willReturnCallback(function () use (&$calls): void { $expected = array_shift($calls); $this->assertEquals($expected, func_get_args()); }); diff --git a/tests/lib/Avatar/UserAvatarTest.php b/tests/lib/Avatar/UserAvatarTest.php index 633a0fda368..ead829c231c 100644 --- a/tests/lib/Avatar/UserAvatarTest.php +++ b/tests/lib/Avatar/UserAvatarTest.php @@ -7,8 +7,10 @@ namespace Test\Avatar; +use OC\Avatar\UserAvatar; use OC\Files\SimpleFS\SimpleFolder; use OC\User\User; +use OCP\Color; use OCP\Files\File; use OCP\Files\NotFoundException; use OCP\Files\SimpleFS\ISimpleFile; @@ -56,7 +58,7 @@ class UserAvatarTest extends \Test\TestCase { ->willReturn($file); $this->folder->method('getFile') - ->willReturnCallback(function (string $path) { + ->willReturnCallback(function (string $path): void { if ($path === 'avatar.64.png') { throw new NotFoundException(); } @@ -144,7 +146,7 @@ class UserAvatarTest extends \Test\TestCase { if ($path === 'avatar.png') { return $file; } else { - throw new \OCP\Files\NotFoundException; + throw new NotFoundException; } } ); @@ -261,17 +263,17 @@ class UserAvatarTest extends \Test\TestCase { } public function testMixPalette(): void { - $colorFrom = new \OCP\Color(0, 0, 0); - $colorTo = new \OCP\Color(6, 12, 18); + $colorFrom = new Color(0, 0, 0); + $colorTo = new Color(6, 12, 18); $steps = 6; - $palette = \OCP\Color::mixPalette($steps, $colorFrom, $colorTo); + $palette = Color::mixPalette($steps, $colorFrom, $colorTo); foreach ($palette as $j => $color) { // calc increment $incR = $colorTo->red() / $steps * $j; $incG = $colorTo->green() / $steps * $j; $incB = $colorTo->blue() / $steps * $j; // ensure everything is equal - $this->assertEquals($color, new \OCP\Color($incR, $incG, $incB)); + $this->assertEquals($color, new Color($incR, $incG, $incB)); } $hashToInt = $this->invokePrivate($this->avatar, 'hashToInt', ['abcdef', 18]); $this->assertTrue(gettype($hashToInt) === 'integer'); @@ -288,7 +290,7 @@ class UserAvatarTest extends \Test\TestCase { $l = $this->createMock(IL10N::class); $l->method('t')->willReturnArgument(0); - return new \OC\Avatar\UserAvatar( + return new UserAvatar( $this->folder, $l, $user, diff --git a/tests/lib/BackgroundJob/DummyJobList.php b/tests/lib/BackgroundJob/DummyJobList.php index 7b7fce7e9e8..fac9db28b01 100644 --- a/tests/lib/BackgroundJob/DummyJobList.php +++ b/tests/lib/BackgroundJob/DummyJobList.php @@ -7,14 +7,16 @@ namespace Test\BackgroundJob; +use OC\BackgroundJob\JobList; use OCP\BackgroundJob\IJob; +use OCP\Server; /** * Class DummyJobList * * in memory job list for testing purposes */ -class DummyJobList extends \OC\BackgroundJob\JobList { +class DummyJobList extends JobList { /** * @var IJob[] */ @@ -38,7 +40,7 @@ class DummyJobList extends \OC\BackgroundJob\JobList { public function add($job, $argument = null, ?int $firstCheck = null): void { if (is_string($job)) { /** @var IJob $job */ - $job = \OCP\Server::get($job); + $job = Server::get($job); } $job->setArgument($argument); $job->setId($this->lastId); diff --git a/tests/lib/BackgroundJob/JobListTest.php b/tests/lib/BackgroundJob/JobListTest.php index 64279c11a35..2c3461f22cd 100644 --- a/tests/lib/BackgroundJob/JobListTest.php +++ b/tests/lib/BackgroundJob/JobListTest.php @@ -10,10 +10,13 @@ declare(strict_types=1); namespace Test\BackgroundJob; +use OC\BackgroundJob\JobList; use OCP\AppFramework\Utility\ITimeFactory; use OCP\BackgroundJob\IJob; use OCP\DB\QueryBuilder\IQueryBuilder; use OCP\IConfig; +use OCP\IDBConnection; +use OCP\Server; use Psr\Log\LoggerInterface; use Test\TestCase; @@ -40,15 +43,15 @@ class JobListTest extends TestCase { protected function setUp(): void { parent::setUp(); - $this->connection = \OC::$server->getDatabaseConnection(); + $this->connection = Server::get(IDBConnection::class); $this->clearJobsList(); $this->config = $this->createMock(IConfig::class); $this->timeFactory = $this->createMock(ITimeFactory::class); - $this->instance = new \OC\BackgroundJob\JobList( + $this->instance = new JobList( $this->connection, $this->config, $this->timeFactory, - \OC::$server->get(LoggerInterface::class), + Server::get(LoggerInterface::class), ); } @@ -277,10 +280,10 @@ class JobListTest extends TestCase { ->method('getTime') ->willReturn(123456789); - $job = new TestJob($this->timeFactory, $this, function () { + $job = new TestJob($this->timeFactory, $this, function (): void { }); - $job2 = new TestJob($this->timeFactory, $this, function () { + $job2 = new TestJob($this->timeFactory, $this, function (): void { }); $this->instance->add($job, 1); @@ -310,10 +313,10 @@ class JobListTest extends TestCase { return time(); }); - $job = new TestParallelAwareJob($this->timeFactory, $this, function () { + $job = new TestParallelAwareJob($this->timeFactory, $this, function (): void { }); - $job2 = new TestParallelAwareJob($this->timeFactory, $this, function () { + $job2 = new TestParallelAwareJob($this->timeFactory, $this, function (): void { }); $this->instance->add($job, 1); diff --git a/tests/lib/BackgroundJob/JobTest.php b/tests/lib/BackgroundJob/JobTest.php index 9024742f432..485f64eca9a 100644 --- a/tests/lib/BackgroundJob/JobTest.php +++ b/tests/lib/BackgroundJob/JobTest.php @@ -8,6 +8,7 @@ namespace Test\BackgroundJob; use OCP\AppFramework\Utility\ITimeFactory; +use OCP\Server; use Psr\Log\LoggerInterface; class JobTest extends \Test\TestCase { @@ -18,7 +19,7 @@ class JobTest extends \Test\TestCase { protected function setUp(): void { parent::setUp(); $this->run = false; - $this->timeFactory = \OCP\Server::get(ITimeFactory::class); + $this->timeFactory = Server::get(ITimeFactory::class); $this->logger = $this->createMock(LoggerInterface::class); \OC::$server->registerService(LoggerInterface::class, fn ($c) => $this->logger); @@ -27,7 +28,7 @@ class JobTest extends \Test\TestCase { public function testRemoveAfterException(): void { $jobList = new DummyJobList(); $e = new \Exception(); - $job = new TestJob($this->timeFactory, $this, function () use ($e) { + $job = new TestJob($this->timeFactory, $this, function () use ($e): void { throw $e; }); $jobList->add($job); @@ -43,7 +44,7 @@ class JobTest extends \Test\TestCase { public function testRemoveAfterError(): void { $jobList = new DummyJobList(); - $job = new TestJob($this->timeFactory, $this, function () { + $job = new TestJob($this->timeFactory, $this, function (): void { $test = null; $test->someMethod(); }); diff --git a/tests/lib/BackgroundJob/QueuedJobTest.php b/tests/lib/BackgroundJob/QueuedJobTest.php index 893f476bb5f..ad01dae0a31 100644 --- a/tests/lib/BackgroundJob/QueuedJobTest.php +++ b/tests/lib/BackgroundJob/QueuedJobTest.php @@ -9,6 +9,7 @@ namespace Test\BackgroundJob; use OCP\AppFramework\Utility\ITimeFactory; use OCP\BackgroundJob\QueuedJob; +use OCP\Server; class TestQueuedJobNew extends QueuedJob { public bool $ran = false; @@ -28,7 +29,7 @@ class QueuedJobTest extends \Test\TestCase { } public function testJobShouldBeRemovedNew(): void { - $job = new TestQueuedJobNew(\OCP\Server::get(ITimeFactory::class)); + $job = new TestQueuedJobNew(Server::get(ITimeFactory::class)); $job->setId(42); $this->jobList->add($job); diff --git a/tests/lib/BackgroundJob/TestJob.php b/tests/lib/BackgroundJob/TestJob.php index ea0634e63d9..f4e2b31594b 100644 --- a/tests/lib/BackgroundJob/TestJob.php +++ b/tests/lib/BackgroundJob/TestJob.php @@ -8,10 +8,10 @@ namespace Test\BackgroundJob; use OCP\AppFramework\Utility\ITimeFactory; +use OCP\BackgroundJob\Job; +use OCP\Server; -class TestJob extends \OCP\BackgroundJob\Job { - private $testCase; - +class TestJob extends Job { /** * @var callable $callback */ @@ -21,9 +21,12 @@ class TestJob extends \OCP\BackgroundJob\Job { * @param JobTest $testCase * @param callable $callback */ - public function __construct(?ITimeFactory $time = null, $testCase = null, $callback = null) { - parent::__construct($time ?? \OCP\Server::get(ITimeFactory::class)); - $this->testCase = $testCase; + public function __construct( + ?ITimeFactory $time = null, + private $testCase = null, + $callback = null, + ) { + parent::__construct($time ?? Server::get(ITimeFactory::class)); $this->callback = $callback; } diff --git a/tests/lib/BackgroundJob/TestParallelAwareJob.php b/tests/lib/BackgroundJob/TestParallelAwareJob.php index f7a6cf5fa79..fb49dd671ce 100644 --- a/tests/lib/BackgroundJob/TestParallelAwareJob.php +++ b/tests/lib/BackgroundJob/TestParallelAwareJob.php @@ -7,10 +7,10 @@ namespace Test\BackgroundJob; use OCP\AppFramework\Utility\ITimeFactory; +use OCP\BackgroundJob\Job; +use OCP\Server; -class TestParallelAwareJob extends \OCP\BackgroundJob\Job { - private $testCase; - +class TestParallelAwareJob extends Job { /** * @var callable $callback */ @@ -20,10 +20,13 @@ class TestParallelAwareJob extends \OCP\BackgroundJob\Job { * @param JobTest $testCase * @param callable $callback */ - public function __construct(?ITimeFactory $time = null, $testCase = null, $callback = null) { - parent::__construct($time ?? \OC::$server->get(ITimeFactory::class)); + public function __construct( + ?ITimeFactory $time = null, + private $testCase = null, + $callback = null, + ) { + parent::__construct($time ?? Server::get(ITimeFactory::class)); $this->setAllowParallelRuns(false); - $this->testCase = $testCase; $this->callback = $callback; } diff --git a/tests/lib/BackgroundJob/TimedJobTest.php b/tests/lib/BackgroundJob/TimedJobTest.php index 6037365104f..27f9c64499c 100644 --- a/tests/lib/BackgroundJob/TimedJobTest.php +++ b/tests/lib/BackgroundJob/TimedJobTest.php @@ -8,6 +8,7 @@ namespace Test\BackgroundJob; use OCP\AppFramework\Utility\ITimeFactory; +use OCP\Server; class TimedJobTest extends \Test\TestCase { private DummyJobList $jobList; @@ -17,7 +18,7 @@ class TimedJobTest extends \Test\TestCase { parent::setUp(); $this->jobList = new DummyJobList(); - $this->time = \OCP\Server::get(ITimeFactory::class); + $this->time = Server::get(ITimeFactory::class); } public function testShouldRunAfterIntervalNew(): void { diff --git a/tests/lib/BinaryFinderTest.php b/tests/lib/BinaryFinderTest.php index 42306e49eac..af7bf8b9126 100644 --- a/tests/lib/BinaryFinderTest.php +++ b/tests/lib/BinaryFinderTest.php @@ -39,9 +39,9 @@ class BinaryFinderTest extends TestCase { $config ->method('getSystemValue') ->with('binary_search_paths', $this->anything()) - ->will($this->returnCallback(function ($key, $default) { + ->willReturnCallback(function ($key, $default) { return $default; - })); + }); $finder = new BinaryFinder($this->cacheFactory, $config); $this->assertEquals($finder->findBinaryPath('cat'), '/usr/bin/cat'); $this->assertEquals($this->cache->get('cat'), '/usr/bin/cat'); @@ -52,9 +52,9 @@ class BinaryFinderTest extends TestCase { $config ->method('getSystemValue') ->with('binary_search_paths', $this->anything()) - ->will($this->returnCallback(function ($key, $default) { + ->willReturnCallback(function ($key, $default) { return $default; - })); + }); $finder = new BinaryFinder($this->cacheFactory, $config); $this->assertFalse($finder->findBinaryPath('cata')); $this->assertFalse($this->cache->get('cata')); diff --git a/tests/lib/Cache/CappedMemoryCacheTest.php b/tests/lib/Cache/CappedMemoryCacheTest.php index f2ed1a5ee0d..f0cf9aa280b 100644 --- a/tests/lib/Cache/CappedMemoryCacheTest.php +++ b/tests/lib/Cache/CappedMemoryCacheTest.php @@ -7,6 +7,8 @@ namespace Test\Cache; +use OCP\Cache\CappedMemoryCache; + /** * Class CappedMemoryCacheTest * @@ -15,11 +17,11 @@ namespace Test\Cache; class CappedMemoryCacheTest extends TestCache { protected function setUp(): void { parent::setUp(); - $this->instance = new \OCP\Cache\CappedMemoryCache(); + $this->instance = new CappedMemoryCache(); } public function testSetOverCap(): void { - $instance = new \OCP\Cache\CappedMemoryCache(3); + $instance = new CappedMemoryCache(3); $instance->set('1', 'a'); $instance->set('2', 'b'); diff --git a/tests/lib/Cache/FileCacheTest.php b/tests/lib/Cache/FileCacheTest.php index 8d3db539dd0..a60609782f0 100644 --- a/tests/lib/Cache/FileCacheTest.php +++ b/tests/lib/Cache/FileCacheTest.php @@ -7,8 +7,16 @@ namespace Test\Cache; +use OC\Cache\File; +use OC\Files\Filesystem; use OC\Files\Storage\Local; +use OC\Files\Storage\Temporary; +use OC\Files\View; +use OCP\Files\LockNotAcquiredException; use OCP\Files\Mount\IMountManager; +use OCP\ITempManager; +use OCP\Lock\LockedException; +use OCP\Server; use Test\Traits\UserTrait; /** @@ -55,17 +63,17 @@ class FileCacheTest extends TestCache { \OC_Hook::clear('OC_Filesystem'); /** @var IMountManager $manager */ - $manager = \OC::$server->get(IMountManager::class); + $manager = Server::get(IMountManager::class); $manager->removeMount('/test'); - $storage = new \OC\Files\Storage\Temporary([]); - \OC\Files\Filesystem::mount($storage, [], '/test/cache'); + $storage = new Temporary([]); + Filesystem::mount($storage, [], '/test/cache'); //set up the users dir - $this->rootView = new \OC\Files\View(''); + $this->rootView = new View(''); $this->rootView->mkdir('/test'); - $this->instance = new \OC\Cache\File(); + $this->instance = new File(); // forces creation of cache folder for subsequent tests $this->instance->set('hack', 'hack'); @@ -89,10 +97,10 @@ class FileCacheTest extends TestCache { private function setupMockStorage() { $mockStorage = $this->getMockBuilder(Local::class) ->onlyMethods(['filemtime', 'unlink']) - ->setConstructorArgs([['datadir' => \OC::$server->getTempManager()->getTemporaryFolder()]]) + ->setConstructorArgs([['datadir' => Server::get(ITempManager::class)->getTemporaryFolder()]]) ->getMock(); - \OC\Files\Filesystem::mount($mockStorage, [], '/test/cache'); + Filesystem::mount($mockStorage, [], '/test/cache'); return $mockStorage; } @@ -127,8 +135,8 @@ class FileCacheTest extends TestCache { public static function lockExceptionProvider(): array { return [ - [new \OCP\Lock\LockedException('key1')], - [new \OCP\Files\LockNotAcquiredException('key1', 1)], + [new LockedException('key1')], + [new LockNotAcquiredException('key1', 1)], ]; } @@ -142,11 +150,7 @@ class FileCacheTest extends TestCache { ->method('filemtime') ->willReturn(100); $mockStorage->expects($this->atLeastOnce()) - ->method('unlink') - ->will($this->onConsecutiveCalls( - $this->throwException($testException), - $this->returnValue(true) - )); + ->method('unlink')->willReturnOnConsecutiveCalls($this->throwException($testException), $this->returnValue(true)); $this->instance->set('key1', 'value1'); $this->instance->set('key2', 'value2'); diff --git a/tests/lib/Calendar/ManagerTest.php b/tests/lib/Calendar/ManagerTest.php index 1fb64d97f47..7f8afc0247b 100644 --- a/tests/lib/Calendar/ManagerTest.php +++ b/tests/lib/Calendar/ManagerTest.php @@ -11,6 +11,7 @@ use OC\AppFramework\Bootstrap\Coordinator; use OC\Calendar\AvailabilityResult; use OC\Calendar\Manager; use OCA\DAV\CalDAV\Auth\CustomPrincipalPlugin; +use OCA\DAV\Connector\Sabre\Server; use OCA\DAV\ServerFactory; use OCP\AppFramework\Utility\ITimeFactory; use OCP\Calendar\ICalendar; @@ -1725,7 +1726,7 @@ EOF; ->method('setCurrentPrincipal') ->with('principals/users/admin'); - $server = $this->createMock(\OCA\DAV\Connector\Sabre\Server::class); + $server = $this->createMock(Server::class); $server->expects(self::once()) ->method('getPlugin') ->with('auth') @@ -1736,7 +1737,7 @@ EOF; RequestInterface $request, ResponseInterface $response, bool $sendResponse, - ) { + ): void { $requestBody = file_get_contents(__DIR__ . '/../../data/ics/free-busy-request.ics'); $this->assertEquals('POST', $request->getMethod()); $this->assertEquals('calendars/admin/outbox', $request->getPath()); @@ -1792,7 +1793,7 @@ EOF; ->method('setCurrentPrincipal') ->with('principals/users/admin'); - $server = $this->createMock(\OCA\DAV\Connector\Sabre\Server::class); + $server = $this->createMock(Server::class); $server->expects(self::once()) ->method('getPlugin') ->with('auth') @@ -1803,7 +1804,7 @@ EOF; RequestInterface $request, ResponseInterface $response, bool $sendResponse, - ) { + ): void { $requestBody = file_get_contents(__DIR__ . '/../../data/ics/free-busy-request.ics'); $this->assertEquals('POST', $request->getMethod()); $this->assertEquals('calendars/admin/outbox', $request->getPath()); diff --git a/tests/lib/Calendar/ResourcesRoomsUpdaterTest.php b/tests/lib/Calendar/ResourcesRoomsUpdaterTest.php index 7776ba8cd3a..9e54d21fda4 100644 --- a/tests/lib/Calendar/ResourcesRoomsUpdaterTest.php +++ b/tests/lib/Calendar/ResourcesRoomsUpdaterTest.php @@ -112,11 +112,11 @@ class ResourcesRoomsUpdaterTest extends TestCase { $backend2->method('getBackendIdentifier') ->willReturn('backend2'); $backend2->method('listAllResources') - ->will($this->throwException(new BackendTemporarilyUnavailableException())); + ->willThrowException(new BackendTemporarilyUnavailableException()); $backend2->method('getResource') - ->will($this->throwException(new BackendTemporarilyUnavailableException())); + ->willThrowException(new BackendTemporarilyUnavailableException()); $backend2->method('getAllResources') - ->will($this->throwException(new BackendTemporarilyUnavailableException())); + ->willThrowException(new BackendTemporarilyUnavailableException()); $backend3->method('getBackendIdentifier') ->willReturn('backend3'); $backend3->method('listAllResources') diff --git a/tests/lib/CapabilitiesManagerTest.php b/tests/lib/CapabilitiesManagerTest.php index 23909a91c5a..5206a28aa76 100644 --- a/tests/lib/CapabilitiesManagerTest.php +++ b/tests/lib/CapabilitiesManagerTest.php @@ -129,7 +129,7 @@ class CapabilitiesManagerTest extends TestCase { } public function testInvalidCapability(): void { - $this->manager->registerCapability(function () { + $this->manager->registerCapability(function (): void { throw new QueryException(); }); diff --git a/tests/lib/Collaboration/Collaborators/MailPluginTest.php b/tests/lib/Collaboration/Collaborators/MailPluginTest.php index 5112795ec7c..61afeb7897c 100644 --- a/tests/lib/Collaboration/Collaborators/MailPluginTest.php +++ b/tests/lib/Collaboration/Collaborators/MailPluginTest.php @@ -618,7 +618,7 @@ class MailPluginTest extends TestCase { $this->groupManager->expects($this->any()) ->method('getUserGroupIds') - ->willReturnCallback(function (\OCP\IUser $user) use ($userToGroupMapping) { + ->willReturnCallback(function (IUser $user) use ($userToGroupMapping) { return $userToGroupMapping[$user->getUID()]; }); diff --git a/tests/lib/Command/AsyncBusTestCase.php b/tests/lib/Command/AsyncBusTestCase.php index c4f173f8b32..6aca4d8d6e6 100644 --- a/tests/lib/Command/AsyncBusTestCase.php +++ b/tests/lib/Command/AsyncBusTestCase.php @@ -20,10 +20,9 @@ class SimpleCommand implements ICommand { } class StateFullCommand implements ICommand { - private $state; - - public function __construct($state) { - $this->state = $state; + public function __construct( + private $state, + ) { } public function handle() { @@ -50,7 +49,7 @@ class ThisClosureTest { } public function test(IBus $bus) { - $bus->push(function () { + $bus->push(function (): void { $this->privateMethod(); }); } @@ -126,7 +125,7 @@ abstract class AsyncBusTestCase extends TestCase { } public function testClosure(): void { - $this->getBus()->push(function () { + $this->getBus()->push(function (): void { AsyncBusTestCase::$lastCommand = 'closure'; }); $this->runJobs(); @@ -134,7 +133,7 @@ abstract class AsyncBusTestCase extends TestCase { } public function testClosureSelf(): void { - $this->getBus()->push(function () { + $this->getBus()->push(function (): void { AsyncBusTestCase::$lastCommand = 'closure-self'; }); $this->runJobs(); @@ -152,7 +151,7 @@ abstract class AsyncBusTestCase extends TestCase { public function testClosureBind(): void { $state = 'bar'; - $this->getBus()->push(function () use ($state) { + $this->getBus()->push(function () use ($state): void { AsyncBusTestCase::$lastCommand = 'closure-' . $state; }); $this->runJobs(); diff --git a/tests/lib/Command/Integrity/SignAppTest.php b/tests/lib/Command/Integrity/SignAppTest.php index 38b5c68e026..15f98dba0c0 100644 --- a/tests/lib/Command/Integrity/SignAppTest.php +++ b/tests/lib/Command/Integrity/SignAppTest.php @@ -58,7 +58,7 @@ class SignAppTest extends TestCase { $outputInterface ->expects($this->any()) ->method('writeln') - ->willReturnCallback(function (string $message) use (&$calls) { + ->willReturnCallback(function (string $message) use (&$calls): void { $expected = array_shift($calls); if ($expected === '*') { $this->assertNotEmpty($message); @@ -91,7 +91,7 @@ class SignAppTest extends TestCase { $outputInterface ->expects($this->any()) ->method('writeln') - ->willReturnCallback(function (string $message) use (&$calls) { + ->willReturnCallback(function (string $message) use (&$calls): void { $expected = array_shift($calls); if ($expected === '*') { $this->assertNotEmpty($message); @@ -124,7 +124,7 @@ class SignAppTest extends TestCase { $outputInterface ->expects($this->any()) ->method('writeln') - ->willReturnCallback(function (string $message) use (&$calls) { + ->willReturnCallback(function (string $message) use (&$calls): void { $expected = array_shift($calls); if ($expected === '*') { $this->assertNotEmpty($message); @@ -160,7 +160,7 @@ class SignAppTest extends TestCase { $outputInterface ->expects($this->any()) ->method('writeln') - ->willReturnCallback(function (string $message) { + ->willReturnCallback(function (string $message): void { $this->assertEquals('Private key "privateKey" does not exists.', $message); }); @@ -191,7 +191,7 @@ class SignAppTest extends TestCase { $outputInterface ->expects($this->any()) ->method('writeln') - ->willReturnCallback(function (string $message) { + ->willReturnCallback(function (string $message): void { $this->assertEquals('Certificate "certificate" does not exists.', $message); }); @@ -227,7 +227,7 @@ class SignAppTest extends TestCase { $outputInterface ->expects($this->any()) ->method('writeln') - ->willReturnCallback(function (string $message) { + ->willReturnCallback(function (string $message): void { $this->assertEquals('Error: My error message', $message); }); @@ -262,7 +262,7 @@ class SignAppTest extends TestCase { $outputInterface ->expects($this->any()) ->method('writeln') - ->willReturnCallback(function (string $message) { + ->willReturnCallback(function (string $message): void { $this->assertEquals('Successfully signed "AppId"', $message); }); diff --git a/tests/lib/Command/Integrity/SignCoreTest.php b/tests/lib/Command/Integrity/SignCoreTest.php index 66227322dda..efff6da2f95 100644 --- a/tests/lib/Command/Integrity/SignCoreTest.php +++ b/tests/lib/Command/Integrity/SignCoreTest.php @@ -48,7 +48,7 @@ class SignCoreTest extends TestCase { $outputInterface ->expects($this->any()) ->method('writeln') - ->willReturnCallback(function (string $message) { + ->willReturnCallback(function (string $message): void { $this->assertEquals('--privateKey, --certificate and --path are required.', $message); }); @@ -71,7 +71,7 @@ class SignCoreTest extends TestCase { $outputInterface ->expects($this->any()) ->method('writeln') - ->willReturnCallback(function (string $message) { + ->willReturnCallback(function (string $message): void { $this->assertEquals('--privateKey, --certificate and --path are required.', $message); }); @@ -100,7 +100,7 @@ class SignCoreTest extends TestCase { $outputInterface ->expects($this->any()) ->method('writeln') - ->willReturnCallback(function (string $message) { + ->willReturnCallback(function (string $message): void { $this->assertEquals('Private key "privateKey" does not exists.', $message); }); @@ -131,7 +131,7 @@ class SignCoreTest extends TestCase { $outputInterface ->expects($this->any()) ->method('writeln') - ->willReturnCallback(function (string $message) { + ->willReturnCallback(function (string $message): void { $this->assertEquals('Certificate "certificate" does not exists.', $message); }); @@ -167,7 +167,7 @@ class SignCoreTest extends TestCase { $outputInterface ->expects($this->any()) ->method('writeln') - ->willReturnCallback(function (string $message) { + ->willReturnCallback(function (string $message): void { $this->assertEquals('Error: My exception message', $message); }); @@ -202,7 +202,7 @@ class SignCoreTest extends TestCase { $outputInterface ->expects($this->any()) ->method('writeln') - ->willReturnCallback(function (string $message) { + ->willReturnCallback(function (string $message): void { $this->assertEquals('Successfully signed "core"', $message); }); diff --git a/tests/lib/Comments/CommentTest.php b/tests/lib/Comments/CommentTest.php index 988ffbe0e0b..9e28531a045 100644 --- a/tests/lib/Comments/CommentTest.php +++ b/tests/lib/Comments/CommentTest.php @@ -8,6 +8,8 @@ namespace Test\Comments; use OC\Comments\Comment; use OCP\Comments\IComment; +use OCP\Comments\IllegalIDChangeException; +use OCP\Comments\MessageTooLongException; use Test\TestCase; class CommentTest extends TestCase { @@ -62,7 +64,7 @@ class CommentTest extends TestCase { public function testSetIdIllegalInput(): void { - $this->expectException(\OCP\Comments\IllegalIDChangeException::class); + $this->expectException(IllegalIDChangeException::class); $comment = new Comment(); @@ -131,7 +133,7 @@ class CommentTest extends TestCase { public function testSetUberlongMessage(): void { - $this->expectException(\OCP\Comments\MessageTooLongException::class); + $this->expectException(MessageTooLongException::class); $comment = new Comment(); $msg = str_pad('', IComment::MAX_MESSAGE_LENGTH + 1, 'x'); diff --git a/tests/lib/Comments/FakeFactory.php b/tests/lib/Comments/FakeFactory.php index 04604ab2b44..19d8b58ae01 100644 --- a/tests/lib/Comments/FakeFactory.php +++ b/tests/lib/Comments/FakeFactory.php @@ -6,12 +6,13 @@ */ namespace Test\Comments; +use OCP\Comments\ICommentsManagerFactory; use OCP\IServerContainer; /** * Class FakeFactory */ -class FakeFactory implements \OCP\Comments\ICommentsManagerFactory { +class FakeFactory implements ICommentsManagerFactory { public function __construct(IServerContainer $serverContainer) { } diff --git a/tests/lib/Comments/ManagerTest.php b/tests/lib/Comments/ManagerTest.php index 86e70c56026..5d03bb06521 100644 --- a/tests/lib/Comments/ManagerTest.php +++ b/tests/lib/Comments/ManagerTest.php @@ -43,7 +43,7 @@ class ManagerTest extends TestCase { protected function setUp(): void { parent::setUp(); - $this->connection = \OC::$server->getDatabaseConnection(); + $this->connection = Server::get(IDBConnection::class); $this->rootFolder = $this->createMock(IRootFolder::class); $sql = $this->connection->getDatabasePlatform()->getTruncateTableSQL('`*PREFIX*comments`'); @@ -96,7 +96,7 @@ class ManagerTest extends TestCase { public function testGetCommentNotFound(): void { - $this->expectException(\OCP\Comments\NotFoundException::class); + $this->expectException(NotFoundException::class); $manager = $this->getManager(); $manager->get('22'); @@ -116,7 +116,7 @@ class ManagerTest extends TestCase { $creationDT = new \DateTime('yesterday'); $latestChildDT = new \DateTime(); - $qb = \OCP\Server::get(IDBConnection::class)->getQueryBuilder(); + $qb = Server::get(IDBConnection::class)->getQueryBuilder(); $qb ->insert('comments') ->values([ @@ -158,7 +158,7 @@ class ManagerTest extends TestCase { public function testGetTreeNotFound(): void { - $this->expectException(\OCP\Comments\NotFoundException::class); + $this->expectException(NotFoundException::class); $manager = $this->getManager(); $manager->getTree('22'); @@ -450,7 +450,7 @@ class ManagerTest extends TestCase { public function testDelete(): void { - $this->expectException(\OCP\Comments\NotFoundException::class); + $this->expectException(NotFoundException::class); $manager = $this->getManager(); @@ -564,7 +564,7 @@ class ManagerTest extends TestCase { $manager->delete($comment->getId()); $comment->setMessage('very beautiful, I am really so much impressed!'); - $this->expectException(\OCP\Comments\NotFoundException::class); + $this->expectException(NotFoundException::class); $manager->save($comment); } @@ -652,10 +652,10 @@ class ManagerTest extends TestCase { } public function testDeleteReferencesOfActorWithUserManagement(): void { - $user = \OCP\Server::get(IUserManager::class)->createUser('xenia', 'NotAnEasyPassword123456+'); + $user = Server::get(IUserManager::class)->createUser('xenia', 'NotAnEasyPassword123456+'); $this->assertInstanceOf(IUser::class, $user); - $manager = \OCP\Server::get(ICommentsManager::class); + $manager = Server::get(ICommentsManager::class); $comment = $manager->create('users', $user->getUID(), 'files', 'file64'); $comment ->setMessage('Most important comment I ever left on the Internet.') @@ -2425,7 +2425,7 @@ class ManagerTest extends TestCase { $expected = array_combine($keys, $expected); if ($notFound) { - $this->expectException(\OCP\Comments\NotFoundException::class); + $this->expectException(NotFoundException::class); } $comment = $processedComments[$expected['message'] . '#' . $expected['actorId']]; $actual = $manager->getReactionComment((int)$comment->getParentId(), $comment->getActorType(), $comment->getActorId(), $comment->getMessage()); diff --git a/tests/lib/Config/LexiconTest.php b/tests/lib/Config/LexiconTest.php index 5bcd3509b22..e9b763b1799 100644 --- a/tests/lib/Config/LexiconTest.php +++ b/tests/lib/Config/LexiconTest.php @@ -31,7 +31,7 @@ class LexiconTest extends TestCase { protected function setUp(): void { parent::setUp(); - $bootstrapCoordinator = \OCP\Server::get(Coordinator::class); + $bootstrapCoordinator = Server::get(Coordinator::class); $bootstrapCoordinator->getRegistrationContext()?->registerConfigLexicon(TestConfigLexicon_I::APPID, TestConfigLexicon_I::class); $bootstrapCoordinator->getRegistrationContext()?->registerConfigLexicon(TestConfigLexicon_N::APPID, TestConfigLexicon_N::class); $bootstrapCoordinator->getRegistrationContext()?->registerConfigLexicon(TestConfigLexicon_W::APPID, TestConfigLexicon_W::class); diff --git a/tests/lib/Config/UserConfigTest.php b/tests/lib/Config/UserConfigTest.php index 7bd1e06e297..865575374d8 100644 --- a/tests/lib/Config/UserConfigTest.php +++ b/tests/lib/Config/UserConfigTest.php @@ -15,6 +15,7 @@ use OC\Config\UserConfig; use OCP\IConfig; use OCP\IDBConnection; use OCP\Security\ICrypto; +use OCP\Server; use Psr\Log\LoggerInterface; use Test\TestCase; @@ -170,10 +171,10 @@ class UserConfigTest extends TestCase { protected function setUp(): void { parent::setUp(); - $this->connection = \OCP\Server::get(IDBConnection::class); - $this->config = \OCP\Server::get(IConfig::class); - $this->logger = \OCP\Server::get(LoggerInterface::class); - $this->crypto = \OCP\Server::get(ICrypto::class); + $this->connection = Server::get(IDBConnection::class); + $this->config = Server::get(IConfig::class); + $this->logger = Server::get(LoggerInterface::class); + $this->crypto = Server::get(ICrypto::class); // storing current preferences and emptying the data table $sql = $this->connection->getQueryBuilder(); @@ -278,7 +279,7 @@ class UserConfigTest extends TestCase { * @return IUserConfig */ private function generateUserConfig(array $preLoading = []): IUserConfig { - $userConfig = new \OC\Config\UserConfig( + $userConfig = new UserConfig( $this->connection, $this->config, $this->logger, diff --git a/tests/lib/ConfigTest.php b/tests/lib/ConfigTest.php index 3be066c6839..89135e0cffd 100644 --- a/tests/lib/ConfigTest.php +++ b/tests/lib/ConfigTest.php @@ -8,6 +8,8 @@ namespace Test; use OC\Config; +use OCP\ITempManager; +use OCP\Server; class ConfigTest extends TestCase { public const TESTCONTENT = '<?php $CONFIG=array("foo"=>"bar", "beers" => array("Appenzeller", "Guinness", "Kölsch"), "alcohol_free" => false);'; @@ -22,7 +24,7 @@ class ConfigTest extends TestCase { protected function setUp(): void { parent::setUp(); - $this->randomTmpDir = \OC::$server->getTempManager()->getTemporaryFolder(); + $this->randomTmpDir = Server::get(ITempManager::class)->getTemporaryFolder(); $this->configFile = $this->randomTmpDir . 'testconfig.php'; file_put_contents($this->configFile, self::TESTCONTENT); } @@ -33,7 +35,7 @@ class ConfigTest extends TestCase { } private function getConfig(): Config { - return new \OC\Config($this->randomTmpDir, 'testconfig.php'); + return new Config($this->randomTmpDir, 'testconfig.php'); } public function testGetKeys(): void { @@ -159,7 +161,7 @@ class ConfigTest extends TestCase { file_put_contents($additionalConfigPath, $additionalConfig); // Reinstantiate the config to force a read-in of the additional configs - $config = new \OC\Config($this->randomTmpDir, 'testconfig.php'); + $config = new Config($this->randomTmpDir, 'testconfig.php'); // Ensure that the config value can be read and the config has not been modified $this->assertSame('totallyOutdated', $config->getValue('php53', 'bogusValue')); diff --git a/tests/lib/Contacts/ContactsMenu/Providers/LocalTimeProviderTest.php b/tests/lib/Contacts/ContactsMenu/Providers/LocalTimeProviderTest.php index 7b1e6249832..198ec6c672e 100644 --- a/tests/lib/Contacts/ContactsMenu/Providers/LocalTimeProviderTest.php +++ b/tests/lib/Contacts/ContactsMenu/Providers/LocalTimeProviderTest.php @@ -47,15 +47,15 @@ class LocalTimeProviderTest extends TestCase { $this->l = $this->createMock(IL10N::class); $this->l->expects($this->any()) ->method('t') - ->will($this->returnCallback(function ($text, $parameters = []) { + ->willReturnCallback(function ($text, $parameters = []) { return vsprintf($text, $parameters); - })); + }); $this->l->expects($this->any()) ->method('n') - ->will($this->returnCallback(function ($text, $textPlural, $n, $parameters = []) { + ->willReturnCallback(function ($text, $textPlural, $n, $parameters = []) { $formatted = str_replace('%n', (string)$n, $n === 1 ? $text : $textPlural); return vsprintf($formatted, $parameters); - })); + }); $this->urlGenerator = $this->createMock(IURLGenerator::class); $this->userManager = $this->createMock(IUserManager::class); $this->timeFactory = $this->createMock(ITimeFactory::class); diff --git a/tests/lib/ContactsManagerTest.php b/tests/lib/ContactsManagerTest.php index 6fea6b39e92..5f7e65312f2 100644 --- a/tests/lib/ContactsManagerTest.php +++ b/tests/lib/ContactsManagerTest.php @@ -6,6 +6,8 @@ */ namespace Test; +use OC\ContactsManager; +use OCP\Constants; use OCP\IAddressBook; class ContactsManagerTest extends \Test\TestCase { @@ -14,7 +16,7 @@ class ContactsManagerTest extends \Test\TestCase { protected function setUp(): void { parent::setUp(); - $this->cm = new \OC\ContactsManager(); + $this->cm = new ContactsManager(); } public static function searchProvider(): array { @@ -153,7 +155,7 @@ class ContactsManagerTest extends \Test\TestCase { $addressbook->expects($this->any()) ->method('getPermissions') - ->willReturn(\OCP\Constants::PERMISSION_ALL); + ->willReturn(Constants::PERMISSION_ALL); $addressbook->expects($this->once()) ->method('delete') @@ -176,7 +178,7 @@ class ContactsManagerTest extends \Test\TestCase { $addressbook->expects($this->any()) ->method('getPermissions') - ->willReturn(\OCP\Constants::PERMISSION_READ); + ->willReturn(Constants::PERMISSION_READ); $addressbook->expects($this->never()) ->method('delete'); @@ -216,7 +218,7 @@ class ContactsManagerTest extends \Test\TestCase { $addressbook->expects($this->any()) ->method('getPermissions') - ->willReturn(\OCP\Constants::PERMISSION_ALL); + ->willReturn(Constants::PERMISSION_ALL); $addressbook->expects($this->once()) ->method('createOrUpdate') @@ -239,7 +241,7 @@ class ContactsManagerTest extends \Test\TestCase { $addressbook->expects($this->any()) ->method('getPermissions') - ->willReturn(\OCP\Constants::PERMISSION_READ); + ->willReturn(Constants::PERMISSION_READ); $addressbook->expects($this->never()) ->method('createOrUpdate'); diff --git a/tests/lib/DB/AdapterTest.php b/tests/lib/DB/AdapterTest.php index 99b7cf4e099..2fc7c5089a3 100644 --- a/tests/lib/DB/AdapterTest.php +++ b/tests/lib/DB/AdapterTest.php @@ -6,6 +6,8 @@ namespace Test\DB; +use OCP\IDBConnection; +use OCP\Server; use Test\TestCase; class AdapterTest extends TestCase { @@ -13,7 +15,7 @@ class AdapterTest extends TestCase { private $connection; public function setUp(): void { - $this->connection = \OC::$server->getDatabaseConnection(); + $this->connection = Server::get(IDBConnection::class); $this->appId = uniqid('test_db_adapter', true); } diff --git a/tests/lib/DB/MigrationsTest.php b/tests/lib/DB/MigrationsTest.php index f5379b30be9..6a730d5290c 100644 --- a/tests/lib/DB/MigrationsTest.php +++ b/tests/lib/DB/MigrationsTest.php @@ -234,7 +234,7 @@ class MigrationsTest extends \Test\TestCase { ]; $this->migrationService->expects($this->exactly(2)) ->method('executeStep') - ->willReturnCallback(function () use (&$calls) { + ->willReturnCallback(function () use (&$calls): void { $expected = array_shift($calls); $this->assertEquals($expected, func_get_args()); }); diff --git a/tests/lib/DB/MigratorTest.php b/tests/lib/DB/MigratorTest.php index 46724afee86..26b0e000cf6 100644 --- a/tests/lib/DB/MigratorTest.php +++ b/tests/lib/DB/MigratorTest.php @@ -16,8 +16,10 @@ use OC\DB\Migrator; use OC\DB\OracleMigrator; use OC\DB\SQLiteMigrator; use OCP\DB\Types; +use OCP\EventDispatcher\IEventDispatcher; use OCP\IConfig; use OCP\IDBConnection; +use OCP\Server; /** * Class MigratorTest @@ -46,15 +48,15 @@ class MigratorTest extends \Test\TestCase { protected function setUp(): void { parent::setUp(); - $this->config = \OC::$server->getConfig(); - $this->connection = \OC::$server->get(\OC\DB\Connection::class); + $this->config = Server::get(IConfig::class); + $this->connection = Server::get(\OC\DB\Connection::class); $this->tableName = $this->getUniqueTableName(); $this->tableNameTmp = $this->getUniqueTableName(); } private function getMigrator(): Migrator { - $dispatcher = \OC::$server->get(\OCP\EventDispatcher\IEventDispatcher::class); + $dispatcher = Server::get(IEventDispatcher::class); if ($this->connection->getDatabaseProvider() === IDBConnection::PLATFORM_SQLITE) { return new SQLiteMigrator($this->connection, $this->config, $dispatcher); } elseif ($this->connection->getDatabaseProvider() === IDBConnection::PLATFORM_ORACLE) { diff --git a/tests/lib/DB/QueryBuilder/ExpressionBuilderDBTest.php b/tests/lib/DB/QueryBuilder/ExpressionBuilderDBTest.php index dc0bca9be95..87fc4273dde 100644 --- a/tests/lib/DB/QueryBuilder/ExpressionBuilderDBTest.php +++ b/tests/lib/DB/QueryBuilder/ExpressionBuilderDBTest.php @@ -26,12 +26,12 @@ class ExpressionBuilderDBTest extends TestCase { protected function setUp(): void { parent::setUp(); - $this->connection = \OC::$server->getDatabaseConnection(); + $this->connection = Server::get(IDBConnection::class); $this->prepareTestingTable(); } public static function likeProvider(): array { - $connection = \OCP\Server::get(IDBConnection::class); + $connection = Server::get(IDBConnection::class); return [ ['foo', 'bar', false], @@ -67,7 +67,7 @@ class ExpressionBuilderDBTest extends TestCase { } public static function ilikeProvider(): array { - $connection = \OCP\Server::get(IDBConnection::class); + $connection = Server::get(IDBConnection::class); return [ ['foo', 'bar', false], diff --git a/tests/lib/DB/QueryBuilder/ExpressionBuilderTest.php b/tests/lib/DB/QueryBuilder/ExpressionBuilderTest.php index ab3d1a5081f..aa6428b0ca8 100644 --- a/tests/lib/DB/QueryBuilder/ExpressionBuilderTest.php +++ b/tests/lib/DB/QueryBuilder/ExpressionBuilderTest.php @@ -10,6 +10,8 @@ namespace Test\DB\QueryBuilder; use Doctrine\DBAL\Query\Expression\ExpressionBuilder as DoctrineExpressionBuilder; use OC\DB\QueryBuilder\ExpressionBuilder\ExpressionBuilder; use OCP\DB\QueryBuilder\IQueryBuilder; +use OCP\IDBConnection; +use OCP\Server; use Psr\Log\LoggerInterface; use Test\TestCase; @@ -39,8 +41,8 @@ class ExpressionBuilderTest extends TestCase { protected function setUp(): void { parent::setUp(); - $this->connection = \OC::$server->getDatabaseConnection(); - $this->internalConnection = \OC::$server->get(\OC\DB\Connection::class); + $this->connection = Server::get(IDBConnection::class); + $this->internalConnection = Server::get(\OC\DB\Connection::class); $this->logger = $this->createMock(LoggerInterface::class); $queryBuilder = $this->createMock(IQueryBuilder::class); diff --git a/tests/lib/DB/QueryBuilder/FunctionBuilderTest.php b/tests/lib/DB/QueryBuilder/FunctionBuilderTest.php index 682aedc9ff7..6dc57879dd7 100644 --- a/tests/lib/DB/QueryBuilder/FunctionBuilderTest.php +++ b/tests/lib/DB/QueryBuilder/FunctionBuilderTest.php @@ -8,6 +8,8 @@ namespace Test\DB\QueryBuilder; use OC\DB\QueryBuilder\Literal; use OCP\DB\QueryBuilder\IQueryBuilder; +use OCP\IDBConnection; +use OCP\Server; use Test\TestCase; /** @@ -24,7 +26,7 @@ class FunctionBuilderTest extends TestCase { protected function setUp(): void { parent::setUp(); - $this->connection = \OC::$server->getDatabaseConnection(); + $this->connection = Server::get(IDBConnection::class); } /** diff --git a/tests/lib/DB/QueryBuilder/QueryBuilderTest.php b/tests/lib/DB/QueryBuilder/QueryBuilderTest.php index 20086335198..05913b87e4e 100644 --- a/tests/lib/DB/QueryBuilder/QueryBuilderTest.php +++ b/tests/lib/DB/QueryBuilder/QueryBuilderTest.php @@ -17,6 +17,7 @@ use OCP\DB\IResult; use OCP\DB\QueryBuilder\IQueryBuilder; use OCP\DB\QueryBuilder\IQueryFunction; use OCP\IDBConnection; +use OCP\Server; use Psr\Log\LoggerInterface; /** @@ -42,7 +43,7 @@ class QueryBuilderTest extends \Test\TestCase { protected function setUp(): void { parent::setUp(); - $this->connection = \OC::$server->getDatabaseConnection(); + $this->connection = Server::get(IDBConnection::class); $this->config = $this->createMock(SystemConfig::class); $this->logger = $this->createMock(LoggerInterface::class); $this->queryBuilder = new QueryBuilder($this->connection, $this->config, $this->logger); @@ -164,7 +165,7 @@ class QueryBuilderTest extends \Test\TestCase { public function dataSelect(): array { $config = $this->createMock(SystemConfig::class); $logger = $this->createMock(LoggerInterface::class); - $queryBuilder = new QueryBuilder(\OC::$server->getDatabaseConnection(), $config, $logger); + $queryBuilder = new QueryBuilder(Server::get(IDBConnection::class), $config, $logger); return [ // select('column1') [['configvalue'], ['configvalue' => '99']], @@ -232,7 +233,7 @@ class QueryBuilderTest extends \Test\TestCase { public function dataSelectAlias(): array { $config = $this->createMock(SystemConfig::class); $logger = $this->createMock(LoggerInterface::class); - $queryBuilder = new QueryBuilder(\OC::$server->getDatabaseConnection(), $config, $logger); + $queryBuilder = new QueryBuilder(Server::get(IDBConnection::class), $config, $logger); return [ ['configvalue', 'cv', ['cv' => '99']], [$queryBuilder->expr()->literal('column1'), 'thing', ['thing' => 'column1']], @@ -341,7 +342,7 @@ class QueryBuilderTest extends \Test\TestCase { public function dataAddSelect(): array { $config = $this->createMock(SystemConfig::class); $logger = $this->createMock(LoggerInterface::class); - $queryBuilder = new QueryBuilder(\OC::$server->getDatabaseConnection(), $config, $logger); + $queryBuilder = new QueryBuilder(Server::get(IDBConnection::class), $config, $logger); return [ // addSelect('column1') [['configvalue'], ['appid' => 'testFirstResult', 'configvalue' => '99']], @@ -496,7 +497,7 @@ class QueryBuilderTest extends \Test\TestCase { public function dataFrom(): array { $config = $this->createMock(SystemConfig::class); $logger = $this->createMock(LoggerInterface::class); - $qb = new QueryBuilder(\OC::$server->getDatabaseConnection(), $config, $logger); + $qb = new QueryBuilder(Server::get(IDBConnection::class), $config, $logger); return [ [$qb->createFunction('(' . $qb->select('*')->from('test')->getSQL() . ')'), 'q', null, null, [ ['table' => '(SELECT * FROM `*PREFIX*test`)', 'alias' => '`q`'] @@ -1200,7 +1201,7 @@ class QueryBuilderTest extends \Test\TestCase { public function dataGetTableName(): array { $config = $this->createMock(SystemConfig::class); $logger = $this->createMock(LoggerInterface::class); - $qb = new QueryBuilder(\OC::$server->getDatabaseConnection(), $config, $logger); + $qb = new QueryBuilder(Server::get(IDBConnection::class), $config, $logger); return [ ['*PREFIX*table', null, '`*PREFIX*table`'], ['*PREFIX*table', true, '`*PREFIX*table`'], @@ -1427,7 +1428,7 @@ class QueryBuilderTest extends \Test\TestCase { $this->logger ->expects($this->once()) ->method('error') - ->willReturnCallback(function ($message, $parameters) { + ->willReturnCallback(function ($message, $parameters): void { $this->assertInstanceOf(QueryException::class, $parameters['exception']); $this->assertSame( 'More than 1000 expressions in a list are not allowed on Oracle.', @@ -1462,7 +1463,7 @@ class QueryBuilderTest extends \Test\TestCase { $this->logger ->expects($this->once()) ->method('error') - ->willReturnCallback(function ($message, $parameters) { + ->willReturnCallback(function ($message, $parameters): void { $this->assertInstanceOf(QueryException::class, $parameters['exception']); $this->assertSame( 'The number of parameters must not exceed 65535. Restriction by PostgreSQL.', diff --git a/tests/lib/DateTimeFormatterTest.php b/tests/lib/DateTimeFormatterTest.php index cfab1643beb..84319512f58 100644 --- a/tests/lib/DateTimeFormatterTest.php +++ b/tests/lib/DateTimeFormatterTest.php @@ -7,6 +7,9 @@ namespace Test; +use OC\DateTimeFormatter; +use OCP\Util; + class DateTimeFormatterTest extends TestCase { /** @var \OC\DateTimeFormatter */ protected $formatter; @@ -33,7 +36,7 @@ class DateTimeFormatterTest extends TestCase { protected function setUp(): void { parent::setUp(); - $this->formatter = new \OC\DateTimeFormatter(new \DateTimeZone('UTC'), \OCP\Util::getL10N('lib', 'en')); + $this->formatter = new DateTimeFormatter(new \DateTimeZone('UTC'), Util::getL10N('lib', 'en')); } protected static function getTimestampAgo($time, $seconds = 0, $minutes = 0, $hours = 0, $days = 0, $years = 0) { @@ -42,7 +45,7 @@ class DateTimeFormatterTest extends TestCase { public static function formatTimeSpanData(): array { $time = 1416916800; // Use a fixed timestamp so we don't switch days/years with the getTimestampAgo - $deL10N = \OCP\Util::getL10N('lib', 'de'); + $deL10N = Util::getL10N('lib', 'de'); return [ ['seconds ago', $time, $time], ['in a few seconds', $time + 5 , $time], @@ -83,7 +86,7 @@ class DateTimeFormatterTest extends TestCase { public static function formatDateSpanData(): array { $time = 1416916800; // Use a fixed timestamp so we don't switch days/years with the getTimestampAgo - $deL10N = \OCP\Util::getL10N('lib', 'de'); + $deL10N = Util::getL10N('lib', 'de'); return [ // Normal testing ['today', self::getTimestampAgo($time, 30, 15), $time], diff --git a/tests/lib/DirectEditing/ManagerTest.php b/tests/lib/DirectEditing/ManagerTest.php index e09a87e448e..1b38cfafaa6 100644 --- a/tests/lib/DirectEditing/ManagerTest.php +++ b/tests/lib/DirectEditing/ManagerTest.php @@ -22,6 +22,7 @@ use OCP\IUser; use OCP\IUserSession; use OCP\L10N\IFactory; use OCP\Security\ISecureRandom; +use OCP\Server; use PHPUnit\Framework\MockObject\MockObject; use Test\TestCase; @@ -124,7 +125,7 @@ class ManagerTest extends TestCase { $this->editor = new Editor(); $this->random = $this->createMock(ISecureRandom::class); - $this->connection = \OC::$server->getDatabaseConnection(); + $this->connection = Server::get(IDBConnection::class); $this->userSession = $this->createMock(IUserSession::class); $this->rootFolder = $this->createMock(IRootFolder::class); $this->userFolder = $this->createMock(Folder::class); diff --git a/tests/lib/Encryption/DecryptAllTest.php b/tests/lib/Encryption/DecryptAllTest.php index 7385ff03785..fc8600b9fc6 100644 --- a/tests/lib/Encryption/DecryptAllTest.php +++ b/tests/lib/Encryption/DecryptAllTest.php @@ -217,7 +217,7 @@ class DecryptAllTest extends TestCase { ]; $instance->expects($this->exactly(2)) ->method('decryptUsersFiles') - ->willReturnCallback(function ($user) use (&$calls) { + ->willReturnCallback(function ($user) use (&$calls): void { $expected = array_shift($calls); $this->assertEquals($expected, $user); }); @@ -297,7 +297,7 @@ class DecryptAllTest extends TestCase { ]; $instance->expects($this->exactly(2)) ->method('decryptFile') - ->willReturnCallback(function ($path) use (&$calls) { + ->willReturnCallback(function ($path) use (&$calls): void { $expected = array_shift($calls); $this->assertEquals($expected, $path); }); @@ -387,7 +387,7 @@ class DecryptAllTest extends TestCase { $this->view->expects($this->once()) ->method('copy') ->with($path, $path . '.decrypted.42') - ->willReturnCallback(function () { + ->willReturnCallback(function (): void { throw new DecryptionFailedException(); }); diff --git a/tests/lib/Encryption/Keys/StorageTest.php b/tests/lib/Encryption/Keys/StorageTest.php index bc79c5771ca..348b0ecf10d 100644 --- a/tests/lib/Encryption/Keys/StorageTest.php +++ b/tests/lib/Encryption/Keys/StorageTest.php @@ -589,7 +589,7 @@ class StorageTest extends TestCase { 'user1/files_encryption/backup/test.encryptionModule.1234567', ]; $this->view->expects($this->exactly(2))->method('mkdir') - ->willReturnCallback(function ($path) use (&$calls) { + ->willReturnCallback(function ($path) use (&$calls): void { $expected = array_shift($calls); $this->assertEquals($expected, $path); }); diff --git a/tests/lib/Encryption/ManagerTest.php b/tests/lib/Encryption/ManagerTest.php index 8dd602349b6..c268540d8cd 100644 --- a/tests/lib/Encryption/ManagerTest.php +++ b/tests/lib/Encryption/ManagerTest.php @@ -6,6 +6,8 @@ */ namespace Test\Encryption; +use OC\Encryption\Exceptions\ModuleAlreadyExistsException; +use OC\Encryption\Exceptions\ModuleDoesNotExistsException; use OC\Encryption\Manager; use OC\Encryption\Util; use OC\Files\View; @@ -88,7 +90,7 @@ class ManagerTest extends TestCase { * @depends testModuleRegistration */ public function testModuleReRegistration($manager): void { - $this->expectException(\OC\Encryption\Exceptions\ModuleAlreadyExistsException::class); + $this->expectException(ModuleAlreadyExistsException::class); $this->expectExceptionMessage('Id "ID0" already used by encryption module "TestDummyModule0"'); $this->addNewEncryptionModule($manager, 0); @@ -105,7 +107,7 @@ class ManagerTest extends TestCase { public function testGetEncryptionModuleUnknown(): void { - $this->expectException(\OC\Encryption\Exceptions\ModuleDoesNotExistsException::class); + $this->expectException(ModuleDoesNotExistsException::class); $this->expectExceptionMessage('Module with ID: unknown does not exist.'); $this->config->expects($this->any())->method('getAppValue')->willReturn(true); diff --git a/tests/lib/Encryption/UtilTest.php b/tests/lib/Encryption/UtilTest.php index 68989c55fb0..6f637bdac40 100644 --- a/tests/lib/Encryption/UtilTest.php +++ b/tests/lib/Encryption/UtilTest.php @@ -6,6 +6,7 @@ */ namespace Test\Encryption; +use OC\Encryption\Exceptions\EncryptionHeaderKeyExistsException; use OC\Encryption\Util; use OC\Files\View; use OCP\Encryption\IEncryptionModule; @@ -91,7 +92,7 @@ class UtilTest extends TestCase { public function testCreateHeaderFailed(): void { - $this->expectException(\OC\Encryption\Exceptions\EncryptionHeaderKeyExistsException::class); + $this->expectException(EncryptionHeaderKeyExistsException::class); $header = ['header1' => 1, 'header2' => 2, 'oc_encryption_module' => 'foo']; diff --git a/tests/lib/Files/Cache/CacheTest.php b/tests/lib/Files/Cache/CacheTest.php index 2815003a996..18670300850 100644 --- a/tests/lib/Files/Cache/CacheTest.php +++ b/tests/lib/Files/Cache/CacheTest.php @@ -11,13 +11,18 @@ use OC\Files\Cache\Cache; use OC\Files\Cache\CacheEntry; use OC\Files\Search\SearchComparison; use OC\Files\Search\SearchQuery; +use OC\Files\Storage\Temporary; +use OC\User\User; use OCP\EventDispatcher\IEventDispatcher; use OCP\Files\Cache\ICacheEntry; use OCP\Files\Search\ISearchComparison; use OCP\IDBConnection; +use OCP\ITagManager; use OCP\IUser; +use OCP\IUserManager; +use OCP\Server; -class LongId extends \OC\Files\Storage\Temporary { +class LongId extends Temporary { public function getId(): string { return 'long:' . str_repeat('foo', 50) . parent::getId(); } @@ -52,10 +57,10 @@ class CacheTest extends \Test\TestCase { protected function setUp(): void { parent::setUp(); - $this->storage = new \OC\Files\Storage\Temporary([]); - $this->storage2 = new \OC\Files\Storage\Temporary([]); - $this->cache = new \OC\Files\Cache\Cache($this->storage); - $this->cache2 = new \OC\Files\Cache\Cache($this->storage2); + $this->storage = new Temporary([]); + $this->storage2 = new Temporary([]); + $this->cache = new Cache($this->storage); + $this->cache2 = new Cache($this->storage2); $this->cache->insert('', ['size' => 0, 'mtime' => 0, 'mimetype' => ICacheEntry::DIRECTORY_MIMETYPE]); $this->cache2->insert('', ['size' => 0, 'mtime' => 0, 'mimetype' => ICacheEntry::DIRECTORY_MIMETYPE]); } @@ -162,8 +167,8 @@ class CacheTest extends \Test\TestCase { public function testFolder($folder): void { if (strpos($folder, 'F09F9890')) { // 4 byte UTF doesn't work on mysql - $params = \OC::$server->get(\OC\DB\Connection::class)->getParams(); - if (\OC::$server->getDatabaseConnection()->getDatabaseProvider() === IDBConnection::PLATFORM_MYSQL && $params['charset'] !== 'utf8mb4') { + $params = Server::get(\OC\DB\Connection::class)->getParams(); + if (Server::get(IDBConnection::class)->getDatabaseProvider() === IDBConnection::PLATFORM_MYSQL && $params['charset'] !== 'utf8mb4') { $this->markTestSkipped('MySQL doesn\'t support 4 byte UTF-8'); } } @@ -311,13 +316,13 @@ class CacheTest extends \Test\TestCase { } public function testStatus(): void { - $this->assertEquals(\OC\Files\Cache\Cache::NOT_FOUND, $this->cache->getStatus('foo')); + $this->assertEquals(Cache::NOT_FOUND, $this->cache->getStatus('foo')); $this->cache->put('foo', ['size' => -1]); - $this->assertEquals(\OC\Files\Cache\Cache::PARTIAL, $this->cache->getStatus('foo')); + $this->assertEquals(Cache::PARTIAL, $this->cache->getStatus('foo')); $this->cache->put('foo', ['size' => -1, 'mtime' => 20, 'mimetype' => 'foo/file']); - $this->assertEquals(\OC\Files\Cache\Cache::SHALLOW, $this->cache->getStatus('foo')); + $this->assertEquals(Cache::SHALLOW, $this->cache->getStatus('foo')); $this->cache->put('foo', ['size' => 10]); - $this->assertEquals(\OC\Files\Cache\Cache::COMPLETE, $this->cache->getStatus('foo')); + $this->assertEquals(Cache::COMPLETE, $this->cache->getStatus('foo')); } public static function putWithAllKindOfQuotesData(): array { @@ -333,7 +338,7 @@ class CacheTest extends \Test\TestCase { * @param $fileName */ public function testPutWithAllKindOfQuotes($fileName): void { - $this->assertEquals(\OC\Files\Cache\Cache::NOT_FOUND, $this->cache->get($fileName)); + $this->assertEquals(Cache::NOT_FOUND, $this->cache->get($fileName)); $this->cache->put($fileName, ['size' => 20, 'mtime' => 25, 'mimetype' => 'foo/file', 'etag' => $fileName]); $cacheEntry = $this->cache->get($fileName); @@ -371,9 +376,9 @@ class CacheTest extends \Test\TestCase { public function testSearchQueryByTag(): void { $userId = static::getUniqueID('user'); - \OC::$server->getUserManager()->createUser($userId, $userId); + Server::get(IUserManager::class)->createUser($userId, $userId); static::loginAsUser($userId); - $user = new \OC\User\User($userId, null, \OC::$server->get(IEventDispatcher::class)); + $user = new User($userId, null, Server::get(IEventDispatcher::class)); $file1 = 'folder'; $file2 = 'folder/foobar'; @@ -393,7 +398,7 @@ class CacheTest extends \Test\TestCase { $id4 = $this->cache->put($file4, $fileData['foo2']); $id5 = $this->cache->put($file5, $fileData['foo3']); - $tagManager = \OCP\Server::get(\OCP\ITagManager::class)->load('files', [], false, $userId); + $tagManager = Server::get(ITagManager::class)->load('files', [], false, $userId); $this->assertTrue($tagManager->tagAs($id1, 'tag1')); $this->assertTrue($tagManager->tagAs($id1, 'tag2')); $this->assertTrue($tagManager->tagAs($id2, 'tag2')); @@ -418,7 +423,7 @@ class CacheTest extends \Test\TestCase { $tagManager->delete('tag2'); static::logout(); - $user = \OC::$server->getUserManager()->get($userId); + $user = Server::get(IUserManager::class)->get($userId); if ($user !== null) { try { $user->delete(); @@ -550,7 +555,7 @@ class CacheTest extends \Test\TestCase { if (strlen($storageId) > 64) { $storageId = md5($storageId); } - $this->assertEquals([$storageId, 'foo'], \OC\Files\Cache\Cache::getById($id)); + $this->assertEquals([$storageId, 'foo'], Cache::getById($id)); } public function testStorageMTime(): void { @@ -577,7 +582,7 @@ class CacheTest extends \Test\TestCase { $storageId = $storage->getId(); $data = ['size' => 1000, 'mtime' => 20, 'mimetype' => 'foo/file']; $id = $cache->put('foo', $data); - $this->assertEquals([md5($storageId), 'foo'], \OC\Files\Cache\Cache::getById($id)); + $this->assertEquals([md5($storageId), 'foo'], Cache::getById($id)); } /** diff --git a/tests/lib/Files/Cache/HomeCacheTest.php b/tests/lib/Files/Cache/HomeCacheTest.php index ad069de1fef..5130ad2730a 100644 --- a/tests/lib/Files/Cache/HomeCacheTest.php +++ b/tests/lib/Files/Cache/HomeCacheTest.php @@ -7,24 +7,20 @@ namespace Test\Files\Cache; -class DummyUser extends \OC\User\User { - /** - * @var string $home - */ - private $home; - - /** - * @var string $uid - */ - private $uid; +use OC\Files\Storage\Home; +use OC\User\User; +use OCP\ITempManager; +use OCP\Server; +class DummyUser extends User { /** * @param string $uid * @param string $home */ - public function __construct($uid, $home) { - $this->home = $home; - $this->uid = $uid; + public function __construct( + private $uid, + private $home, + ) { } /** @@ -68,8 +64,8 @@ class HomeCacheTest extends \Test\TestCase { protected function setUp(): void { parent::setUp(); - $this->user = new DummyUser('foo', \OC::$server->getTempManager()->getTemporaryFolder()); - $this->storage = new \OC\Files\Storage\Home(['user' => $this->user]); + $this->user = new DummyUser('foo', Server::get(ITempManager::class)->getTemporaryFolder()); + $this->storage = new Home(['user' => $this->user]); $this->cache = $this->storage->getCache(); } diff --git a/tests/lib/Files/Cache/LocalRootScannerTest.php b/tests/lib/Files/Cache/LocalRootScannerTest.php index e683283b7e1..727da2ed698 100644 --- a/tests/lib/Files/Cache/LocalRootScannerTest.php +++ b/tests/lib/Files/Cache/LocalRootScannerTest.php @@ -9,6 +9,8 @@ declare(strict_types=1); namespace Test\Files\Cache; use OC\Files\Storage\LocalRootStorage; +use OCP\ITempManager; +use OCP\Server; use Test\TestCase; /** @@ -21,7 +23,7 @@ class LocalRootScannerTest extends TestCase { protected function setUp(): void { parent::setUp(); - $folder = \OC::$server->getTempManager()->getTemporaryFolder(); + $folder = Server::get(ITempManager::class)->getTemporaryFolder(); $this->storage = new LocalRootStorage(['datadir' => $folder]); } diff --git a/tests/lib/Files/Cache/MoveFromCacheTraitTest.php b/tests/lib/Files/Cache/MoveFromCacheTraitTest.php index e8a6c8acf32..fc36a10892a 100644 --- a/tests/lib/Files/Cache/MoveFromCacheTraitTest.php +++ b/tests/lib/Files/Cache/MoveFromCacheTraitTest.php @@ -7,10 +7,12 @@ namespace Test\Files\Cache; +use OC\Files\Cache\Cache; use OC\Files\Cache\MoveFromCacheTrait; +use OC\Files\Storage\Temporary; use OCP\Files\Cache\ICacheEntry; -class FallBackCrossCacheMoveCache extends \OC\Files\Cache\Cache { +class FallBackCrossCacheMoveCache extends Cache { use MoveFromCacheTrait; } @@ -23,8 +25,8 @@ class MoveFromCacheTraitTest extends CacheTest { protected function setUp(): void { parent::setUp(); - $this->storage = new \OC\Files\Storage\Temporary([]); - $this->storage2 = new \OC\Files\Storage\Temporary([]); + $this->storage = new Temporary([]); + $this->storage2 = new Temporary([]); $this->cache = new FallBackCrossCacheMoveCache($this->storage); $this->cache2 = new FallBackCrossCacheMoveCache($this->storage2); diff --git a/tests/lib/Files/Cache/ScannerTest.php b/tests/lib/Files/Cache/ScannerTest.php index dc5ba5d3cdf..0502cd3717a 100644 --- a/tests/lib/Files/Cache/ScannerTest.php +++ b/tests/lib/Files/Cache/ScannerTest.php @@ -14,6 +14,8 @@ use OC\Files\Cache\Scanner; use OC\Files\Storage\Storage; use OC\Files\Storage\Temporary; use OCP\Files\Cache\IScanner; +use OCP\IDBConnection; +use OCP\Server; use Test\TestCase; /** @@ -67,7 +69,7 @@ class ScannerTest extends TestCase { $data = "dummy file data\n"; $this->storage->file_put_contents('foo🙈.txt', $data); - if (OC::$server->getDatabaseConnection()->supports4ByteText()) { + if (Server::get(IDBConnection::class)->supports4ByteText()) { $this->assertNotNull($this->scanner->scanFile('foo🙈.txt')); $this->assertTrue($this->cache->inCache('foo🙈.txt'), true); @@ -337,7 +339,7 @@ class ScannerTest extends TestCase { $oldFolderId = $this->cache->getId('folder'); // delete the folder without removing the children - $query = OC::$server->getDatabaseConnection()->getQueryBuilder(); + $query = Server::get(IDBConnection::class)->getQueryBuilder(); $query->delete('filecache') ->where($query->expr()->eq('fileid', $query->createNamedParameter($oldFolderId))); $query->execute(); @@ -363,7 +365,7 @@ class ScannerTest extends TestCase { $oldFolderId = $this->cache->getId('folder'); // delete the folder without removing the children - $query = OC::$server->getDatabaseConnection()->getQueryBuilder(); + $query = Server::get(IDBConnection::class)->getQueryBuilder(); $query->delete('filecache') ->where($query->expr()->eq('fileid', $query->createNamedParameter($oldFolderId))); $query->execute(); diff --git a/tests/lib/Files/Cache/SearchBuilderTest.php b/tests/lib/Files/Cache/SearchBuilderTest.php index 28af199639a..957cf6c9f42 100644 --- a/tests/lib/Files/Cache/SearchBuilderTest.php +++ b/tests/lib/Files/Cache/SearchBuilderTest.php @@ -16,6 +16,8 @@ use OCP\Files\Search\ISearchBinaryOperator; use OCP\Files\Search\ISearchComparison; use OCP\Files\Search\ISearchOperator; use OCP\FilesMetadata\IFilesMetadataManager; +use OCP\IDBConnection; +use OCP\Server; use Test\TestCase; /** @@ -39,7 +41,7 @@ class SearchBuilderTest extends TestCase { protected function setUp(): void { parent::setUp(); - $this->builder = \OC::$server->getDatabaseConnection()->getQueryBuilder(); + $this->builder = Server::get(IDBConnection::class)->getQueryBuilder(); $this->mimetypeLoader = $this->createMock(IMimeTypeLoader::class); $this->filesMetadataManager = $this->createMock(IFilesMetadataManager::class); @@ -76,7 +78,7 @@ class SearchBuilderTest extends TestCase { protected function tearDown(): void { parent::tearDown(); - $builder = \OC::$server->getDatabaseConnection()->getQueryBuilder(); + $builder = Server::get(IDBConnection::class)->getQueryBuilder(); $builder->delete('filecache') ->where($builder->expr()->eq('storage', $builder->createNamedParameter($this->numericStorageId, IQueryBuilder::PARAM_INT))); @@ -109,7 +111,7 @@ class SearchBuilderTest extends TestCase { $data['mimetype'] = 1; } - $builder = \OC::$server->getDatabaseConnection()->getQueryBuilder(); + $builder = Server::get(IDBConnection::class)->getQueryBuilder(); $values = []; foreach ($data as $key => $value) { diff --git a/tests/lib/Files/Cache/UpdaterLegacyTest.php b/tests/lib/Files/Cache/UpdaterLegacyTest.php index 0f7e9d78d77..5d1abb46c0d 100644 --- a/tests/lib/Files/Cache/UpdaterLegacyTest.php +++ b/tests/lib/Files/Cache/UpdaterLegacyTest.php @@ -8,8 +8,11 @@ namespace Test\Files\Cache; use OC\Files\Filesystem as Filesystem; +use OC\Files\Storage\Temporary; use OC\Files\View; use OCP\Files\Mount\IMountManager; +use OCP\IUserManager; +use OCP\Server; /** * Class UpdaterLegacyTest @@ -39,7 +42,7 @@ class UpdaterLegacyTest extends \Test\TestCase { protected function setUp(): void { parent::setUp(); - $this->storage = new \OC\Files\Storage\Temporary([]); + $this->storage = new Temporary([]); $textData = "dummy file data\n"; $imgData = file_get_contents(\OC::$SERVERROOT . '/core/img/logo/logo.png'); $this->storage->mkdir('folder'); @@ -56,13 +59,13 @@ class UpdaterLegacyTest extends \Test\TestCase { self::$user = $this->getUniqueID(); } - \OC::$server->getUserManager()->createUser(self::$user, 'NotAnEasyPassword123456+'); + Server::get(IUserManager::class)->createUser(self::$user, 'NotAnEasyPassword123456+'); $this->loginAsUser(self::$user); Filesystem::init(self::$user, '/' . self::$user . '/files'); /** @var IMountManager $manager */ - $manager = \OC::$server->get(IMountManager::class); + $manager = Server::get(IMountManager::class); $manager->removeMount('/' . self::$user); Filesystem::mount($this->storage, [], '/' . self::$user . '/files'); @@ -76,7 +79,7 @@ class UpdaterLegacyTest extends \Test\TestCase { } $result = false; - $user = \OC::$server->getUserManager()->get(self::$user); + $user = Server::get(IUserManager::class)->get(self::$user); if ($user !== null) { $result = $user->delete(); } @@ -122,7 +125,7 @@ class UpdaterLegacyTest extends \Test\TestCase { } public function testWriteWithMountPoints(): void { - $storage2 = new \OC\Files\Storage\Temporary([]); + $storage2 = new Temporary([]); $storage2->getScanner()->scan(''); //initialize etags $cache2 = $storage2->getCache(); Filesystem::mount($storage2, [], '/' . self::$user . '/files/folder/substorage'); @@ -183,7 +186,7 @@ class UpdaterLegacyTest extends \Test\TestCase { } public function testDeleteWithMountPoints(): void { - $storage2 = new \OC\Files\Storage\Temporary([]); + $storage2 = new Temporary([]); $cache2 = $storage2->getCache(); Filesystem::mount($storage2, [], '/' . self::$user . '/files/folder/substorage'); Filesystem::file_put_contents('folder/substorage/foo.txt', 'asd'); @@ -239,7 +242,7 @@ class UpdaterLegacyTest extends \Test\TestCase { } public function testRenameWithMountPoints(): void { - $storage2 = new \OC\Files\Storage\Temporary([]); + $storage2 = new Temporary([]); $cache2 = $storage2->getCache(); Filesystem::mount($storage2, [], '/' . self::$user . '/files/folder/substorage'); Filesystem::file_put_contents('folder/substorage/foo.txt', 'asd'); diff --git a/tests/lib/Files/Cache/WatcherTest.php b/tests/lib/Files/Cache/WatcherTest.php index 7319aa9b68d..c086fb3206d 100644 --- a/tests/lib/Files/Cache/WatcherTest.php +++ b/tests/lib/Files/Cache/WatcherTest.php @@ -7,6 +7,9 @@ namespace Test\Files\Cache; +use OC\Files\Cache\Watcher; +use OC\Files\Storage\Temporary; + /** * Class WatcherTest * @@ -44,7 +47,7 @@ class WatcherTest extends \Test\TestCase { $storage = $this->getTestStorage(); $cache = $storage->getCache(); $updater = $storage->getWatcher(); - $updater->setPolicy(\OC\Files\Cache\Watcher::CHECK_ONCE); + $updater->setPolicy(Watcher::CHECK_ONCE); //set the mtime to the past so it can detect an mtime change $cache->put('', ['storage_mtime' => 10]); @@ -85,7 +88,7 @@ class WatcherTest extends \Test\TestCase { $storage = $this->getTestStorage(); $cache = $storage->getCache(); $updater = $storage->getWatcher(); - $updater->setPolicy(\OC\Files\Cache\Watcher::CHECK_ONCE); + $updater->setPolicy(Watcher::CHECK_ONCE); //set the mtime to the past so it can detect an mtime change $cache->put('', ['storage_mtime' => 10]); @@ -102,7 +105,7 @@ class WatcherTest extends \Test\TestCase { $storage = $this->getTestStorage(); $cache = $storage->getCache(); $updater = $storage->getWatcher(); - $updater->setPolicy(\OC\Files\Cache\Watcher::CHECK_ONCE); + $updater->setPolicy(Watcher::CHECK_ONCE); //set the mtime to the past so it can detect an mtime change $cache->put('foo.txt', ['storage_mtime' => 10]); @@ -124,7 +127,7 @@ class WatcherTest extends \Test\TestCase { //set the mtime to the past so it can detect an mtime change $cache->put('foo.txt', ['storage_mtime' => 10]); - $updater->setPolicy(\OC\Files\Cache\Watcher::CHECK_NEVER); + $updater->setPolicy(Watcher::CHECK_NEVER); $storage->file_put_contents('foo.txt', 'q'); $this->assertFalse($updater->checkUpdate('foo.txt')); @@ -142,7 +145,7 @@ class WatcherTest extends \Test\TestCase { //set the mtime to the past so it can detect an mtime change $cache->put('foo.txt', ['storage_mtime' => 10]); - $updater->setPolicy(\OC\Files\Cache\Watcher::CHECK_ONCE); + $updater->setPolicy(Watcher::CHECK_ONCE); $storage->file_put_contents('foo.txt', 'q'); $this->assertTrue($updater->checkUpdate('foo.txt')); @@ -160,7 +163,7 @@ class WatcherTest extends \Test\TestCase { //set the mtime to the past so it can detect an mtime change $cache->put('foo.txt', ['storage_mtime' => 10]); - $updater->setPolicy(\OC\Files\Cache\Watcher::CHECK_ALWAYS); + $updater->setPolicy(Watcher::CHECK_ALWAYS); $storage->file_put_contents('foo.txt', 'q'); $this->assertTrue($updater->checkUpdate('foo.txt')); @@ -175,7 +178,7 @@ class WatcherTest extends \Test\TestCase { * @return \OC\Files\Storage\Storage */ private function getTestStorage($scan = true) { - $storage = new \OC\Files\Storage\Temporary([]); + $storage = new Temporary([]); $textData = "dummy file data\n"; $imgData = file_get_contents(\OC::$SERVERROOT . '/core/img/logo/logo.png'); $storage->mkdir('folder'); diff --git a/tests/lib/Files/Cache/Wrapper/CacheJailTest.php b/tests/lib/Files/Cache/Wrapper/CacheJailTest.php index 57024e2eb79..4073f3b9bae 100644 --- a/tests/lib/Files/Cache/Wrapper/CacheJailTest.php +++ b/tests/lib/Files/Cache/Wrapper/CacheJailTest.php @@ -35,7 +35,7 @@ class CacheJailTest extends CacheTest { parent::setUp(); $this->storage->mkdir('jail'); $this->sourceCache = $this->cache; - $this->cache = new \OC\Files\Cache\Wrapper\CacheJail($this->sourceCache, 'jail'); + $this->cache = new CacheJail($this->sourceCache, 'jail'); $this->cache->insert('', ['size' => 0, 'mtime' => 0, 'mimetype' => ICacheEntry::DIRECTORY_MIMETYPE]); } @@ -130,7 +130,7 @@ class CacheJailTest extends CacheTest { $this->assertEquals('bar', $path); // path from jailed '' of foo/bar is foo/bar - $this->cache = new \OC\Files\Cache\Wrapper\CacheJail($this->sourceCache, ''); + $this->cache = new CacheJail($this->sourceCache, ''); $path = $this->cache->getPathById($id); $this->assertEquals('jail/bar', $path); } @@ -200,7 +200,7 @@ class CacheJailTest extends CacheTest { $this->sourceCache->put($file2, $data1); $this->sourceCache->put($file3, $data1); - $nested = new \OC\Files\Cache\Wrapper\CacheJail($this->cache, 'bar'); + $nested = new CacheJail($this->cache, 'bar'); $result = $nested->search('%asd%'); $this->assertCount(1, $result); @@ -218,7 +218,7 @@ class CacheJailTest extends CacheTest { $this->sourceCache->put($file2, $data1); $this->sourceCache->put($file3, $data1); - $nested = new \OC\Files\Cache\Wrapper\CacheJail($this->sourceCache, ''); + $nested = new CacheJail($this->sourceCache, ''); $result = $nested->search('%asd%'); $this->assertCount(1, $result); diff --git a/tests/lib/Files/Cache/Wrapper/CachePermissionsMaskTest.php b/tests/lib/Files/Cache/Wrapper/CachePermissionsMaskTest.php index 9aa1ee5b723..e4e14e7d5d0 100644 --- a/tests/lib/Files/Cache/Wrapper/CachePermissionsMaskTest.php +++ b/tests/lib/Files/Cache/Wrapper/CachePermissionsMaskTest.php @@ -7,6 +7,7 @@ namespace Test\Files\Cache\Wrapper; +use OC\Files\Cache\Wrapper\CachePermissionsMask; use OCP\Constants; use Test\Files\Cache\CacheTest; @@ -31,7 +32,7 @@ class CachePermissionsMaskTest extends CacheTest { } protected function getMaskedCached($mask) { - return new \OC\Files\Cache\Wrapper\CachePermissionsMask($this->sourceCache, $mask); + return new CachePermissionsMask($this->sourceCache, $mask); } public static function maskProvider(): array { diff --git a/tests/lib/Files/Config/UserMountCacheTest.php b/tests/lib/Files/Config/UserMountCacheTest.php index 88c0ceaef08..55251e68110 100644 --- a/tests/lib/Files/Config/UserMountCacheTest.php +++ b/tests/lib/Files/Config/UserMountCacheTest.php @@ -26,6 +26,7 @@ use OCP\ICacheFactory; use OCP\IConfig; use OCP\IDBConnection; use OCP\IUserManager; +use OCP\Server; use Psr\Log\LoggerInterface; use Test\TestCase; use Test\Util\User\Dummy; @@ -45,7 +46,7 @@ class UserMountCacheTest extends TestCase { $this->fileIds = []; - $this->connection = \OC::$server->getDatabaseConnection(); + $this->connection = Server::get(IDBConnection::class); $config = $this->getMockBuilder(IConfig::class) ->disableOriginalConstructor() diff --git a/tests/lib/Files/EtagTest.php b/tests/lib/Files/EtagTest.php index b0cdff16f4d..82ed0ceff96 100644 --- a/tests/lib/Files/EtagTest.php +++ b/tests/lib/Files/EtagTest.php @@ -8,8 +8,13 @@ namespace Test\Files; use OC\Files\Filesystem; +use OC\Files\Utils\Scanner; +use OC\Share\Share; use OCA\Files_Sharing\AppInfo\Application; use OCP\EventDispatcher\IEventDispatcher; +use OCP\IConfig; +use OCP\IDBConnection; +use OCP\ITempManager; use OCP\IUserManager; use OCP\Server; use Psr\Log\LoggerInterface; @@ -38,12 +43,12 @@ class EtagTest extends \Test\TestCase { // init files sharing new Application(); - \OC\Share\Share::registerBackend('file', 'OCA\Files_Sharing\ShareBackend\File'); - \OC\Share\Share::registerBackend('folder', 'OCA\Files_Sharing\ShareBackend\Folder', 'file'); + Share::registerBackend('file', 'OCA\Files_Sharing\ShareBackend\File'); + Share::registerBackend('folder', 'OCA\Files_Sharing\ShareBackend\Folder', 'file'); - $config = \OC::$server->getConfig(); + $config = Server::get(IConfig::class); $this->datadir = $config->getSystemValueString('datadirectory'); - $this->tmpDir = \OC::$server->getTempManager()->getTemporaryFolder(); + $this->tmpDir = Server::get(ITempManager::class)->getTemporaryFolder(); $config->setSystemValue('datadirectory', $this->tmpDir); $this->userBackend = new \Test\Util\User\Dummy(); @@ -51,7 +56,7 @@ class EtagTest extends \Test\TestCase { } protected function tearDown(): void { - \OC::$server->getConfig()->setSystemValue('datadirectory', $this->datadir); + Server::get(IConfig::class)->setSystemValue('datadirectory', $this->datadir); $this->logout(); parent::tearDown(); @@ -71,7 +76,7 @@ class EtagTest extends \Test\TestCase { $files = ['/foo.txt', '/folder/bar.txt', '/folder/subfolder', '/folder/subfolder/qwerty.txt']; $originalEtags = $this->getEtags($files); - $scanner = new \OC\Files\Utils\Scanner($user1, \OC::$server->getDatabaseConnection(), \OC::$server->query(IEventDispatcher::class), \OC::$server->get(LoggerInterface::class)); + $scanner = new Scanner($user1, Server::get(IDBConnection::class), Server::get(IEventDispatcher::class), Server::get(LoggerInterface::class)); $scanner->backgroundScan('/'); $newEtags = $this->getEtags($files); diff --git a/tests/lib/Files/FilesystemTest.php b/tests/lib/Files/FilesystemTest.php index 529b4f58428..9b5e24f8b74 100644 --- a/tests/lib/Files/FilesystemTest.php +++ b/tests/lib/Files/FilesystemTest.php @@ -7,24 +7,29 @@ namespace Test\Files; +use OC\Files\Filesystem; use OC\Files\Mount\MountPoint; use OC\Files\Storage\Temporary; +use OC\Files\View; use OC\User\NoUserException; use OCP\Files; use OCP\Files\Config\IMountProvider; +use OCP\Files\Config\IMountProviderCollection; use OCP\Files\Storage\IStorageFactory; +use OCP\IConfig; +use OCP\ITempManager; use OCP\IUser; use OCP\IUserManager; +use OCP\IUserSession; use OCP\Server; class DummyMountProvider implements IMountProvider { - private $mounts = []; - /** * @param array $mounts */ - public function __construct(array $mounts) { - $this->mounts = $mounts; + public function __construct( + private array $mounts, + ) { } /** @@ -59,7 +64,7 @@ class FilesystemTest extends \Test\TestCase { * @return array */ private function getStorageData() { - $dir = \OC::$server->getTempManager()->getTemporaryFolder(); + $dir = Server::get(ITempManager::class)->getTemporaryFolder(); $this->tmpDirs[] = $dir; return ['datadir' => $dir]; } @@ -69,7 +74,7 @@ class FilesystemTest extends \Test\TestCase { $userBackend = new \Test\Util\User\Dummy(); $userBackend->createUser(self::TEST_FILESYSTEM_USER1, self::TEST_FILESYSTEM_USER1); $userBackend->createUser(self::TEST_FILESYSTEM_USER2, self::TEST_FILESYSTEM_USER2); - \OC::$server->getUserManager()->registerBackend($userBackend); + Server::get(IUserManager::class)->registerBackend($userBackend); $this->loginAsUser(); } @@ -84,20 +89,20 @@ class FilesystemTest extends \Test\TestCase { } public function testMount(): void { - \OC\Files\Filesystem::mount('\OC\Files\Storage\Local', self::getStorageData(), '/'); - $this->assertEquals('/', \OC\Files\Filesystem::getMountPoint('/')); - $this->assertEquals('/', \OC\Files\Filesystem::getMountPoint('/some/folder')); - [, $internalPath] = \OC\Files\Filesystem::resolvePath('/'); + Filesystem::mount('\OC\Files\Storage\Local', self::getStorageData(), '/'); + $this->assertEquals('/', Filesystem::getMountPoint('/')); + $this->assertEquals('/', Filesystem::getMountPoint('/some/folder')); + [, $internalPath] = Filesystem::resolvePath('/'); $this->assertEquals('', $internalPath); - [, $internalPath] = \OC\Files\Filesystem::resolvePath('/some/folder'); + [, $internalPath] = Filesystem::resolvePath('/some/folder'); $this->assertEquals('some/folder', $internalPath); - \OC\Files\Filesystem::mount('\OC\Files\Storage\Local', self::getStorageData(), '/some'); - $this->assertEquals('/', \OC\Files\Filesystem::getMountPoint('/')); - $this->assertEquals('/some/', \OC\Files\Filesystem::getMountPoint('/some/folder')); - $this->assertEquals('/some/', \OC\Files\Filesystem::getMountPoint('/some/')); - $this->assertEquals('/some/', \OC\Files\Filesystem::getMountPoint('/some')); - [, $internalPath] = \OC\Files\Filesystem::resolvePath('/some/folder'); + Filesystem::mount('\OC\Files\Storage\Local', self::getStorageData(), '/some'); + $this->assertEquals('/', Filesystem::getMountPoint('/')); + $this->assertEquals('/some/', Filesystem::getMountPoint('/some/folder')); + $this->assertEquals('/some/', Filesystem::getMountPoint('/some/')); + $this->assertEquals('/some/', Filesystem::getMountPoint('/some')); + [, $internalPath] = Filesystem::resolvePath('/some/folder'); $this->assertEquals('folder', $internalPath); } @@ -199,7 +204,7 @@ class FilesystemTest extends \Test\TestCase { * @dataProvider normalizePathData */ public function testNormalizePath($expected, $path, $stripTrailingSlash = true): void { - $this->assertEquals($expected, \OC\Files\Filesystem::normalizePath($path, $stripTrailingSlash)); + $this->assertEquals($expected, Filesystem::normalizePath($path, $stripTrailingSlash)); } public static function normalizePathKeepUnicodeData(): array { @@ -217,15 +222,15 @@ class FilesystemTest extends \Test\TestCase { * @dataProvider normalizePathKeepUnicodeData */ public function testNormalizePathKeepUnicode($expected, $path, $keepUnicode = false): void { - $this->assertEquals($expected, \OC\Files\Filesystem::normalizePath($path, true, false, $keepUnicode)); + $this->assertEquals($expected, Filesystem::normalizePath($path, true, false, $keepUnicode)); } public function testNormalizePathKeepUnicodeCache(): void { $nfdName = 'ümlaut'; $nfcName = 'ümlaut'; // call in succession due to cache - $this->assertEquals('/' . $nfcName, \OC\Files\Filesystem::normalizePath($nfdName, true, false, false)); - $this->assertEquals('/' . $nfdName, \OC\Files\Filesystem::normalizePath($nfdName, true, false, true)); + $this->assertEquals('/' . $nfcName, Filesystem::normalizePath($nfdName, true, false, false)); + $this->assertEquals('/' . $nfdName, Filesystem::normalizePath($nfdName, true, false, true)); } public static function isValidPathData(): array { @@ -258,7 +263,7 @@ class FilesystemTest extends \Test\TestCase { * @dataProvider isValidPathData */ public function testIsValidPath($path, $expected): void { - $this->assertSame($expected, \OC\Files\Filesystem::isValidPath($path)); + $this->assertSame($expected, Filesystem::isValidPath($path)); } public static function isFileBlacklistedData(): array { @@ -280,7 +285,7 @@ class FilesystemTest extends \Test\TestCase { * @dataProvider isFileBlacklistedData */ public function testIsFileBlacklisted($path, $expected): void { - $this->assertSame($expected, \OC\Files\Filesystem::isFileBlacklisted($path)); + $this->assertSame($expected, Filesystem::isFileBlacklisted($path)); } public function testNormalizePathUTF8(): void { @@ -288,36 +293,36 @@ class FilesystemTest extends \Test\TestCase { $this->markTestSkipped('UTF8 normalizer Patchwork was not found'); } - $this->assertEquals("/foo/bar\xC3\xBC", \OC\Files\Filesystem::normalizePath("/foo/baru\xCC\x88")); - $this->assertEquals("/foo/bar\xC3\xBC", \OC\Files\Filesystem::normalizePath("\\foo\\baru\xCC\x88")); + $this->assertEquals("/foo/bar\xC3\xBC", Filesystem::normalizePath("/foo/baru\xCC\x88")); + $this->assertEquals("/foo/bar\xC3\xBC", Filesystem::normalizePath("\\foo\\baru\xCC\x88")); } public function testHooks(): void { - if (\OC\Files\Filesystem::getView()) { + if (Filesystem::getView()) { $user = \OC_User::getUser(); } else { $user = self::TEST_FILESYSTEM_USER1; $backend = new \Test\Util\User\Dummy(); Server::get(IUserManager::class)->registerBackend($backend); $backend->createUser($user, $user); - $userObj = \OC::$server->getUserManager()->get($user); - \OC::$server->getUserSession()->setUser($userObj); - \OC\Files\Filesystem::init($user, '/' . $user . '/files'); + $userObj = Server::get(IUserManager::class)->get($user); + Server::get(IUserSession::class)->setUser($userObj); + Filesystem::init($user, '/' . $user . '/files'); } \OC_Hook::clear('OC_Filesystem'); \OC_Hook::connect('OC_Filesystem', 'post_write', $this, 'dummyHook'); - \OC\Files\Filesystem::mount('OC\Files\Storage\Temporary', [], '/'); + Filesystem::mount('OC\Files\Storage\Temporary', [], '/'); - $rootView = new \OC\Files\View(''); + $rootView = new View(''); $rootView->mkdir('/' . $user); $rootView->mkdir('/' . $user . '/files'); // \OC\Files\Filesystem::file_put_contents('/foo', 'foo'); - \OC\Files\Filesystem::mkdir('/bar'); + Filesystem::mkdir('/bar'); // \OC\Files\Filesystem::file_put_contents('/bar//foo', 'foo'); - $tmpFile = \OC::$server->getTempManager()->getTemporaryFile(); + $tmpFile = Server::get(ITempManager::class)->getTemporaryFile(); file_put_contents($tmpFile, 'foo'); $fh = fopen($tmpFile, 'r'); // \OC\Files\Filesystem::file_put_contents('/bar//foo', $fh); @@ -328,29 +333,29 @@ class FilesystemTest extends \Test\TestCase { * */ public function testLocalMountWhenUserDoesNotExist(): void { - $this->expectException(\OC\User\NoUserException::class); + $this->expectException(NoUserException::class); $userId = $this->getUniqueID('user_'); - \OC\Files\Filesystem::initMountPoints($userId); + Filesystem::initMountPoints($userId); } public function testNullUserThrows(): void { - $this->expectException(\OC\User\NoUserException::class); + $this->expectException(NoUserException::class); - \OC\Files\Filesystem::initMountPoints(null); + Filesystem::initMountPoints(null); } public function testNullUserThrowsTwice(): void { $thrown = 0; try { - \OC\Files\Filesystem::initMountPoints(null); + Filesystem::initMountPoints(null); } catch (NoUserException $e) { $thrown++; } try { - \OC\Files\Filesystem::initMountPoints(null); + Filesystem::initMountPoints(null); } catch (NoUserException $e) { $thrown++; } @@ -365,13 +370,13 @@ class FilesystemTest extends \Test\TestCase { $userId = $this->getUniqueID('user_'); try { - \OC\Files\Filesystem::initMountPoints($userId); + Filesystem::initMountPoints($userId); } catch (NoUserException $e) { $thrown++; } try { - \OC\Files\Filesystem::initMountPoints($userId); + Filesystem::initMountPoints($userId); } catch (NoUserException $e) { $thrown++; } @@ -385,11 +390,11 @@ class FilesystemTest extends \Test\TestCase { public function testHomeMount(): void { $userId = $this->getUniqueID('user_'); - \OC::$server->getUserManager()->createUser($userId, $userId); + Server::get(IUserManager::class)->createUser($userId, $userId); - \OC\Files\Filesystem::initMountPoints($userId); + Filesystem::initMountPoints($userId); - $homeMount = \OC\Files\Filesystem::getStorage('/' . $userId . '/'); + $homeMount = Filesystem::getStorage('/' . $userId . '/'); $this->assertTrue($homeMount->instanceOfStorage('\OCP\Files\IHomeStorage')); if ($homeMount->instanceOfStorage('\OC\Files\ObjectStore\HomeObjectStoreStorage')) { @@ -398,7 +403,7 @@ class FilesystemTest extends \Test\TestCase { $this->assertEquals('home::' . $userId, $homeMount->getId()); } - $user = \OC::$server->getUserManager()->get($userId); + $user = Server::get(IUserManager::class)->get($userId); if ($user !== null) { $user->delete(); } @@ -406,7 +411,7 @@ class FilesystemTest extends \Test\TestCase { public function dummyHook($arguments) { $path = $arguments['path']; - $this->assertEquals($path, \OC\Files\Filesystem::normalizePath($path)); //the path passed to the hook should already be normalized + $this->assertEquals($path, Filesystem::normalizePath($path)); //the path passed to the hook should already be normalized } /** @@ -414,22 +419,22 @@ class FilesystemTest extends \Test\TestCase { */ public function testMountDefaultCacheDir(): void { $userId = $this->getUniqueID('user_'); - $config = \OC::$server->getConfig(); + $config = Server::get(IConfig::class); $oldCachePath = $config->getSystemValueString('cache_path', ''); // no cache path configured $config->setSystemValue('cache_path', ''); - \OC::$server->getUserManager()->createUser($userId, $userId); - \OC\Files\Filesystem::initMountPoints($userId); + Server::get(IUserManager::class)->createUser($userId, $userId); + Filesystem::initMountPoints($userId); $this->assertEquals( '/' . $userId . '/', - \OC\Files\Filesystem::getMountPoint('/' . $userId . '/cache') + Filesystem::getMountPoint('/' . $userId . '/cache') ); - [$storage, $internalPath] = \OC\Files\Filesystem::resolvePath('/' . $userId . '/cache'); + [$storage, $internalPath] = Filesystem::resolvePath('/' . $userId . '/cache'); $this->assertTrue($storage->instanceOfStorage('\OCP\Files\IHomeStorage')); $this->assertEquals('cache', $internalPath); - $user = \OC::$server->getUserManager()->get($userId); + $user = Server::get(IUserManager::class)->get($userId); if ($user !== null) { $user->delete(); } @@ -444,23 +449,23 @@ class FilesystemTest extends \Test\TestCase { public function testMountExternalCacheDir(): void { $userId = $this->getUniqueID('user_'); - $config = \OC::$server->getConfig(); + $config = Server::get(IConfig::class); $oldCachePath = $config->getSystemValueString('cache_path', ''); // set cache path to temp dir - $cachePath = \OC::$server->getTempManager()->getTemporaryFolder() . '/extcache'; + $cachePath = Server::get(ITempManager::class)->getTemporaryFolder() . '/extcache'; $config->setSystemValue('cache_path', $cachePath); - \OC::$server->getUserManager()->createUser($userId, $userId); - \OC\Files\Filesystem::initMountPoints($userId); + Server::get(IUserManager::class)->createUser($userId, $userId); + Filesystem::initMountPoints($userId); $this->assertEquals( '/' . $userId . '/cache/', - \OC\Files\Filesystem::getMountPoint('/' . $userId . '/cache') + Filesystem::getMountPoint('/' . $userId . '/cache') ); - [$storage, $internalPath] = \OC\Files\Filesystem::resolvePath('/' . $userId . '/cache'); + [$storage, $internalPath] = Filesystem::resolvePath('/' . $userId . '/cache'); $this->assertTrue($storage->instanceOfStorage('\OC\Files\Storage\Local')); $this->assertEquals('', $internalPath); - $user = \OC::$server->getUserManager()->get($userId); + $user = Server::get(IUserManager::class)->get($userId); if ($user !== null) { $user->delete(); } @@ -469,11 +474,11 @@ class FilesystemTest extends \Test\TestCase { } public function testRegisterMountProviderAfterSetup(): void { - \OC\Files\Filesystem::initMountPoints(self::TEST_FILESYSTEM_USER2); - $this->assertEquals('/', \OC\Files\Filesystem::getMountPoint('/foo/bar')); + Filesystem::initMountPoints(self::TEST_FILESYSTEM_USER2); + $this->assertEquals('/', Filesystem::getMountPoint('/foo/bar')); $mount = new MountPoint(new Temporary([]), '/foo/bar'); $mountProvider = new DummyMountProvider([self::TEST_FILESYSTEM_USER2 => [$mount]]); - \OCP\Server::get(\OCP\Files\Config\IMountProviderCollection::class)->registerProvider($mountProvider); - $this->assertEquals('/foo/bar/', \OC\Files\Filesystem::getMountPoint('/foo/bar')); + Server::get(IMountProviderCollection::class)->registerProvider($mountProvider); + $this->assertEquals('/foo/bar/', Filesystem::getMountPoint('/foo/bar')); } } diff --git a/tests/lib/Files/Mount/ManagerTest.php b/tests/lib/Files/Mount/ManagerTest.php index 12338c18dbd..b2ddf2d8ef4 100644 --- a/tests/lib/Files/Mount/ManagerTest.php +++ b/tests/lib/Files/Mount/ManagerTest.php @@ -7,6 +7,7 @@ namespace Test\Files\Mount; +use OC\Files\Mount\MountPoint; use OC\Files\SetupManagerFactory; use OC\Files\Storage\Temporary; @@ -28,33 +29,33 @@ class ManagerTest extends \Test\TestCase { } public function testFind(): void { - $rootMount = new \OC\Files\Mount\MountPoint(new Temporary([]), '/'); + $rootMount = new MountPoint(new Temporary([]), '/'); $this->manager->addMount($rootMount); $this->assertEquals($rootMount, $this->manager->find('/')); $this->assertEquals($rootMount, $this->manager->find('/foo/bar')); $storage = new Temporary([]); - $mount1 = new \OC\Files\Mount\MountPoint($storage, '/foo'); + $mount1 = new MountPoint($storage, '/foo'); $this->manager->addMount($mount1); $this->assertEquals($rootMount, $this->manager->find('/')); $this->assertEquals($mount1, $this->manager->find('/foo/bar')); $this->assertEquals(1, count($this->manager->findIn('/'))); - $mount2 = new \OC\Files\Mount\MountPoint(new Temporary([]), '/bar'); + $mount2 = new MountPoint(new Temporary([]), '/bar'); $this->manager->addMount($mount2); $this->assertEquals(2, count($this->manager->findIn('/'))); $id = $mount1->getStorageId(); $this->assertEquals([$mount1], $this->manager->findByStorageId($id)); - $mount3 = new \OC\Files\Mount\MountPoint($storage, '/foo/bar'); + $mount3 = new MountPoint($storage, '/foo/bar'); $this->manager->addMount($mount3); $this->assertEquals([$mount1, $mount3], $this->manager->findByStorageId($id)); } public function testLong(): void { $storage = new LongId([]); - $mount = new \OC\Files\Mount\MountPoint($storage, '/foo'); + $mount = new MountPoint($storage, '/foo'); $this->manager->addMount($mount); $id = $mount->getStorageId(); diff --git a/tests/lib/Files/Mount/MountPointTest.php b/tests/lib/Files/Mount/MountPointTest.php index 96987c9f5eb..af66a9028eb 100644 --- a/tests/lib/Files/Mount/MountPointTest.php +++ b/tests/lib/Files/Mount/MountPointTest.php @@ -7,6 +7,7 @@ namespace Test\Files\Mount; +use OC\Files\Mount\MountPoint; use OC\Files\Storage\StorageFactory; use OC\Lockdown\Filesystem\NullStorage; use OCP\Files\Storage\IStorage; @@ -23,7 +24,7 @@ class MountPointTest extends \Test\TestCase { ->method('wrap') ->willReturn($storage); - $mountPoint = new \OC\Files\Mount\MountPoint( + $mountPoint = new MountPoint( // just use this because a real class is needed NullStorage::class, '/mountpoint', @@ -43,14 +44,14 @@ class MountPointTest extends \Test\TestCase { $loader = $this->createMock(StorageFactory::class); $loader->expects($this->once()) ->method('wrap') - ->will($this->throwException(new \Exception('Test storage init exception'))); + ->willThrowException(new \Exception('Test storage init exception')); $called = false; - $wrapper = function ($mountPoint, $storage) use ($called) { + $wrapper = function ($mountPoint, $storage) use ($called): void { $called = true; }; - $mountPoint = new \OC\Files\Mount\MountPoint( + $mountPoint = new MountPoint( // just use this because a real class is needed NullStorage::class, '/mountpoint', diff --git a/tests/lib/Files/Mount/MountTest.php b/tests/lib/Files/Mount/MountTest.php index 76d70cdd214..7be7fc67cd6 100644 --- a/tests/lib/Files/Mount/MountTest.php +++ b/tests/lib/Files/Mount/MountTest.php @@ -7,6 +7,7 @@ namespace Test\Files\Mount; +use OC\Files\Mount\MountPoint; use OC\Files\Storage\StorageFactory; use OC\Files\Storage\Wrapper\Wrapper; @@ -15,12 +16,12 @@ class MountTest extends \Test\TestCase { $storage = $this->getMockBuilder('\OC\Files\Storage\Temporary') ->disableOriginalConstructor() ->getMock(); - $mount = new \OC\Files\Mount\MountPoint($storage, '/foo'); + $mount = new MountPoint($storage, '/foo'); $this->assertInstanceOf('\OC\Files\Storage\Temporary', $mount->getStorage()); } public function testFromStorageClassname(): void { - $mount = new \OC\Files\Mount\MountPoint('\OC\Files\Storage\Temporary', '/foo'); + $mount = new MountPoint('\OC\Files\Storage\Temporary', '/foo'); $this->assertInstanceOf('\OC\Files\Storage\Temporary', $mount->getStorage()); } @@ -38,7 +39,7 @@ class MountTest extends \Test\TestCase { $storage = $this->getMockBuilder('\OC\Files\Storage\Temporary') ->disableOriginalConstructor() ->getMock(); - $mount = new \OC\Files\Mount\MountPoint($storage, '/foo', [], $loader); + $mount = new MountPoint($storage, '/foo', [], $loader); $this->assertInstanceOf('\OC\Files\Storage\Wrapper\Wrapper', $mount->getStorage()); } } diff --git a/tests/lib/Files/Mount/ObjectHomeMountProviderTest.php b/tests/lib/Files/Mount/ObjectHomeMountProviderTest.php index 2b809835953..c0b49813c93 100644 --- a/tests/lib/Files/Mount/ObjectHomeMountProviderTest.php +++ b/tests/lib/Files/Mount/ObjectHomeMountProviderTest.php @@ -241,10 +241,9 @@ class ObjectHomeMountProviderTest extends \Test\TestCase { } class FakeObjectStore implements IObjectStore { - private $arguments; - - public function __construct(array $arguments) { - $this->arguments = $arguments; + public function __construct( + private array $arguments, + ) { } public function getArguments() { diff --git a/tests/lib/Files/Node/FileTest.php b/tests/lib/Files/Node/FileTest.php index 74a23520344..f3d893d5af2 100644 --- a/tests/lib/Files/Node/FileTest.php +++ b/tests/lib/Files/Node/FileTest.php @@ -7,7 +7,10 @@ namespace Test\Files\Node; +use OC\Files\Node\File; use OC\Files\Node\Root; +use OCP\Constants; +use OCP\Files\NotPermittedException; /** * Class FileTest @@ -19,9 +22,9 @@ use OC\Files\Node\Root; class FileTest extends NodeTestCase { protected function createTestNode($root, $view, $path, array $data = [], $internalPath = '', $storage = null) { if ($data || $internalPath || $storage) { - return new \OC\Files\Node\File($root, $view, $path, $this->getFileInfo($data, $internalPath, $storage)); + return new File($root, $view, $path, $this->getFileInfo($data, $internalPath, $storage)); } else { - return new \OC\Files\Node\File($root, $view, $path); + return new File($root, $view, $path); } } @@ -43,7 +46,7 @@ class FileTest extends NodeTestCase { ->setConstructorArgs([$this->manager, $this->view, $this->user, $this->userMountCache, $this->logger, $this->userManager, $this->eventDispatcher, $this->cacheFactory]) ->getMock(); - $hook = function ($file) { + $hook = function ($file): void { throw new \Exception('Hooks are not supposed to be called'); }; @@ -58,15 +61,15 @@ class FileTest extends NodeTestCase { $this->view->expects($this->once()) ->method('getFileInfo') ->with('/bar/foo') - ->willReturn($this->getFileInfo(['permissions' => \OCP\Constants::PERMISSION_READ])); + ->willReturn($this->getFileInfo(['permissions' => Constants::PERMISSION_READ])); - $node = new \OC\Files\Node\File($root, $this->view, '/bar/foo'); + $node = new File($root, $this->view, '/bar/foo'); $this->assertEquals('bar', $node->getContent()); } public function testGetContentNotPermitted(): void { - $this->expectException(\OCP\Files\NotPermittedException::class); + $this->expectException(NotPermittedException::class); /** @var \OC\Files\Node\Root|\PHPUnit\Framework\MockObject\MockObject $root */ $root = $this->getMockBuilder(Root::class) @@ -82,7 +85,7 @@ class FileTest extends NodeTestCase { ->with('/bar/foo') ->willReturn($this->getFileInfo(['permissions' => 0])); - $node = new \OC\Files\Node\File($root, $this->view, '/bar/foo'); + $node = new File($root, $this->view, '/bar/foo'); $node->getContent(); } @@ -99,20 +102,20 @@ class FileTest extends NodeTestCase { $this->view->expects($this->once()) ->method('getFileInfo') ->with('/bar/foo') - ->willReturn($this->getFileInfo(['permissions' => \OCP\Constants::PERMISSION_ALL])); + ->willReturn($this->getFileInfo(['permissions' => Constants::PERMISSION_ALL])); $this->view->expects($this->once()) ->method('file_put_contents') ->with('/bar/foo', 'bar') ->willReturn(true); - $node = new \OC\Files\Node\File($root, $this->view, '/bar/foo'); + $node = new File($root, $this->view, '/bar/foo'); $node->putContent('bar'); } public function testPutContentNotPermitted(): void { - $this->expectException(\OCP\Files\NotPermittedException::class); + $this->expectException(NotPermittedException::class); /** @var \OC\Files\Node\Root|\PHPUnit\Framework\MockObject\MockObject $root */ $root = $this->getMockBuilder(Root::class) @@ -122,9 +125,9 @@ class FileTest extends NodeTestCase { $this->view->expects($this->once()) ->method('getFileInfo') ->with('/bar/foo') - ->willReturn($this->getFileInfo(['permissions' => \OCP\Constants::PERMISSION_READ])); + ->willReturn($this->getFileInfo(['permissions' => Constants::PERMISSION_READ])); - $node = new \OC\Files\Node\File($root, $this->view, '/bar/foo'); + $node = new File($root, $this->view, '/bar/foo'); $node->putContent('bar'); } @@ -139,7 +142,7 @@ class FileTest extends NodeTestCase { ->with('/bar/foo') ->willReturn($this->getFileInfo(['mimetype' => 'text/plain'])); - $node = new \OC\Files\Node\File($root, $this->view, '/bar/foo'); + $node = new File($root, $this->view, '/bar/foo'); $this->assertEquals('text/plain', $node->getMimeType()); } @@ -148,7 +151,7 @@ class FileTest extends NodeTestCase { fwrite($stream, 'bar'); rewind($stream); - $root = new \OC\Files\Node\Root( + $root = new Root( $this->manager, $this->view, $this->user, @@ -159,7 +162,7 @@ class FileTest extends NodeTestCase { $this->cacheFactory, ); - $hook = function ($file) { + $hook = function ($file): void { throw new \Exception('Hooks are not supposed to be called'); }; @@ -174,9 +177,9 @@ class FileTest extends NodeTestCase { $this->view->expects($this->once()) ->method('getFileInfo') ->with('/bar/foo') - ->willReturn($this->getFileInfo(['permissions' => \OCP\Constants::PERMISSION_ALL])); + ->willReturn($this->getFileInfo(['permissions' => Constants::PERMISSION_ALL])); - $node = new \OC\Files\Node\File($root, $this->view, '/bar/foo'); + $node = new File($root, $this->view, '/bar/foo'); $fh = $node->fopen('r'); $this->assertEquals($stream, $fh); $this->assertEquals('bar', fread($fh, 3)); @@ -185,7 +188,7 @@ class FileTest extends NodeTestCase { public function testFOpenWrite(): void { $stream = fopen('php://memory', 'w+'); - $root = new \OC\Files\Node\Root( + $root = new Root( $this->manager, $this->view, $this->user, @@ -196,7 +199,7 @@ class FileTest extends NodeTestCase { $this->cacheFactory, ); $hooksCalled = 0; - $hook = function ($file) use (&$hooksCalled) { + $hook = function ($file) use (&$hooksCalled): void { $hooksCalled++; }; @@ -211,9 +214,9 @@ class FileTest extends NodeTestCase { $this->view->expects($this->once()) ->method('getFileInfo') ->with('/bar/foo') - ->willReturn($this->getFileInfo(['permissions' => \OCP\Constants::PERMISSION_ALL])); + ->willReturn($this->getFileInfo(['permissions' => Constants::PERMISSION_ALL])); - $node = new \OC\Files\Node\File($root, $this->view, '/bar/foo'); + $node = new File($root, $this->view, '/bar/foo'); $fh = $node->fopen('w'); $this->assertEquals($stream, $fh); fwrite($fh, 'bar'); @@ -224,9 +227,9 @@ class FileTest extends NodeTestCase { public function testFOpenReadNotPermitted(): void { - $this->expectException(\OCP\Files\NotPermittedException::class); + $this->expectException(NotPermittedException::class); - $root = new \OC\Files\Node\Root( + $root = new Root( $this->manager, $this->view, $this->user, @@ -236,7 +239,7 @@ class FileTest extends NodeTestCase { $this->eventDispatcher, $this->cacheFactory, ); - $hook = function ($file) { + $hook = function ($file): void { throw new \Exception('Hooks are not supposed to be called'); }; @@ -245,15 +248,15 @@ class FileTest extends NodeTestCase { ->with('/bar/foo') ->willReturn($this->getFileInfo(['permissions' => 0])); - $node = new \OC\Files\Node\File($root, $this->view, '/bar/foo'); + $node = new File($root, $this->view, '/bar/foo'); $node->fopen('r'); } public function testFOpenReadWriteNoReadPermissions(): void { - $this->expectException(\OCP\Files\NotPermittedException::class); + $this->expectException(NotPermittedException::class); - $root = new \OC\Files\Node\Root( + $root = new Root( $this->manager, $this->view, $this->user, @@ -263,24 +266,24 @@ class FileTest extends NodeTestCase { $this->eventDispatcher, $this->cacheFactory, ); - $hook = function () { + $hook = function (): void { throw new \Exception('Hooks are not supposed to be called'); }; $this->view->expects($this->once()) ->method('getFileInfo') ->with('/bar/foo') - ->willReturn($this->getFileInfo(['permissions' => \OCP\Constants::PERMISSION_UPDATE])); + ->willReturn($this->getFileInfo(['permissions' => Constants::PERMISSION_UPDATE])); - $node = new \OC\Files\Node\File($root, $this->view, '/bar/foo'); + $node = new File($root, $this->view, '/bar/foo'); $node->fopen('w'); } public function testFOpenReadWriteNoWritePermissions(): void { - $this->expectException(\OCP\Files\NotPermittedException::class); + $this->expectException(NotPermittedException::class); - $root = new \OC\Files\Node\Root( + $root = new Root( $this->manager, $this->view, $this->user, @@ -290,16 +293,16 @@ class FileTest extends NodeTestCase { $this->eventDispatcher, $this->cacheFactory, ); - $hook = function () { + $hook = function (): void { throw new \Exception('Hooks are not supposed to be called'); }; $this->view->expects($this->once()) ->method('getFileInfo') ->with('/bar/foo') - ->willReturn($this->getFileInfo(['permissions' => \OCP\Constants::PERMISSION_READ])); + ->willReturn($this->getFileInfo(['permissions' => Constants::PERMISSION_READ])); - $node = new \OC\Files\Node\File($root, $this->view, '/bar/foo'); + $node = new File($root, $this->view, '/bar/foo'); $node->fopen('w'); } } diff --git a/tests/lib/Files/Node/FolderTest.php b/tests/lib/Files/Node/FolderTest.php index 25f555e7068..53e8f07a0d3 100644 --- a/tests/lib/Files/Node/FolderTest.php +++ b/tests/lib/Files/Node/FolderTest.php @@ -21,12 +21,15 @@ use OC\Files\Search\SearchBinaryOperator; use OC\Files\Search\SearchComparison; use OC\Files\Search\SearchOrder; use OC\Files\Search\SearchQuery; +use OC\Files\Storage\Storage; use OC\Files\Storage\Temporary; use OC\Files\Storage\Wrapper\Jail; +use OCP\Constants; use OCP\Files\Cache\ICacheEntry; use OCP\Files\IRootFolder; use OCP\Files\Mount\IMountPoint; use OCP\Files\NotFoundException; +use OCP\Files\NotPermittedException; use OCP\Files\Search\ISearchBinaryOperator; use OCP\Files\Search\ISearchComparison; use OCP\Files\Search\ISearchOrder; @@ -150,7 +153,7 @@ class FolderTest extends NodeTestCase { $root->method('get') ->with('/bar/foo/asd') - ->will($this->throwException(new NotFoundException())); + ->willThrowException(new NotFoundException()); $node = new Folder($root, $view, '/bar/foo'); $this->assertFalse($node->nodeExists('asd')); @@ -168,7 +171,7 @@ class FolderTest extends NodeTestCase { $view->method('getFileInfo') ->with('/bar/foo') - ->willReturn($this->getFileInfo(['permissions' => \OCP\Constants::PERMISSION_ALL])); + ->willReturn($this->getFileInfo(['permissions' => Constants::PERMISSION_ALL])); $view->method('mkdir') ->with('/bar/foo/asd') @@ -192,7 +195,7 @@ class FolderTest extends NodeTestCase { $view->method('getFileInfo') ->with('/foobar') - ->willReturn($this->getFileInfo(['permissions' => \OCP\Constants::PERMISSION_ALL])); + ->willReturn($this->getFileInfo(['permissions' => Constants::PERMISSION_ALL])); $view->method('mkdir') ->with('/foobar/asd/sdf') @@ -206,7 +209,7 @@ class FolderTest extends NodeTestCase { public function testNewFolderNotPermitted(): void { - $this->expectException(\OCP\Files\NotPermittedException::class); + $this->expectException(NotPermittedException::class); $manager = $this->createMock(Manager::class); $view = $this->getRootViewMock(); @@ -218,7 +221,7 @@ class FolderTest extends NodeTestCase { $view->method('getFileInfo') ->with('/bar/foo') - ->willReturn($this->getFileInfo(['permissions' => \OCP\Constants::PERMISSION_READ])); + ->willReturn($this->getFileInfo(['permissions' => Constants::PERMISSION_READ])); $node = new Folder($root, $view, '/bar/foo'); $node->newFolder('asd'); @@ -236,21 +239,21 @@ class FolderTest extends NodeTestCase { $view->method('getFileInfo') ->with('/bar/foo') - ->willReturn($this->getFileInfo(['permissions' => \OCP\Constants::PERMISSION_ALL])); + ->willReturn($this->getFileInfo(['permissions' => Constants::PERMISSION_ALL])); $view->method('touch') ->with('/bar/foo/asd') ->willReturn(true); $node = new Folder($root, $view, '/bar/foo'); - $child = new \OC\Files\Node\File($root, $view, '/bar/foo/asd', null, $node); + $child = new File($root, $view, '/bar/foo/asd', null, $node); $result = $node->newFile('asd'); $this->assertEquals($child, $result); } public function testNewFileNotPermitted(): void { - $this->expectException(\OCP\Files\NotPermittedException::class); + $this->expectException(NotPermittedException::class); $manager = $this->createMock(Manager::class); $view = $this->getRootViewMock(); @@ -262,7 +265,7 @@ class FolderTest extends NodeTestCase { $view->method('getFileInfo') ->with('/bar/foo') - ->willReturn($this->getFileInfo(['permissions' => \OCP\Constants::PERMISSION_READ])); + ->willReturn($this->getFileInfo(['permissions' => Constants::PERMISSION_READ])); $node = new Folder($root, $view, '/bar/foo'); $node->newFile('asd'); @@ -502,7 +505,7 @@ class FolderTest extends NodeTestCase { ->onlyMethods(['getMountsIn', 'getMount']) ->setConstructorArgs([$manager, $view, $this->user, $this->userMountCache, $this->logger, $this->userManager, $this->eventDispatcher, $this->cacheFactory]) ->getMock(); - $storage = $this->createMock(\OC\Files\Storage\Storage::class); + $storage = $this->createMock(Storage::class); $mount = new MountPoint($storage, '/bar'); $storage->method('getId')->willReturn(''); $cache = $this->getMockBuilder(Cache::class)->setConstructorArgs([$storage])->getMock(); @@ -551,7 +554,7 @@ class FolderTest extends NodeTestCase { ->onlyMethods(['getMountsIn', 'getMount']) ->setConstructorArgs([$manager, $view, $this->user, $this->userMountCache, $this->logger, $this->userManager, $this->eventDispatcher, $this->cacheFactory]) ->getMock(); - $storage = $this->createMock(\OC\Files\Storage\Storage::class); + $storage = $this->createMock(Storage::class); $mount = new MountPoint($storage, '/bar'); $storage->method('getId')->willReturn(''); $cache = $this->getMockBuilder(Cache::class)->setConstructorArgs([$storage])->getMock(); @@ -596,7 +599,7 @@ class FolderTest extends NodeTestCase { ->onlyMethods(['getMountsIn', 'getMount']) ->setConstructorArgs([$manager, $view, $this->user, $this->userMountCache, $this->logger, $this->userManager, $this->eventDispatcher, $this->cacheFactory]) ->getMock(); - $storage = $this->createMock(\OC\Files\Storage\Storage::class); + $storage = $this->createMock(Storage::class); $mount = new MountPoint($storage, '/bar'); $storage->method('getId')->willReturn(''); $cache = $this->getMockBuilder(Cache::class)->setConstructorArgs([$storage])->getMock(); @@ -640,7 +643,7 @@ class FolderTest extends NodeTestCase { ->onlyMethods(['getMountsIn', 'getMount']) ->setConstructorArgs([$manager, $view, $this->user, $this->userMountCache, $this->logger, $this->userManager, $this->eventDispatcher, $this->cacheFactory]) ->getMock(); - $storage = $this->createMock(\OC\Files\Storage\Storage::class); + $storage = $this->createMock(Storage::class); $mount1 = new MountPoint($storage, '/bar'); $mount2 = new MountPoint($storage, '/bar/foo/asd'); $storage->method('getId')->willReturn(''); @@ -753,14 +756,14 @@ class FolderTest extends NodeTestCase { 'mtime' => $baseTime, 'mimetype' => 'text/plain', 'size' => 3, - 'permissions' => \OCP\Constants::PERMISSION_ALL, + 'permissions' => Constants::PERMISSION_ALL, ]); $id2 = $cache->put('bar/foo/old.txt', [ 'storage_mtime' => $baseTime - 100, 'mtime' => $baseTime - 100, 'mimetype' => 'text/plain', 'size' => 3, - 'permissions' => \OCP\Constants::PERMISSION_READ, + 'permissions' => Constants::PERMISSION_READ, ]); $cache->put('bar/asd/outside.txt', [ 'storage_mtime' => $baseTime, @@ -773,7 +776,7 @@ class FolderTest extends NodeTestCase { 'mtime' => $baseTime - 600, 'mimetype' => 'text/plain', 'size' => 3, - 'permissions' => \OCP\Constants::PERMISSION_ALL, + 'permissions' => Constants::PERMISSION_ALL, ]); $node = new Folder($root, $view, $folderPath, $folderInfo); @@ -830,7 +833,7 @@ class FolderTest extends NodeTestCase { 'mimetype' => 'text/plain', 'size' => 3, 'parent' => $id1, - 'permissions' => \OCP\Constants::PERMISSION_ALL, + 'permissions' => Constants::PERMISSION_ALL, ]); $id3 = $cache->put('bar/foo/folder/asd.txt', [ 'storage_mtime' => $baseTime - 100, @@ -838,7 +841,7 @@ class FolderTest extends NodeTestCase { 'mimetype' => 'text/plain', 'size' => 3, 'parent' => $id1, - 'permissions' => \OCP\Constants::PERMISSION_ALL, + 'permissions' => Constants::PERMISSION_ALL, ]); $node = new Folder($root, $view, $folderPath, $folderInfo); @@ -891,7 +894,7 @@ class FolderTest extends NodeTestCase { 'mtime' => $baseTime, 'mimetype' => 'text/plain', 'size' => 3, - 'permissions' => \OCP\Constants::PERMISSION_ALL, + 'permissions' => Constants::PERMISSION_ALL, ]); $cache->put('outside.txt', [ diff --git a/tests/lib/Files/Node/HookConnectorTest.php b/tests/lib/Files/Node/HookConnectorTest.php index 87e83fd0a3b..0b7d26fd24d 100644 --- a/tests/lib/Files/Node/HookConnectorTest.php +++ b/tests/lib/Files/Node/HookConnectorTest.php @@ -15,6 +15,7 @@ use OC\Files\View; use OC\Memcache\ArrayCache; use OCP\EventDispatcher\GenericEvent as APIGenericEvent; use OCP\EventDispatcher\IEventDispatcher; +use OCP\Files\Config\IUserMountCache; use OCP\Files\Events\Node\AbstractNodeEvent; use OCP\Files\Events\Node\AbstractNodesEvent; use OCP\Files\Events\Node\BeforeNodeCopiedEvent; @@ -32,6 +33,7 @@ use OCP\Files\Events\Node\NodeWrittenEvent; use OCP\Files\Node; use OCP\ICacheFactory; use OCP\IUserManager; +use OCP\Server; use Psr\Log\LoggerInterface; use Symfony\Component\EventDispatcher\GenericEvent; use Test\TestCase; @@ -79,15 +81,15 @@ class HookConnectorTest extends TestCase { $this->root = new Root( Filesystem::getMountManager(), $this->view, - \OC::$server->getUserManager()->get($this->userId), - \OCP\Server::get(\OCP\Files\Config\IUserMountCache::class), + Server::get(IUserManager::class)->get($this->userId), + Server::get(IUserMountCache::class), $this->createMock(LoggerInterface::class), $this->createMock(IUserManager::class), $this->createMock(IEventDispatcher::class), $cacheFactory, ); - $this->eventDispatcher = \OC::$server->query(IEventDispatcher::class); - $this->logger = \OC::$server->query(LoggerInterface::class); + $this->eventDispatcher = Server::get(IEventDispatcher::class); + $this->logger = Server::get(LoggerInterface::class); } protected function tearDown(): void { @@ -98,49 +100,49 @@ class HookConnectorTest extends TestCase { public static function viewToNodeProvider(): array { return [ - [function () { + [function (): void { Filesystem::file_put_contents('test.txt', 'asd'); }, 'preWrite', '\OCP\Files::preWrite', BeforeNodeWrittenEvent::class], - [function () { + [function (): void { Filesystem::file_put_contents('test.txt', 'asd'); }, 'postWrite', '\OCP\Files::postWrite', NodeWrittenEvent::class], - [function () { + [function (): void { Filesystem::file_put_contents('test.txt', 'asd'); }, 'preCreate', '\OCP\Files::preCreate', BeforeNodeCreatedEvent::class], - [function () { + [function (): void { Filesystem::file_put_contents('test.txt', 'asd'); }, 'postCreate', '\OCP\Files::postCreate', NodeCreatedEvent::class], - [function () { + [function (): void { Filesystem::mkdir('test.txt'); }, 'preCreate', '\OCP\Files::preCreate', BeforeNodeCreatedEvent::class], - [function () { + [function (): void { Filesystem::mkdir('test.txt'); }, 'postCreate', '\OCP\Files::postCreate', NodeCreatedEvent::class], - [function () { + [function (): void { Filesystem::touch('test.txt'); }, 'preTouch', '\OCP\Files::preTouch', BeforeNodeTouchedEvent::class], - [function () { + [function (): void { Filesystem::touch('test.txt'); }, 'postTouch', '\OCP\Files::postTouch', NodeTouchedEvent::class], - [function () { + [function (): void { Filesystem::touch('test.txt'); }, 'preCreate', '\OCP\Files::preCreate', BeforeNodeCreatedEvent::class], - [function () { + [function (): void { Filesystem::touch('test.txt'); }, 'postCreate', '\OCP\Files::postCreate', NodeCreatedEvent::class], - [function () { + [function (): void { Filesystem::file_put_contents('test.txt', 'asd'); Filesystem::unlink('test.txt'); }, 'preDelete', '\OCP\Files::preDelete', BeforeNodeDeletedEvent::class], - [function () { + [function (): void { Filesystem::file_put_contents('test.txt', 'asd'); Filesystem::unlink('test.txt'); }, 'postDelete', '\OCP\Files::postDelete', NodeDeletedEvent::class], - [function () { + [function (): void { Filesystem::mkdir('test.txt'); Filesystem::rmdir('test.txt'); }, 'preDelete', '\OCP\Files::preDelete', BeforeNodeDeletedEvent::class], - [function () { + [function (): void { Filesystem::mkdir('test.txt'); Filesystem::rmdir('test.txt'); }, 'postDelete', '\OCP\Files::postDelete', NodeDeletedEvent::class], @@ -159,7 +161,7 @@ class HookConnectorTest extends TestCase { /** @var Node $hookNode */ $hookNode = null; - $this->root->listen('\OC\Files', $expectedHook, function ($node) use (&$hookNode, &$hookCalled) { + $this->root->listen('\OC\Files', $expectedHook, function ($node) use (&$hookNode, &$hookCalled): void { $hookCalled = true; $hookNode = $node; }); @@ -167,7 +169,7 @@ class HookConnectorTest extends TestCase { $dispatcherCalled = false; /** @var Node $dispatcherNode */ $dispatcherNode = null; - $this->eventDispatcher->addListener($expectedLegacyEvent, function ($event) use (&$dispatcherCalled, &$dispatcherNode) { + $this->eventDispatcher->addListener($expectedLegacyEvent, function ($event) use (&$dispatcherCalled, &$dispatcherNode): void { /** @var GenericEvent|APIGenericEvent $event */ $dispatcherCalled = true; $dispatcherNode = $event->getSubject(); @@ -175,7 +177,7 @@ class HookConnectorTest extends TestCase { $newDispatcherCalled = false; $newDispatcherNode = null; - $this->eventDispatcher->addListener($expectedEvent, function ($event) use ($expectedEvent, &$newDispatcherCalled, &$newDispatcherNode) { + $this->eventDispatcher->addListener($expectedEvent, function ($event) use ($expectedEvent, &$newDispatcherCalled, &$newDispatcherNode): void { if ($event instanceof $expectedEvent) { /** @var AbstractNodeEvent $event */ $newDispatcherCalled = true; @@ -197,19 +199,19 @@ class HookConnectorTest extends TestCase { public static function viewToNodeProviderCopyRename(): array { return [ - [function () { + [function (): void { Filesystem::file_put_contents('source', 'asd'); Filesystem::rename('source', 'target'); }, 'preRename', '\OCP\Files::preRename', BeforeNodeRenamedEvent::class], - [function () { + [function (): void { Filesystem::file_put_contents('source', 'asd'); Filesystem::rename('source', 'target'); }, 'postRename', '\OCP\Files::postRename', NodeRenamedEvent::class], - [function () { + [function (): void { Filesystem::file_put_contents('source', 'asd'); Filesystem::copy('source', 'target'); }, 'preCopy', '\OCP\Files::preCopy', BeforeNodeCopiedEvent::class], - [function () { + [function (): void { Filesystem::file_put_contents('source', 'asd'); Filesystem::copy('source', 'target'); }, 'postCopy', '\OCP\Files::postCopy', NodeCopiedEvent::class], @@ -230,7 +232,7 @@ class HookConnectorTest extends TestCase { /** @var Node $hookTargetNode */ $hookTargetNode = null; - $this->root->listen('\OC\Files', $expectedHook, function ($sourceNode, $targetNode) use (&$hookCalled, &$hookSourceNode, &$hookTargetNode) { + $this->root->listen('\OC\Files', $expectedHook, function ($sourceNode, $targetNode) use (&$hookCalled, &$hookSourceNode, &$hookTargetNode): void { $hookCalled = true; $hookSourceNode = $sourceNode; $hookTargetNode = $targetNode; @@ -241,7 +243,7 @@ class HookConnectorTest extends TestCase { $dispatcherSourceNode = null; /** @var Node $dispatcherTargetNode */ $dispatcherTargetNode = null; - $this->eventDispatcher->addListener($expectedLegacyEvent, function ($event) use (&$dispatcherSourceNode, &$dispatcherTargetNode, &$dispatcherCalled) { + $this->eventDispatcher->addListener($expectedLegacyEvent, function ($event) use (&$dispatcherSourceNode, &$dispatcherTargetNode, &$dispatcherCalled): void { /** @var GenericEvent|APIGenericEvent $event */ $dispatcherCalled = true; [$dispatcherSourceNode, $dispatcherTargetNode] = $event->getSubject(); @@ -252,7 +254,7 @@ class HookConnectorTest extends TestCase { $newDispatcherSourceNode = null; /** @var Node $dispatcherTargetNode */ $newDispatcherTargetNode = null; - $this->eventDispatcher->addListener($expectedEvent, function ($event) use ($expectedEvent, &$newDispatcherSourceNode, &$newDispatcherTargetNode, &$newDispatcherCalled) { + $this->eventDispatcher->addListener($expectedEvent, function ($event) use ($expectedEvent, &$newDispatcherSourceNode, &$newDispatcherTargetNode, &$newDispatcherCalled): void { if ($event instanceof $expectedEvent) { /** @var AbstractNodesEvent$event */ $newDispatcherCalled = true; @@ -283,7 +285,7 @@ class HookConnectorTest extends TestCase { /** @var Node $hookNode */ $hookNode = null; - $this->root->listen('\OC\Files', 'postDelete', function ($node) use (&$hookNode, &$hookCalled) { + $this->root->listen('\OC\Files', 'postDelete', function ($node) use (&$hookNode, &$hookCalled): void { $hookCalled = true; $hookNode = $node; }); @@ -291,7 +293,7 @@ class HookConnectorTest extends TestCase { $dispatcherCalled = false; /** @var Node $dispatcherNode */ $dispatcherNode = null; - $this->eventDispatcher->addListener('\OCP\Files::postDelete', function ($event) use (&$dispatcherCalled, &$dispatcherNode) { + $this->eventDispatcher->addListener('\OCP\Files::postDelete', function ($event) use (&$dispatcherCalled, &$dispatcherNode): void { /** @var GenericEvent|APIGenericEvent $event */ $dispatcherCalled = true; $dispatcherNode = $event->getSubject(); @@ -300,7 +302,7 @@ class HookConnectorTest extends TestCase { $newDispatcherCalled = false; /** @var Node $dispatcherNode */ $newDispatcherNode = null; - $this->eventDispatcher->addListener(NodeDeletedEvent::class, function ($event) use (&$newDispatcherCalled, &$newDispatcherNode) { + $this->eventDispatcher->addListener(NodeDeletedEvent::class, function ($event) use (&$newDispatcherCalled, &$newDispatcherNode): void { if ($event instanceof NodeDeletedEvent) { /** @var AbstractNodeEvent $event */ $newDispatcherCalled = true; diff --git a/tests/lib/Files/Node/IntegrationTest.php b/tests/lib/Files/Node/IntegrationTest.php index c90a6115f2a..6bd956326e9 100644 --- a/tests/lib/Files/Node/IntegrationTest.php +++ b/tests/lib/Files/Node/IntegrationTest.php @@ -16,6 +16,7 @@ use OCP\Files\Config\IUserMountCache; use OCP\Files\Mount\IMountManager; use OCP\ICacheFactory; use OCP\IUserManager; +use OCP\Server; use Psr\Log\LoggerInterface; use Test\Traits\UserTrait; @@ -47,7 +48,7 @@ class IntegrationTest extends \Test\TestCase { protected function setUp(): void { parent::setUp(); - $manager = \OCP\Server::get(IMountManager::class); + $manager = Server::get(IMountManager::class); \OC_Hook::clear('OC_Filesystem'); @@ -64,7 +65,7 @@ class IntegrationTest extends \Test\TestCase { $manager, $this->view, $user, - \OCP\Server::get(IUserMountCache::class), + Server::get(IUserMountCache::class), $this->createMock(LoggerInterface::class), $this->createMock(IUserManager::class), $this->createMock(IEventDispatcher::class), diff --git a/tests/lib/Files/Node/NodeTestCase.php b/tests/lib/Files/Node/NodeTestCase.php index a2b8a3ddffe..6da4e1e9317 100644 --- a/tests/lib/Files/Node/NodeTestCase.php +++ b/tests/lib/Files/Node/NodeTestCase.php @@ -9,14 +9,19 @@ namespace Test\Files\Node; use OC\Files\FileInfo; use OC\Files\Mount\Manager; +use OC\Files\Node\File; +use OC\Files\Node\Folder; use OC\Files\Node\Root; use OC\Files\View; use OC\Memcache\ArrayCache; +use OCP\Constants; use OCP\EventDispatcher\IEventDispatcher; +use OCP\Files\InvalidPathException; use OCP\Files\IRootFolder; use OCP\Files\Mount\IMountPoint; use OCP\Files\Node; use OCP\Files\NotFoundException; +use OCP\Files\NotPermittedException; use OCP\Files\Storage\IStorage; use OCP\ICacheFactory; use OCP\IUser; @@ -139,7 +144,7 @@ abstract class NodeTestCase extends \Test\TestCase { $this->view->expects($this->once()) ->method('getFileInfo') ->with('/bar/foo') - ->willReturn($this->getFileInfo(['permissions' => \OCP\Constants::PERMISSION_ALL])); + ->willReturn($this->getFileInfo(['permissions' => Constants::PERMISSION_ALL])); $this->view->expects($this->once()) ->method($this->getViewDeleteMethod()) @@ -156,7 +161,7 @@ abstract class NodeTestCase extends \Test\TestCase { /** * @param \OC\Files\Node\File $node */ - $preListener = function ($node) use (&$test, &$hooksRun) { + $preListener = function ($node) use (&$test, &$hooksRun): void { $test->assertInstanceOf($this->getNodeClass(), $node); $test->assertEquals('foo', $node->getInternalPath()); $test->assertEquals('/bar/foo', $node->getPath()); @@ -167,7 +172,7 @@ abstract class NodeTestCase extends \Test\TestCase { /** * @param \OC\Files\Node\File $node */ - $postListener = function ($node) use (&$test, &$hooksRun) { + $postListener = function ($node) use (&$test, &$hooksRun): void { $test->assertInstanceOf($this->getNonExistingNodeClass(), $node); $test->assertEquals('foo', $node->getInternalPath()); $test->assertEquals('/bar/foo', $node->getPath()); @@ -176,7 +181,7 @@ abstract class NodeTestCase extends \Test\TestCase { $hooksRun++; }; - $root = new \OC\Files\Node\Root( + $root = new Root( $this->manager, $this->view, $this->user, @@ -193,7 +198,7 @@ abstract class NodeTestCase extends \Test\TestCase { $this->view->expects($this->any()) ->method('getFileInfo') ->with('/bar/foo') - ->willReturn($this->getFileInfo(['permissions' => \OCP\Constants::PERMISSION_ALL, 'fileid' => 1, 'mimetype' => 'text/plain'], 'foo')); + ->willReturn($this->getFileInfo(['permissions' => Constants::PERMISSION_ALL, 'fileid' => 1, 'mimetype' => 'text/plain'], 'foo')); $this->view->expects($this->once()) ->method($this->getViewDeleteMethod()) @@ -207,7 +212,7 @@ abstract class NodeTestCase extends \Test\TestCase { public function testDeleteNotPermitted(): void { - $this->expectException(\OCP\Files\NotPermittedException::class); + $this->expectException(NotPermittedException::class); $this->root->expects($this->any()) ->method('getUser') @@ -216,7 +221,7 @@ abstract class NodeTestCase extends \Test\TestCase { $this->view->expects($this->once()) ->method('getFileInfo') ->with('/bar/foo') - ->willReturn($this->getFileInfo(['permissions' => \OCP\Constants::PERMISSION_READ])); + ->willReturn($this->getFileInfo(['permissions' => Constants::PERMISSION_READ])); $node = $this->createTestNode($this->root, $this->view, '/bar/foo'); $node->delete(); @@ -397,7 +402,7 @@ abstract class NodeTestCase extends \Test\TestCase { $this->view->expects($this->once()) ->method('getFileInfo') ->with('/bar/foo') - ->willReturn($this->getFileInfo(['permissions' => \OCP\Constants::PERMISSION_ALL])); + ->willReturn($this->getFileInfo(['permissions' => Constants::PERMISSION_ALL])); $node = $this->createTestNode($this->root, $this->view, '/bar/foo'); $node->touch(100); @@ -410,7 +415,7 @@ abstract class NodeTestCase extends \Test\TestCase { /** * @param \OC\Files\Node\File $node */ - $preListener = function ($node) use (&$test, &$hooksRun) { + $preListener = function ($node) use (&$test, &$hooksRun): void { $test->assertEquals('foo', $node->getInternalPath()); $test->assertEquals('/bar/foo', $node->getPath()); $hooksRun++; @@ -419,13 +424,13 @@ abstract class NodeTestCase extends \Test\TestCase { /** * @param \OC\Files\Node\File $node */ - $postListener = function ($node) use (&$test, &$hooksRun) { + $postListener = function ($node) use (&$test, &$hooksRun): void { $test->assertEquals('foo', $node->getInternalPath()); $test->assertEquals('/bar/foo', $node->getPath()); $hooksRun++; }; - $root = new \OC\Files\Node\Root( + $root = new Root( $this->manager, $this->view, $this->user, @@ -446,7 +451,7 @@ abstract class NodeTestCase extends \Test\TestCase { $this->view->expects($this->any()) ->method('getFileInfo') ->with('/bar/foo') - ->willReturn($this->getFileInfo(['permissions' => \OCP\Constants::PERMISSION_ALL], 'foo')); + ->willReturn($this->getFileInfo(['permissions' => Constants::PERMISSION_ALL], 'foo')); $node = $this->createTestNode($root, $this->view, '/bar/foo'); $node->touch(100); @@ -455,7 +460,7 @@ abstract class NodeTestCase extends \Test\TestCase { public function testTouchNotPermitted(): void { - $this->expectException(\OCP\Files\NotPermittedException::class); + $this->expectException(NotPermittedException::class); $this->root->expects($this->any()) ->method('getUser') @@ -464,7 +469,7 @@ abstract class NodeTestCase extends \Test\TestCase { $this->view->expects($this->any()) ->method('getFileInfo') ->with('/bar/foo') - ->willReturn($this->getFileInfo(['permissions' => \OCP\Constants::PERMISSION_READ])); + ->willReturn($this->getFileInfo(['permissions' => Constants::PERMISSION_READ])); $node = $this->createTestNode($this->root, $this->view, '/bar/foo'); $node->touch(100); @@ -472,7 +477,7 @@ abstract class NodeTestCase extends \Test\TestCase { public function testInvalidPath(): void { - $this->expectException(\OCP\Files\InvalidPathException::class); + $this->expectException(InvalidPathException::class); $node = $this->createTestNode($this->root, $this->view, '/../foo'); $node->getFileInfo(); @@ -486,10 +491,10 @@ abstract class NodeTestCase extends \Test\TestCase { $this->view->expects($this->any()) ->method('getFileInfo') - ->willReturn($this->getFileInfo(['permissions' => \OCP\Constants::PERMISSION_ALL, 'fileid' => 3])); + ->willReturn($this->getFileInfo(['permissions' => Constants::PERMISSION_ALL, 'fileid' => 3])); $node = $this->createTestNode($this->root, $this->view, '/bar/foo'); - $parentNode = new \OC\Files\Node\Folder($this->root, $this->view, '/bar'); + $parentNode = new Folder($this->root, $this->view, '/bar'); $newNode = $this->createTestNode($this->root, $this->view, '/bar/asd'); $this->root->method('get') @@ -505,7 +510,7 @@ abstract class NodeTestCase extends \Test\TestCase { public function testCopyNotPermitted(): void { - $this->expectException(\OCP\Files\NotPermittedException::class); + $this->expectException(NotPermittedException::class); /** * @var \OC\Files\Storage\Storage | \PHPUnit\Framework\MockObject\MockObject $storage @@ -520,10 +525,10 @@ abstract class NodeTestCase extends \Test\TestCase { $this->view->expects($this->any()) ->method('getFileInfo') - ->willReturn($this->getFileInfo(['permissions' => \OCP\Constants::PERMISSION_READ, 'fileid' => 3])); + ->willReturn($this->getFileInfo(['permissions' => Constants::PERMISSION_READ, 'fileid' => 3])); $node = $this->createTestNode($this->root, $this->view, '/bar/foo'); - $parentNode = new \OC\Files\Node\Folder($this->root, $this->view, '/bar'); + $parentNode = new Folder($this->root, $this->view, '/bar'); $this->root->expects($this->once()) ->method('get') @@ -536,7 +541,7 @@ abstract class NodeTestCase extends \Test\TestCase { public function testCopyNoParent(): void { - $this->expectException(\OCP\Files\NotFoundException::class); + $this->expectException(NotFoundException::class); $this->view->expects($this->never()) ->method('copy'); @@ -546,20 +551,20 @@ abstract class NodeTestCase extends \Test\TestCase { $this->root->expects($this->once()) ->method('get') ->with('/bar/asd') - ->will($this->throwException(new NotFoundException())); + ->willThrowException(new NotFoundException()); $node->copy('/bar/asd/foo'); } public function testCopyParentIsFile(): void { - $this->expectException(\OCP\Files\NotPermittedException::class); + $this->expectException(NotPermittedException::class); $this->view->expects($this->never()) ->method('copy'); $node = $this->createTestNode($this->root, $this->view, '/bar/foo'); - $parentNode = new \OC\Files\Node\File($this->root, $this->view, '/bar'); + $parentNode = new File($this->root, $this->view, '/bar'); $this->root->expects($this->once()) ->method('get') @@ -578,10 +583,10 @@ abstract class NodeTestCase extends \Test\TestCase { $this->view->expects($this->any()) ->method('getFileInfo') - ->willReturn($this->getFileInfo(['permissions' => \OCP\Constants::PERMISSION_ALL, 'fileid' => 1])); + ->willReturn($this->getFileInfo(['permissions' => Constants::PERMISSION_ALL, 'fileid' => 1])); $node = $this->createTestNode($this->root, $this->view, '/bar/foo'); - $parentNode = new \OC\Files\Node\Folder($this->root, $this->view, '/bar'); + $parentNode = new Folder($this->root, $this->view, '/bar'); $this->root->expects($this->any()) ->method('get') @@ -621,13 +626,13 @@ abstract class NodeTestCase extends \Test\TestCase { $this->view->expects($this->any()) ->method('getFileInfo') - ->willReturn($this->getFileInfo(['permissions' => \OCP\Constants::PERMISSION_ALL, 'fileid' => 1])); + ->willReturn($this->getFileInfo(['permissions' => Constants::PERMISSION_ALL, 'fileid' => 1])); /** * @var \OC\Files\Node\File|\PHPUnit\Framework\MockObject\MockObject $node */ $node = $this->createTestNode($root, $this->view, '/bar/foo'); - $parentNode = new \OC\Files\Node\Folder($root, $this->view, '/bar'); + $parentNode = new Folder($root, $this->view, '/bar'); $targetTestNode = $this->createTestNode($root, $this->view, '/bar/asd'); $root->expects($this->any()) @@ -636,7 +641,7 @@ abstract class NodeTestCase extends \Test\TestCase { $hooksRun = 0; - $preListener = function (Node $sourceNode, Node $targetNode) use (&$hooksRun, $node) { + $preListener = function (Node $sourceNode, Node $targetNode) use (&$hooksRun, $node): void { $this->assertSame($node, $sourceNode); $this->assertInstanceOf($this->getNodeClass(), $sourceNode); $this->assertInstanceOf($this->getNonExistingNodeClass(), $targetNode); @@ -644,7 +649,7 @@ abstract class NodeTestCase extends \Test\TestCase { $hooksRun++; }; - $postListener = function (Node $sourceNode, Node $targetNode) use (&$hooksRun, $node, $targetTestNode) { + $postListener = function (Node $sourceNode, Node $targetNode) use (&$hooksRun, $node, $targetTestNode): void { $this->assertSame($node, $sourceNode); $this->assertNotSame($node, $targetNode); $this->assertSame($targetTestNode, $targetNode); @@ -653,13 +658,13 @@ abstract class NodeTestCase extends \Test\TestCase { $hooksRun++; }; - $preWriteListener = function (Node $targetNode) use (&$hooksRun) { + $preWriteListener = function (Node $targetNode) use (&$hooksRun): void { $this->assertInstanceOf($this->getNonExistingNodeClass(), $targetNode); $this->assertEquals('/bar/asd', $targetNode->getPath()); $hooksRun++; }; - $postWriteListener = function (Node $targetNode) use (&$hooksRun, $targetTestNode) { + $postWriteListener = function (Node $targetNode) use (&$hooksRun, $targetTestNode): void { $this->assertSame($targetTestNode, $targetNode); $hooksRun++; }; @@ -676,17 +681,17 @@ abstract class NodeTestCase extends \Test\TestCase { public function testMoveNotPermitted(): void { - $this->expectException(\OCP\Files\NotPermittedException::class); + $this->expectException(NotPermittedException::class); $this->view->expects($this->any()) ->method('getFileInfo') - ->willReturn($this->getFileInfo(['permissions' => \OCP\Constants::PERMISSION_READ])); + ->willReturn($this->getFileInfo(['permissions' => Constants::PERMISSION_READ])); $this->view->expects($this->never()) ->method('rename'); $node = $this->createTestNode($this->root, $this->view, '/bar/foo'); - $parentNode = new \OC\Files\Node\Folder($this->root, $this->view, '/bar'); + $parentNode = new Folder($this->root, $this->view, '/bar'); $this->root->expects($this->once()) ->method('get') @@ -698,7 +703,7 @@ abstract class NodeTestCase extends \Test\TestCase { public function testMoveNoParent(): void { - $this->expectException(\OCP\Files\NotFoundException::class); + $this->expectException(NotFoundException::class); /** * @var \OC\Files\Storage\Storage | \PHPUnit\Framework\MockObject\MockObject $storage @@ -713,20 +718,20 @@ abstract class NodeTestCase extends \Test\TestCase { $this->root->expects($this->once()) ->method('get') ->with('/bar') - ->will($this->throwException(new NotFoundException())); + ->willThrowException(new NotFoundException()); $node->move('/bar/asd'); } public function testMoveParentIsFile(): void { - $this->expectException(\OCP\Files\NotPermittedException::class); + $this->expectException(NotPermittedException::class); $this->view->expects($this->never()) ->method('rename'); $node = $this->createTestNode($this->root, $this->view, '/bar/foo'); - $parentNode = new \OC\Files\Node\File($this->root, $this->view, '/bar'); + $parentNode = new File($this->root, $this->view, '/bar'); $this->root->expects($this->once()) ->method('get') @@ -738,7 +743,7 @@ abstract class NodeTestCase extends \Test\TestCase { public function testMoveFailed(): void { - $this->expectException(\OCP\Files\NotPermittedException::class); + $this->expectException(NotPermittedException::class); $this->view->expects($this->any()) ->method('rename') @@ -747,10 +752,10 @@ abstract class NodeTestCase extends \Test\TestCase { $this->view->expects($this->any()) ->method('getFileInfo') - ->willReturn($this->getFileInfo(['permissions' => \OCP\Constants::PERMISSION_ALL, 'fileid' => 1])); + ->willReturn($this->getFileInfo(['permissions' => Constants::PERMISSION_ALL, 'fileid' => 1])); $node = $this->createTestNode($this->root, $this->view, '/bar/foo'); - $parentNode = new \OC\Files\Node\Folder($this->root, $this->view, '/bar'); + $parentNode = new Folder($this->root, $this->view, '/bar'); $this->root->expects($this->any()) ->method('get') @@ -761,7 +766,7 @@ abstract class NodeTestCase extends \Test\TestCase { public function testCopyFailed(): void { - $this->expectException(\OCP\Files\NotPermittedException::class); + $this->expectException(NotPermittedException::class); $this->view->expects($this->any()) ->method('copy') @@ -770,10 +775,10 @@ abstract class NodeTestCase extends \Test\TestCase { $this->view->expects($this->any()) ->method('getFileInfo') - ->willReturn($this->getFileInfo(['permissions' => \OCP\Constants::PERMISSION_ALL, 'fileid' => 1])); + ->willReturn($this->getFileInfo(['permissions' => Constants::PERMISSION_ALL, 'fileid' => 1])); $node = $this->createTestNode($this->root, $this->view, '/bar/foo'); - $parentNode = new \OC\Files\Node\Folder($this->root, $this->view, '/bar'); + $parentNode = new Folder($this->root, $this->view, '/bar'); $this->root->expects($this->any()) ->method('get') diff --git a/tests/lib/Files/Node/RootTest.php b/tests/lib/Files/Node/RootTest.php index f2ef1a0e3ee..979ed1c6dcb 100644 --- a/tests/lib/Files/Node/RootTest.php +++ b/tests/lib/Files/Node/RootTest.php @@ -10,10 +10,14 @@ namespace Test\Files\Node; use OC\Files\FileInfo; use OC\Files\Mount\Manager; use OC\Files\Node\Folder; +use OC\Files\Node\Root; use OC\Files\View; use OC\Memcache\ArrayCache; +use OC\User\NoUserException; use OCP\Cache\CappedMemoryCache; use OCP\EventDispatcher\IEventDispatcher; +use OCP\Files\NotFoundException; +use OCP\Files\NotPermittedException; use OCP\ICacheFactory; use OCP\IUser; use OCP\IUserManager; @@ -83,7 +87,7 @@ class RootTest extends \Test\TestCase { ->disableOriginalConstructor() ->getMock(); $view = $this->getRootViewMock(); - $root = new \OC\Files\Node\Root( + $root = new Root( $this->manager, $view, $this->user, @@ -107,7 +111,7 @@ class RootTest extends \Test\TestCase { public function testGetNotFound(): void { - $this->expectException(\OCP\Files\NotFoundException::class); + $this->expectException(NotFoundException::class); /** * @var \OC\Files\Storage\Storage $storage @@ -116,7 +120,7 @@ class RootTest extends \Test\TestCase { ->disableOriginalConstructor() ->getMock(); $view = $this->getRootViewMock(); - $root = new \OC\Files\Node\Root( + $root = new Root( $this->manager, $view, $this->user, @@ -138,10 +142,10 @@ class RootTest extends \Test\TestCase { public function testGetInvalidPath(): void { - $this->expectException(\OCP\Files\NotPermittedException::class); + $this->expectException(NotPermittedException::class); $view = $this->getRootViewMock(); - $root = new \OC\Files\Node\Root( + $root = new Root( $this->manager, $view, $this->user, @@ -157,10 +161,10 @@ class RootTest extends \Test\TestCase { public function testGetNoStorages(): void { - $this->expectException(\OCP\Files\NotFoundException::class); + $this->expectException(NotFoundException::class); $view = $this->getRootViewMock(); - $root = new \OC\Files\Node\Root( + $root = new Root( $this->manager, $view, $this->user, @@ -175,7 +179,7 @@ class RootTest extends \Test\TestCase { } public function testGetUserFolder(): void { - $root = new \OC\Files\Node\Root( + $root = new Root( $this->manager, $this->getRootViewMock(), $this->user, @@ -214,10 +218,10 @@ class RootTest extends \Test\TestCase { public function testGetUserFolderWithNoUserObj(): void { - $this->expectException(\OC\User\NoUserException::class); + $this->expectException(NoUserException::class); $this->expectExceptionMessage('Backends provided no user object'); - $root = new \OC\Files\Node\Root( + $root = new Root( $this->createMock(Manager::class), $this->getRootViewMock(), null, diff --git a/tests/lib/Files/ObjectStore/AzureTest.php b/tests/lib/Files/ObjectStore/AzureTest.php index 1103b15ecd2..3c07f69f65d 100644 --- a/tests/lib/Files/ObjectStore/AzureTest.php +++ b/tests/lib/Files/ObjectStore/AzureTest.php @@ -7,13 +7,15 @@ namespace Test\Files\ObjectStore; use OC\Files\ObjectStore\Azure; +use OCP\IConfig; +use OCP\Server; /** * @group PRIMARY-azure */ class AzureTest extends ObjectStoreTestCase { protected function getInstance() { - $config = \OC::$server->getConfig()->getSystemValue('objectstore'); + $config = Server::get(IConfig::class)->getSystemValue('objectstore'); if (!is_array($config) || $config['class'] !== 'OC\\Files\\ObjectStore\\Azure') { $this->markTestSkipped('objectstore not configured for azure'); } diff --git a/tests/lib/Files/ObjectStore/ObjectStoreStorageTest.php b/tests/lib/Files/ObjectStore/ObjectStoreStorageTest.php index 508f328fae2..cca75d4f35e 100644 --- a/tests/lib/Files/ObjectStore/ObjectStoreStorageTest.php +++ b/tests/lib/Files/ObjectStore/ObjectStoreStorageTest.php @@ -10,6 +10,7 @@ namespace Test\Files\ObjectStore; use OC\Files\ObjectStore\StorageObjectStore; use OC\Files\Storage\Temporary; use OC\Files\Storage\Wrapper\Jail; +use OCP\Constants; use OCP\Files\ObjectStore\IObjectStore; use Test\Files\Storage\Storage; @@ -231,13 +232,13 @@ class ObjectStoreStorageTest extends Storage { $this->instance->file_put_contents('test.txt', 'foo'); $this->assertTrue($cache->inCache('test.txt')); - $cache->update($cache->getId('test.txt'), ['permissions' => \OCP\Constants::PERMISSION_READ]); - $this->assertEquals(\OCP\Constants::PERMISSION_READ, $this->instance->getPermissions('test.txt')); + $cache->update($cache->getId('test.txt'), ['permissions' => Constants::PERMISSION_READ]); + $this->assertEquals(Constants::PERMISSION_READ, $this->instance->getPermissions('test.txt')); $this->assertTrue($this->instance->copy('test.txt', 'new.txt')); $this->assertTrue($cache->inCache('new.txt')); - $this->assertEquals(\OCP\Constants::PERMISSION_READ, $this->instance->getPermissions('new.txt')); + $this->assertEquals(Constants::PERMISSION_READ, $this->instance->getPermissions('new.txt')); } /** @@ -254,13 +255,13 @@ class ObjectStoreStorageTest extends Storage { $instance->file_put_contents('test.txt', 'foo'); $this->assertTrue($cache->inCache('test.txt')); - $cache->update($cache->getId('test.txt'), ['permissions' => \OCP\Constants::PERMISSION_READ]); - $this->assertEquals(\OCP\Constants::PERMISSION_READ, $instance->getPermissions('test.txt')); + $cache->update($cache->getId('test.txt'), ['permissions' => Constants::PERMISSION_READ]); + $this->assertEquals(Constants::PERMISSION_READ, $instance->getPermissions('test.txt')); $this->assertTrue($instance->copy('test.txt', 'new.txt')); $this->assertTrue($cache->inCache('new.txt')); - $this->assertEquals(\OCP\Constants::PERMISSION_ALL, $instance->getPermissions('new.txt')); + $this->assertEquals(Constants::PERMISSION_ALL, $instance->getPermissions('new.txt')); } public function testCopyFolderSize(): void { diff --git a/tests/lib/Files/ObjectStore/S3Test.php b/tests/lib/Files/ObjectStore/S3Test.php index 76fc80c975f..d3c282d0427 100644 --- a/tests/lib/Files/ObjectStore/S3Test.php +++ b/tests/lib/Files/ObjectStore/S3Test.php @@ -8,6 +8,8 @@ namespace Test\Files\ObjectStore; use Icewind\Streams\Wrapper; use OC\Files\ObjectStore\S3; +use OCP\IConfig; +use OCP\Server; class MultiPartUploadS3 extends S3 { public function writeObject($urn, $stream, ?string $mimetype = null) { @@ -52,7 +54,7 @@ class S3Test extends ObjectStoreTestCase { } protected function getInstance() { - $config = \OC::$server->getConfig()->getSystemValue('objectstore'); + $config = Server::get(IConfig::class)->getSystemValue('objectstore'); if (!is_array($config) || $config['class'] !== S3::class) { $this->markTestSkipped('objectstore not configured for s3'); } diff --git a/tests/lib/Files/ObjectStore/SwiftTest.php b/tests/lib/Files/ObjectStore/SwiftTest.php index 9fb8c9bb68e..2321d8eafda 100644 --- a/tests/lib/Files/ObjectStore/SwiftTest.php +++ b/tests/lib/Files/ObjectStore/SwiftTest.php @@ -8,6 +8,8 @@ namespace Test\Files\ObjectStore; use OC\Files\ObjectStore\Swift; +use OCP\IConfig; +use OCP\Server; /** * @group PRIMARY-swift @@ -17,7 +19,7 @@ class SwiftTest extends ObjectStoreTestCase { * @return \OCP\Files\ObjectStore\IObjectStore */ protected function getInstance() { - $config = \OC::$server->getConfig()->getSystemValue('objectstore'); + $config = Server::get(IConfig::class)->getSystemValue('objectstore'); if (!is_array($config) || $config['class'] !== 'OC\\Files\\ObjectStore\\Swift') { $this->markTestSkipped('objectstore not configured for swift'); } diff --git a/tests/lib/Files/PathVerificationTest.php b/tests/lib/Files/PathVerificationTest.php index d6dff445c0f..8e4dfd1bb1e 100644 --- a/tests/lib/Files/PathVerificationTest.php +++ b/tests/lib/Files/PathVerificationTest.php @@ -10,6 +10,8 @@ namespace Test\Files; use OC\Files\Storage\Local; use OC\Files\View; use OCP\Files\InvalidPathException; +use OCP\IDBConnection; +use OCP\Server; /** * Class PathVerificationTest @@ -31,7 +33,7 @@ class PathVerificationTest extends \Test\TestCase { public function testPathVerificationFileNameTooLong(): void { - $this->expectException(\OCP\Files\InvalidPathException::class); + $this->expectException(InvalidPathException::class); $this->expectExceptionMessage('Filename is too long'); $fileName = str_repeat('a', 500); @@ -43,7 +45,7 @@ class PathVerificationTest extends \Test\TestCase { * @dataProvider providesEmptyFiles */ public function testPathVerificationEmptyFileName($fileName): void { - $this->expectException(\OCP\Files\InvalidPathException::class); + $this->expectException(InvalidPathException::class); $this->expectExceptionMessage('Empty filename is not allowed'); $this->view->verifyPath('', $fileName); @@ -60,7 +62,7 @@ class PathVerificationTest extends \Test\TestCase { * @dataProvider providesDotFiles */ public function testPathVerificationDotFiles($fileName): void { - $this->expectException(\OCP\Files\InvalidPathException::class); + $this->expectException(InvalidPathException::class); $this->expectExceptionMessage('Dot files are not allowed'); $this->view->verifyPath('', $fileName); @@ -83,7 +85,7 @@ class PathVerificationTest extends \Test\TestCase { * @dataProvider providesAstralPlane */ public function testPathVerificationAstralPlane($fileName): void { - $connection = \OC::$server->getDatabaseConnection(); + $connection = Server::get(IDBConnection::class); if (!$connection->supports4ByteText()) { $this->expectException(InvalidPathException::class); diff --git a/tests/lib/Files/Storage/CommonTest.php b/tests/lib/Files/Storage/CommonTest.php index 529615f3733..d6904665904 100644 --- a/tests/lib/Files/Storage/CommonTest.php +++ b/tests/lib/Files/Storage/CommonTest.php @@ -14,6 +14,7 @@ use OCP\Files\IFilenameValidator; use OCP\Files\InvalidCharacterInPathException; use OCP\Files\InvalidPathException; use OCP\ITempManager; +use OCP\Server; use PHPUnit\Framework\MockObject\MockObject; /** @@ -33,7 +34,7 @@ class CommonTest extends Storage { $this->filenameValidator = $this->createMock(IFilenameValidator::class); $this->overwriteService(IFilenameValidator::class, $this->filenameValidator); - $this->tmpDir = \OCP\Server::get(ITempManager::class)->getTemporaryFolder(); + $this->tmpDir = Server::get(ITempManager::class)->getTemporaryFolder(); $this->instance = new \OC\Files\Storage\CommonTest(['datadir' => $this->tmpDir]); } diff --git a/tests/lib/Files/Storage/CopyDirectoryTest.php b/tests/lib/Files/Storage/CopyDirectoryTest.php index e434c6b787f..054101510b7 100644 --- a/tests/lib/Files/Storage/CopyDirectoryTest.php +++ b/tests/lib/Files/Storage/CopyDirectoryTest.php @@ -7,6 +7,7 @@ namespace Test\Files\Storage; +use OC\Files\Storage\PolyFill\CopyDirectory; use OC\Files\Storage\Temporary; class StorageNoRecursiveCopy extends Temporary { @@ -19,7 +20,7 @@ class StorageNoRecursiveCopy extends Temporary { } class CopyDirectoryStorage extends StorageNoRecursiveCopy { - use \OC\Files\Storage\PolyFill\CopyDirectory; + use CopyDirectory; } /** diff --git a/tests/lib/Files/Storage/HomeTest.php b/tests/lib/Files/Storage/HomeTest.php index 26b81c6f1a0..f459ff5c23b 100644 --- a/tests/lib/Files/Storage/HomeTest.php +++ b/tests/lib/Files/Storage/HomeTest.php @@ -7,21 +7,21 @@ namespace Test\Files\Storage; +use OC\Files\Storage\Home; use OC\User\User; use OCP\Files; +use OCP\ITempManager; +use OCP\Server; class DummyUser extends User { - private $home; - - private $uid; - /** * @param string $uid * @param string $home */ - public function __construct($uid, $home) { - $this->uid = $uid; - $this->home = $home; + public function __construct( + private $uid, + private $home, + ) { } public function getHome() { @@ -56,10 +56,10 @@ class HomeTest extends Storage { protected function setUp(): void { parent::setUp(); - $this->tmpDir = \OC::$server->getTempManager()->getTemporaryFolder(); + $this->tmpDir = Server::get(ITempManager::class)->getTemporaryFolder(); $this->userId = $this->getUniqueID('user_'); $this->user = new DummyUser($this->userId, $this->tmpDir); - $this->instance = new \OC\Files\Storage\Home(['user' => $this->user]); + $this->instance = new Home(['user' => $this->user]); } protected function tearDown(): void { diff --git a/tests/lib/Files/Storage/LocalTest.php b/tests/lib/Files/Storage/LocalTest.php index 13317fad7bb..e3953b7bde5 100644 --- a/tests/lib/Files/Storage/LocalTest.php +++ b/tests/lib/Files/Storage/LocalTest.php @@ -7,8 +7,13 @@ namespace Test\Files\Storage; +use OC\Files\Storage\Local; use OC\Files\Storage\Wrapper\Jail; use OCP\Files; +use OCP\Files\ForbiddenException; +use OCP\Files\StorageNotAvailableException; +use OCP\ITempManager; +use OCP\Server; /** * Class LocalTest @@ -26,8 +31,8 @@ class LocalTest extends Storage { protected function setUp(): void { parent::setUp(); - $this->tmpDir = \OC::$server->getTempManager()->getTemporaryFolder(); - $this->instance = new \OC\Files\Storage\Local(['datadir' => $this->tmpDir]); + $this->tmpDir = Server::get(ITempManager::class)->getTemporaryFolder(); + $this->instance = new Local(['datadir' => $this->tmpDir]); } protected function tearDown(): void { @@ -55,19 +60,19 @@ class LocalTest extends Storage { public function testInvalidArgumentsEmptyArray(): void { $this->expectException(\InvalidArgumentException::class); - new \OC\Files\Storage\Local([]); + new Local([]); } public function testInvalidArgumentsNoArray(): void { $this->expectException(\InvalidArgumentException::class); - new \OC\Files\Storage\Local([]); + new Local([]); } public function testDisallowSymlinksOutsideDatadir(): void { - $this->expectException(\OCP\Files\ForbiddenException::class); + $this->expectException(ForbiddenException::class); $subDir1 = $this->tmpDir . 'sub1'; $subDir2 = $this->tmpDir . 'sub2'; @@ -77,7 +82,7 @@ class LocalTest extends Storage { symlink($subDir2, $sym); - $storage = new \OC\Files\Storage\Local(['datadir' => $subDir1]); + $storage = new Local(['datadir' => $subDir1]); $storage->file_put_contents('sym/foo', 'bar'); } @@ -91,7 +96,7 @@ class LocalTest extends Storage { symlink($subDir2, $sym); - $storage = new \OC\Files\Storage\Local(['datadir' => $subDir1]); + $storage = new Local(['datadir' => $subDir1]); $storage->file_put_contents('sym/foo', 'bar'); $this->addToAssertionCount(1); @@ -129,12 +134,12 @@ class LocalTest extends Storage { } public function testUnavailableExternal(): void { - $this->expectException(\OCP\Files\StorageNotAvailableException::class); - $this->instance = new \OC\Files\Storage\Local(['datadir' => $this->tmpDir . '/unexist', 'isExternal' => true]); + $this->expectException(StorageNotAvailableException::class); + $this->instance = new Local(['datadir' => $this->tmpDir . '/unexist', 'isExternal' => true]); } public function testUnavailableNonExternal(): void { - $this->instance = new \OC\Files\Storage\Local(['datadir' => $this->tmpDir . '/unexist']); + $this->instance = new Local(['datadir' => $this->tmpDir . '/unexist']); // no exception thrown $this->assertNotNull($this->instance); } diff --git a/tests/lib/Files/Storage/Storage.php b/tests/lib/Files/Storage/Storage.php index 99162e12834..3e239d005b7 100644 --- a/tests/lib/Files/Storage/Storage.php +++ b/tests/lib/Files/Storage/Storage.php @@ -8,6 +8,7 @@ namespace Test\Files\Storage; use OC\Files\Cache\Watcher; +use OC\Files\Storage\Wrapper\Wrapper; use OCP\Files\Storage\IStorage; use OCP\Files\Storage\IWriteStreamStorage; @@ -327,7 +328,7 @@ abstract class Storage extends \Test\TestCase { * no change. */ public function testCheckUpdate(): void { - if ($this->instance instanceof \OC\Files\Storage\Wrapper\Wrapper) { + if ($this->instance instanceof Wrapper) { $this->markTestSkipped('Cannot test update check on wrappers'); } $textFile = \OC::$SERVERROOT . '/tests/data/lorem.txt'; diff --git a/tests/lib/Files/Storage/StorageFactoryTest.php b/tests/lib/Files/Storage/StorageFactoryTest.php index 83e8a7bf6eb..2bdc3592631 100644 --- a/tests/lib/Files/Storage/StorageFactoryTest.php +++ b/tests/lib/Files/Storage/StorageFactoryTest.php @@ -8,6 +8,7 @@ namespace Test\Files\Storage; use OC\Files\Mount\MountPoint; +use OC\Files\Storage\StorageFactory; use OC\Files\Storage\Wrapper\Wrapper; use OCP\Files\Mount\IMountPoint; use OCP\Files\Storage\IStorage; @@ -26,7 +27,7 @@ class DummyWrapper extends Wrapper { class StorageFactoryTest extends TestCase { public function testSimpleWrapper(): void { - $instance = new \OC\Files\Storage\StorageFactory(); + $instance = new StorageFactory(); $mount = new MountPoint('\OC\Files\Storage\Temporary', '/foo', [[]], $instance); $instance->addStorageWrapper('dummy', function ($mountPoint, IStorage $storage, IMountPoint $mount) { $this->assertInstanceOf('\OC\Files\Storage\Temporary', $storage); @@ -39,7 +40,7 @@ class StorageFactoryTest extends TestCase { } public function testRemoveWrapper(): void { - $instance = new \OC\Files\Storage\StorageFactory(); + $instance = new StorageFactory(); $mount = new MountPoint('\OC\Files\Storage\Temporary', '/foo', [[]], $instance); $instance->addStorageWrapper('dummy', function ($mountPoint, IStorage $storage) { return new DummyWrapper(['storage' => $storage]); @@ -50,7 +51,7 @@ class StorageFactoryTest extends TestCase { } public function testWrapperPriority(): void { - $instance = new \OC\Files\Storage\StorageFactory(); + $instance = new StorageFactory(); $mount = new MountPoint('\OC\Files\Storage\Temporary', '/foo', [[]], $instance); $instance->addStorageWrapper('dummy1', function ($mountPoint, IStorage $storage) { return new DummyWrapper(['storage' => $storage, 'data' => 1]); diff --git a/tests/lib/Files/Storage/Wrapper/AvailabilityTest.php b/tests/lib/Files/Storage/Wrapper/AvailabilityTest.php index 29277772358..8e2ead4a423 100644 --- a/tests/lib/Files/Storage/Wrapper/AvailabilityTest.php +++ b/tests/lib/Files/Storage/Wrapper/AvailabilityTest.php @@ -53,7 +53,7 @@ class AvailabilityTest extends \Test\TestCase { * */ public function testUnavailable(): void { - $this->expectException(\OCP\Files\StorageNotAvailableException::class); + $this->expectException(StorageNotAvailableException::class); $this->storage->expects($this->once()) ->method('getAvailability') @@ -82,7 +82,7 @@ class AvailabilityTest extends \Test\TestCase { ]; $this->storage->expects($this->exactly(2)) ->method('setAvailability') - ->willReturnCallback(function ($value) use (&$calls) { + ->willReturnCallback(function ($value) use (&$calls): void { $expected = array_shift($calls); $this->assertEquals($expected, $value); }); @@ -97,7 +97,7 @@ class AvailabilityTest extends \Test\TestCase { * */ public function testAvailableThrowStorageNotAvailable(): void { - $this->expectException(\OCP\Files\StorageNotAvailableException::class); + $this->expectException(StorageNotAvailableException::class); $this->storage->expects($this->once()) ->method('getAvailability') @@ -106,7 +106,7 @@ class AvailabilityTest extends \Test\TestCase { ->method('test'); $this->storage->expects($this->once()) ->method('mkdir') - ->will($this->throwException(new StorageNotAvailableException())); + ->willThrowException(new StorageNotAvailableException()); $this->storageCache->expects($this->once()) ->method('setAvailability') ->with($this->equalTo(false)); @@ -148,7 +148,7 @@ class AvailabilityTest extends \Test\TestCase { ->method('test'); $this->storage->expects($this->once()) ->method('mkdir') - ->will($this->throwException(new \Exception())); + ->willThrowException(new \Exception()); $this->storage->expects($this->never()) ->method('setAvailability'); diff --git a/tests/lib/Files/Storage/Wrapper/EncodingTest.php b/tests/lib/Files/Storage/Wrapper/EncodingTest.php index 9d8a1e16145..2d29e2d0952 100644 --- a/tests/lib/Files/Storage/Wrapper/EncodingTest.php +++ b/tests/lib/Files/Storage/Wrapper/EncodingTest.php @@ -7,6 +7,9 @@ namespace Test\Files\Storage\Wrapper; +use OC\Files\Storage\Temporary; +use OC\Files\Storage\Wrapper\Encoding; + class EncodingTest extends \Test\Files\Storage\Storage { public const NFD_NAME = 'ümlaut'; public const NFC_NAME = 'ümlaut'; @@ -18,8 +21,8 @@ class EncodingTest extends \Test\Files\Storage\Storage { protected function setUp(): void { parent::setUp(); - $this->sourceStorage = new \OC\Files\Storage\Temporary([]); - $this->instance = new \OC\Files\Storage\Wrapper\Encoding([ + $this->sourceStorage = new Temporary([]); + $this->instance = new Encoding([ 'storage' => $this->sourceStorage ]); } diff --git a/tests/lib/Files/Storage/Wrapper/EncryptionTest.php b/tests/lib/Files/Storage/Wrapper/EncryptionTest.php index 1c299fa989f..8065854ec50 100644 --- a/tests/lib/Files/Storage/Wrapper/EncryptionTest.php +++ b/tests/lib/Files/Storage/Wrapper/EncryptionTest.php @@ -8,7 +8,6 @@ namespace Test\Files\Storage\Wrapper; use Exception; -use OC; use OC\Encryption\Exceptions\ModuleDoesNotExistsException; use OC\Encryption\File; use OC\Encryption\Util; @@ -28,6 +27,8 @@ use OCP\Files\Cache\ICache; use OCP\Files\Mount\IMountPoint; use OCP\ICacheFactory; use OCP\IConfig; +use OCP\ITempManager; +use OCP\Server; use PHPUnit\Framework\MockObject\MockObject; use Psr\Log\LoggerInterface; use Test\Files\Storage\Storage; @@ -726,7 +727,7 @@ class EncryptionTest extends Storage { $storage2->expects($this->any()) ->method('fopen') ->willReturnCallback(function ($path, $mode) { - $temp = OC::$server->getTempManager(); + $temp = Server::get(ITempManager::class); return fopen($temp->getTemporaryFile(), $mode); }); $storage2->method('getId') @@ -775,7 +776,7 @@ class EncryptionTest extends Storage { $storage2->expects($this->any()) ->method('fopen') ->willReturnCallback(function ($path, $mode) { - $temp = OC::$server->getTempManager(); + $temp = Server::get(ITempManager::class); return fopen($temp->getTemporaryFile(), $mode); }); $storage2->method('getId') diff --git a/tests/lib/Files/Storage/Wrapper/JailTest.php b/tests/lib/Files/Storage/Wrapper/JailTest.php index fbc4e1d09ee..f7babfb609d 100644 --- a/tests/lib/Files/Storage/Wrapper/JailTest.php +++ b/tests/lib/Files/Storage/Wrapper/JailTest.php @@ -7,6 +7,10 @@ namespace Test\Files\Storage\Wrapper; +use OC\Files\Filesystem; +use OC\Files\Storage\Temporary; +use OC\Files\Storage\Wrapper\Jail; + class JailTest extends \Test\Files\Storage\Storage { /** * @var \OC\Files\Storage\Temporary @@ -15,9 +19,9 @@ class JailTest extends \Test\Files\Storage\Storage { protected function setUp(): void { parent::setUp(); - $this->sourceStorage = new \OC\Files\Storage\Temporary([]); + $this->sourceStorage = new Temporary([]); $this->sourceStorage->mkdir('foo'); - $this->instance = new \OC\Files\Storage\Wrapper\Jail([ + $this->instance = new Jail([ 'storage' => $this->sourceStorage, 'root' => 'foo' ]); @@ -28,7 +32,7 @@ class JailTest extends \Test\Files\Storage\Storage { $contents = []; $dh = $this->sourceStorage->opendir(''); while (($file = readdir($dh)) !== false) { - if (!\OC\Files\Filesystem::isIgnoredDir($file)) { + if (!Filesystem::isIgnoredDir($file)) { $contents[] = $file; } } diff --git a/tests/lib/Files/Storage/Wrapper/PermissionsMaskTest.php b/tests/lib/Files/Storage/Wrapper/PermissionsMaskTest.php index 5c0a035d094..003842dbbc2 100644 --- a/tests/lib/Files/Storage/Wrapper/PermissionsMaskTest.php +++ b/tests/lib/Files/Storage/Wrapper/PermissionsMaskTest.php @@ -7,6 +7,8 @@ namespace Test\Files\Storage\Wrapper; +use OC\Files\Storage\Temporary; +use OC\Files\Storage\Wrapper\PermissionsMask; use OC\Files\Storage\Wrapper\Wrapper; use OCP\Constants; use OCP\Files\Cache\IScanner; @@ -22,7 +24,7 @@ class PermissionsMaskTest extends \Test\Files\Storage\Storage { protected function setUp(): void { parent::setUp(); - $this->sourceStorage = new \OC\Files\Storage\Temporary([]); + $this->sourceStorage = new Temporary([]); $this->instance = $this->getMaskedStorage(Constants::PERMISSION_ALL); } @@ -32,7 +34,7 @@ class PermissionsMaskTest extends \Test\Files\Storage\Storage { } protected function getMaskedStorage($mask) { - return new \OC\Files\Storage\Wrapper\PermissionsMask([ + return new PermissionsMask([ 'storage' => $this->sourceStorage, 'mask' => $mask ]); @@ -127,7 +129,7 @@ class PermissionsMaskTest extends \Test\Files\Storage\Storage { public function testScanNewFilesNested(): void { $storage = $this->getMaskedStorage(Constants::PERMISSION_READ + Constants::PERMISSION_CREATE + Constants::PERMISSION_UPDATE); - $nestedStorage = new \OC\Files\Storage\Wrapper\PermissionsMask([ + $nestedStorage = new PermissionsMask([ 'storage' => $storage, 'mask' => Constants::PERMISSION_READ + Constants::PERMISSION_CREATE ]); @@ -149,7 +151,7 @@ class PermissionsMaskTest extends \Test\Files\Storage\Storage { $storage = $this->getMaskedStorage(Constants::PERMISSION_READ); $scanner = $storage->getScanner(); $called = false; - $scanner->listen('\OC\Files\Cache\Scanner', 'addToCache', function () use (&$called) { + $scanner->listen('\OC\Files\Cache\Scanner', 'addToCache', function () use (&$called): void { $called = true; }); $scanner->scan('foo', IScanner::SCAN_RECURSIVE, IScanner::REUSE_ETAG | IScanner::REUSE_SIZE); @@ -167,7 +169,7 @@ class PermissionsMaskTest extends \Test\Files\Storage\Storage { $wrappedStorage = new Wrapper(['storage' => $storage]); $scanner = $wrappedStorage->getScanner(); $called = false; - $scanner->listen('\OC\Files\Cache\Scanner', 'addToCache', function () use (&$called) { + $scanner->listen('\OC\Files\Cache\Scanner', 'addToCache', function () use (&$called): void { $called = true; }); $scanner->scan('foo', IScanner::SCAN_RECURSIVE, IScanner::REUSE_ETAG | IScanner::REUSE_SIZE); diff --git a/tests/lib/Files/Storage/Wrapper/QuotaTest.php b/tests/lib/Files/Storage/Wrapper/QuotaTest.php index 3115f1288a0..b2bcdfa32d8 100644 --- a/tests/lib/Files/Storage/Wrapper/QuotaTest.php +++ b/tests/lib/Files/Storage/Wrapper/QuotaTest.php @@ -10,7 +10,10 @@ namespace Test\Files\Storage\Wrapper; //ensure the constants are loaded use OC\Files\Cache\CacheEntry; use OC\Files\Storage\Local; +use OC\Files\Storage\Wrapper\Quota; use OCP\Files; +use OCP\ITempManager; +use OCP\Server; /** * Class QuotaTest @@ -28,9 +31,9 @@ class QuotaTest extends \Test\Files\Storage\Storage { protected function setUp(): void { parent::setUp(); - $this->tmpDir = \OC::$server->getTempManager()->getTemporaryFolder(); - $storage = new \OC\Files\Storage\Local(['datadir' => $this->tmpDir]); - $this->instance = new \OC\Files\Storage\Wrapper\Quota(['storage' => $storage, 'quota' => 10000000]); + $this->tmpDir = Server::get(ITempManager::class)->getTemporaryFolder(); + $storage = new Local(['datadir' => $this->tmpDir]); + $this->instance = new Quota(['storage' => $storage, 'quota' => 10000000]); } protected function tearDown(): void { @@ -42,10 +45,10 @@ class QuotaTest extends \Test\Files\Storage\Storage { * @param integer $limit */ protected function getLimitedStorage($limit) { - $storage = new \OC\Files\Storage\Local(['datadir' => $this->tmpDir]); + $storage = new Local(['datadir' => $this->tmpDir]); $storage->mkdir('files'); $storage->getScanner()->scan(''); - return new \OC\Files\Storage\Wrapper\Quota(['storage' => $storage, 'quota' => $limit]); + return new Quota(['storage' => $storage, 'quota' => $limit]); } public function testFilePutContentsNotEnoughSpace(): void { @@ -83,7 +86,7 @@ class QuotaTest extends \Test\Files\Storage\Storage { ->willReturn(-2); $storage->getScanner()->scan(''); - $instance = new \OC\Files\Storage\Wrapper\Quota(['storage' => $storage, 'quota' => 9]); + $instance = new Quota(['storage' => $storage, 'quota' => 9]); $instance->getCache()->put( '', ['size' => 3] ); @@ -138,7 +141,7 @@ class QuotaTest extends \Test\Files\Storage\Storage { ->method('fopen') ->willReturn(false); - $instance = new \OC\Files\Storage\Wrapper\Quota(['storage' => $failStorage, 'quota' => 1000]); + $instance = new Quota(['storage' => $failStorage, 'quota' => 1000]); $this->assertFalse($instance->fopen('failedfopen', 'r')); } @@ -196,7 +199,7 @@ class QuotaTest extends \Test\Files\Storage\Storage { ->with('files') ->willReturn(new CacheEntry(['size' => 50])); - $instance = new \OC\Files\Storage\Wrapper\Quota(['storage' => $storage, 'quota' => 1024, 'root' => 'files']); + $instance = new Quota(['storage' => $storage, 'quota' => 1024, 'root' => 'files']); $this->assertEquals(1024 - 50, $instance->free_space('')); } diff --git a/tests/lib/Files/Storage/Wrapper/WrapperTest.php b/tests/lib/Files/Storage/Wrapper/WrapperTest.php index 4cbae1762fc..d7b7683c58a 100644 --- a/tests/lib/Files/Storage/Wrapper/WrapperTest.php +++ b/tests/lib/Files/Storage/Wrapper/WrapperTest.php @@ -7,7 +7,11 @@ namespace Test\Files\Storage\Wrapper; +use OC\Files\Storage\Local; +use OC\Files\Storage\Wrapper\Wrapper; use OCP\Files; +use OCP\ITempManager; +use OCP\Server; class WrapperTest extends \Test\Files\Storage\Storage { /** @@ -18,9 +22,9 @@ class WrapperTest extends \Test\Files\Storage\Storage { protected function setUp(): void { parent::setUp(); - $this->tmpDir = \OC::$server->getTempManager()->getTemporaryFolder(); - $storage = new \OC\Files\Storage\Local(['datadir' => $this->tmpDir]); - $this->instance = new \OC\Files\Storage\Wrapper\Wrapper(['storage' => $storage]); + $this->tmpDir = Server::get(ITempManager::class)->getTemporaryFolder(); + $storage = new Local(['datadir' => $this->tmpDir]); + $this->instance = new Wrapper(['storage' => $storage]); } protected function tearDown(): void { diff --git a/tests/lib/Files/Stream/DummyEncryptionWrapper.php b/tests/lib/Files/Stream/DummyEncryptionWrapper.php index 211050905bd..6846762cb67 100644 --- a/tests/lib/Files/Stream/DummyEncryptionWrapper.php +++ b/tests/lib/Files/Stream/DummyEncryptionWrapper.php @@ -7,7 +7,9 @@ namespace Test\Files\Stream; -class DummyEncryptionWrapper extends \OC\Files\Stream\Encryption { +use OC\Files\Stream\Encryption; + +class DummyEncryptionWrapper extends Encryption { /** * simulate a non-seekable stream wrapper by always return false * diff --git a/tests/lib/Files/Stream/HashWrapperTest.php b/tests/lib/Files/Stream/HashWrapperTest.php index 1e9bbd8f289..66dee77b607 100644 --- a/tests/lib/Files/Stream/HashWrapperTest.php +++ b/tests/lib/Files/Stream/HashWrapperTest.php @@ -25,7 +25,7 @@ class HashWrapperTest extends TestCase { $data = $tmpData; } - $wrapper = HashWrapper::wrap($data, $algo, function ($result) use ($hash) { + $wrapper = HashWrapper::wrap($data, $algo, function ($result) use ($hash): void { $this->assertEquals($hash, $result); }); stream_get_contents($wrapper); diff --git a/tests/lib/Files/Stream/QuotaTest.php b/tests/lib/Files/Stream/QuotaTest.php index 2df767d6c60..31c0f6c1453 100644 --- a/tests/lib/Files/Stream/QuotaTest.php +++ b/tests/lib/Files/Stream/QuotaTest.php @@ -7,6 +7,8 @@ namespace Test\Files\Stream; +use OC\Files\Stream\Quota; + class QuotaTest extends \Test\TestCase { /** * @param string $mode @@ -15,7 +17,7 @@ class QuotaTest extends \Test\TestCase { */ protected function getStream($mode, $limit) { $source = fopen('php://temp', $mode); - return \OC\Files\Stream\Quota::wrap($source, $limit); + return Quota::wrap($source, $limit); } public function testWriteEnoughSpace(): void { @@ -60,7 +62,7 @@ class QuotaTest extends \Test\TestCase { public function testWriteNotEnoughSpaceExistingStream(): void { $source = fopen('php://temp', 'w+'); fwrite($source, 'foobar'); - $stream = \OC\Files\Stream\Quota::wrap($source, 3); + $stream = Quota::wrap($source, 3); $this->assertEquals(3, fwrite($stream, 'foobar')); rewind($stream); $this->assertEquals('foobarfoo', fread($stream, 100)); @@ -69,7 +71,7 @@ class QuotaTest extends \Test\TestCase { public function testWriteNotEnoughSpaceExistingStreamRewind(): void { $source = fopen('php://temp', 'w+'); fwrite($source, 'foobar'); - $stream = \OC\Files\Stream\Quota::wrap($source, 3); + $stream = Quota::wrap($source, 3); rewind($stream); $this->assertEquals(6, fwrite($stream, 'qwerty')); rewind($stream); diff --git a/tests/lib/Files/Type/DetectionTest.php b/tests/lib/Files/Type/DetectionTest.php index 1005f12786a..81fb7ad4bcb 100644 --- a/tests/lib/Files/Type/DetectionTest.php +++ b/tests/lib/Files/Type/DetectionTest.php @@ -9,6 +9,7 @@ namespace Test\Files\Type; use OC\Files\Type\Detection; use OCP\IURLGenerator; +use OCP\Server; use Psr\Log\LoggerInterface; class DetectionTest extends \Test\TestCase { @@ -18,8 +19,8 @@ class DetectionTest extends \Test\TestCase { protected function setUp(): void { parent::setUp(); $this->detection = new Detection( - \OC::$server->getURLGenerator(), - \OC::$server->get(LoggerInterface::class), + Server::get(IURLGenerator::class), + Server::get(LoggerInterface::class), \OC::$SERVERROOT . '/config/', \OC::$SERVERROOT . '/resources/config/' ); diff --git a/tests/lib/Files/Type/LoaderTest.php b/tests/lib/Files/Type/LoaderTest.php index 6eaf6ac2013..f1018093c45 100644 --- a/tests/lib/Files/Type/LoaderTest.php +++ b/tests/lib/Files/Type/LoaderTest.php @@ -9,6 +9,7 @@ namespace Test\Files\Type; use OC\Files\Type\Loader; use OCP\IDBConnection; +use OCP\Server; use Test\TestCase; class LoaderTest extends TestCase { @@ -16,7 +17,7 @@ class LoaderTest extends TestCase { protected Loader $loader; protected function setUp(): void { - $this->db = \OC::$server->get(IDBConnection::class); + $this->db = Server::get(IDBConnection::class); $this->loader = new Loader($this->db); } diff --git a/tests/lib/Files/Utils/ScannerTest.php b/tests/lib/Files/Utils/ScannerTest.php index 047da5851b7..ebad4680ff6 100644 --- a/tests/lib/Files/Utils/ScannerTest.php +++ b/tests/lib/Files/Utils/ScannerTest.php @@ -10,13 +10,18 @@ namespace Test\Files\Utils; use OC\Files\Filesystem; use OC\Files\Mount\MountPoint; use OC\Files\Storage\Temporary; +use OC\Files\Utils\Scanner; use OCP\EventDispatcher\IEventDispatcher; use OCP\Files\Config\IMountProvider; +use OCP\Files\Config\IMountProviderCollection; use OCP\Files\Storage\IStorageFactory; +use OCP\IDBConnection; use OCP\IUser; +use OCP\IUserManager; +use OCP\Server; use Psr\Log\LoggerInterface; -class TestScanner extends \OC\Files\Utils\Scanner { +class TestScanner extends Scanner { /** * @var \OC\Files\Mount\MountPoint[] $mounts */ @@ -51,13 +56,13 @@ class ScannerTest extends \Test\TestCase { parent::setUp(); $this->userBackend = new \Test\Util\User\Dummy(); - \OC::$server->getUserManager()->registerBackend($this->userBackend); + Server::get(IUserManager::class)->registerBackend($this->userBackend); $this->loginAsUser(); } protected function tearDown(): void { $this->logout(); - \OC::$server->getUserManager()->removeBackend($this->userBackend); + Server::get(IUserManager::class)->removeBackend($this->userBackend); parent::tearDown(); } @@ -71,7 +76,7 @@ class ScannerTest extends \Test\TestCase { $storage->file_put_contents('foo.txt', 'qwerty'); $storage->file_put_contents('folder/bar.txt', 'qwerty'); - $scanner = new TestScanner('', \OC::$server->getDatabaseConnection(), $this->createMock(IEventDispatcher::class), \OC::$server->get(LoggerInterface::class)); + $scanner = new TestScanner('', Server::get(IDBConnection::class), $this->createMock(IEventDispatcher::class), Server::get(LoggerInterface::class)); $scanner->addMount($mount); $scanner->scan(''); @@ -93,7 +98,7 @@ class ScannerTest extends \Test\TestCase { $storage->file_put_contents('foo.txt', 'qwerty'); $storage->file_put_contents('folder/bar.txt', 'qwerty'); - $scanner = new TestScanner('', \OC::$server->getDatabaseConnection(), $this->createMock(IEventDispatcher::class), \OC::$server->get(LoggerInterface::class)); + $scanner = new TestScanner('', Server::get(IDBConnection::class), $this->createMock(IEventDispatcher::class), Server::get(LoggerInterface::class)); $scanner->addMount($mount); $scanner->scan(''); @@ -124,14 +129,14 @@ class ScannerTest extends \Test\TestCase { } }); - \OCP\Server::get(\OCP\Files\Config\IMountProviderCollection::class)->registerProvider($mountProvider); + Server::get(IMountProviderCollection::class)->registerProvider($mountProvider); $cache = $storage->getCache(); $storage->mkdir('folder'); $storage->file_put_contents('foo.txt', 'qwerty'); $storage->file_put_contents('folder/bar.txt', 'qwerty'); - $scanner = new \OC\Files\Utils\Scanner($uid, \OC::$server->getDatabaseConnection(), \OC::$server->query(IEventDispatcher::class), \OC::$server->get(LoggerInterface::class)); + $scanner = new Scanner($uid, Server::get(IDBConnection::class), Server::get(IEventDispatcher::class), Server::get(LoggerInterface::class)); $this->assertFalse($cache->inCache('folder/bar.txt')); $scanner->scan('/' . $uid . '/files/foo'); @@ -160,7 +165,7 @@ class ScannerTest extends \Test\TestCase { $this->expectException(\InvalidArgumentException::class); $this->expectExceptionMessage('Invalid path to scan'); - $scanner = new TestScanner('', \OC::$server->getDatabaseConnection(), $this->createMock(IEventDispatcher::class), \OC::$server->get(LoggerInterface::class)); + $scanner = new TestScanner('', Server::get(IDBConnection::class), $this->createMock(IEventDispatcher::class), Server::get(LoggerInterface::class)); $scanner->scan($invalidPath); } @@ -174,7 +179,7 @@ class ScannerTest extends \Test\TestCase { $storage->file_put_contents('folder/bar.txt', 'qwerty'); $storage->touch('folder/bar.txt', time() - 200); - $scanner = new TestScanner('', \OC::$server->getDatabaseConnection(), $this->createMock(IEventDispatcher::class), \OC::$server->get(LoggerInterface::class)); + $scanner = new TestScanner('', Server::get(IDBConnection::class), $this->createMock(IEventDispatcher::class), Server::get(LoggerInterface::class)); $scanner->addMount($mount); $scanner->scan(''); @@ -200,7 +205,7 @@ class ScannerTest extends \Test\TestCase { $storage->file_put_contents('folder/bar.txt', 'qwerty'); $storage->file_put_contents('folder/subfolder/foobar.txt', 'qwerty'); - $scanner = new TestScanner('', \OC::$server->getDatabaseConnection(), $this->createMock(IEventDispatcher::class), \OC::$server->get(LoggerInterface::class)); + $scanner = new TestScanner('', Server::get(IDBConnection::class), $this->createMock(IEventDispatcher::class), Server::get(LoggerInterface::class)); $scanner->addMount($mount); $scanner->scan('', $recusive = false); diff --git a/tests/lib/Files/ViewTest.php b/tests/lib/Files/ViewTest.php index d611df372e6..36e448ea6e2 100644 --- a/tests/lib/Files/ViewTest.php +++ b/tests/lib/Files/ViewTest.php @@ -7,6 +7,7 @@ namespace Test\Files; +use OC\Files\Cache\Scanner; use OC\Files\Cache\Watcher; use OC\Files\Filesystem; use OC\Files\Mount\MountPoint; @@ -20,13 +21,19 @@ use OCA\Files_Trashbin\Trash\ITrashManager; use OCP\Cache\CappedMemoryCache; use OCP\Constants; use OCP\Files\Config\IMountProvider; +use OCP\Files\Config\IMountProviderCollection; use OCP\Files\FileInfo; use OCP\Files\ForbiddenException; use OCP\Files\GenericFileException; +use OCP\Files\InvalidPathException; use OCP\Files\Mount\IMountManager; +use OCP\Files\NotFoundException; use OCP\Files\Storage\IStorage; use OCP\Files\Storage\IStorageFactory; +use OCP\IConfig; use OCP\IDBConnection; +use OCP\IGroupManager; +use OCP\ITempManager; use OCP\IUserManager; use OCP\Lock\ILockingProvider; use OCP\Lock\LockedException; @@ -117,8 +124,8 @@ class ViewTest extends \Test\TestCase { Server::get(IUserManager::class)->registerBackend(new \Test\Util\User\Dummy()); //login - $userManager = \OC::$server->getUserManager(); - $groupManager = \OC::$server->getGroupManager(); + $userManager = Server::get(IUserManager::class); + $groupManager = Server::get(IGroupManager::class); $this->user = 'test'; $this->userObject = $userManager->createUser('test', 'test'); @@ -128,7 +135,7 @@ class ViewTest extends \Test\TestCase { self::loginAsUser($this->user); /** @var IMountManager $manager */ - $manager = \OC::$server->get(IMountManager::class); + $manager = Server::get(IMountManager::class); $manager->removeMount('/test'); $this->tempStorage = null; @@ -149,13 +156,13 @@ class ViewTest extends \Test\TestCase { self::logout(); /** @var SetupManager $setupManager */ - $setupManager = \OC::$server->get(SetupManager::class); + $setupManager = Server::get(SetupManager::class); $setupManager->setupRoot(); $this->userObject->delete(); $this->groupObject->delete(); - $mountProviderCollection = \OCP\Server::get(\OCP\Files\Config\IMountProviderCollection::class); + $mountProviderCollection = Server::get(IMountProviderCollection::class); self::invokePrivate($mountProviderCollection, 'providers', [[]]); parent::tearDown(); @@ -275,7 +282,7 @@ class ViewTest extends \Test\TestCase { public function testGetPathNotExisting(): void { - $this->expectException(\OCP\Files\NotFoundException::class); + $this->expectException(NotFoundException::class); $storage1 = $this->getTestStorage(); Filesystem::mount($storage1, [], '/'); @@ -315,9 +322,9 @@ class ViewTest extends \Test\TestCase { */ public function testRemoveSharePermissionWhenSharingDisabledForUser($excludeGroups, $excludeGroupsList, $expectedShareable): void { // Reset sharing disabled for users cache - self::invokePrivate(\OC::$server->get(ShareDisableChecker::class), 'sharingDisabledForUsersCache', [new CappedMemoryCache()]); + self::invokePrivate(Server::get(ShareDisableChecker::class), 'sharingDisabledForUsersCache', [new CappedMemoryCache()]); - $config = \OC::$server->getConfig(); + $config = Server::get(IConfig::class); $oldExcludeGroupsFlag = $config->getAppValue('core', 'shareapi_exclude_groups', 'no'); $oldExcludeGroupsList = $config->getAppValue('core', 'shareapi_exclude_groups_list', ''); $config->setAppValue('core', 'shareapi_exclude_groups', $excludeGroups); @@ -340,7 +347,7 @@ class ViewTest extends \Test\TestCase { $config->setAppValue('core', 'shareapi_exclude_groups_list', $oldExcludeGroupsList); // Reset sharing disabled for users cache - self::invokePrivate(\OC::$server->get(ShareDisableChecker::class), 'sharingDisabledForUsersCache', [new CappedMemoryCache()]); + self::invokePrivate(Server::get(ShareDisableChecker::class), 'sharingDisabledForUsersCache', [new CappedMemoryCache()]); } public function testCacheIncompleteFolder(): void { @@ -845,7 +852,7 @@ class ViewTest extends \Test\TestCase { * 1024 is the max path length in mac */ $folderName = 'abcdefghijklmnopqrstuvwxyz012345678901234567890123456789'; - $tmpdirLength = strlen(\OC::$server->getTempManager()->getTemporaryFolder()); + $tmpdirLength = strlen(Server::get(ITempManager::class)->getTemporaryFolder()); if (\OC_Util::runningOnMac()) { $depth = ((1024 - $tmpdirLength) / 57); } else { @@ -892,7 +899,7 @@ class ViewTest extends \Test\TestCase { $info = $view->getFileInfo('/test/test'); $view->touch('/test/test', $past); - $scanner->scanFile('test', \OC\Files\Cache\Scanner::REUSE_ETAG); + $scanner->scanFile('test', Scanner::REUSE_ETAG); $info2 = $view->getFileInfo('/test/test'); $this->assertSame($info['etag'], $info2['etag']); @@ -1082,7 +1089,7 @@ class ViewTest extends \Test\TestCase { * @dataProvider tooLongPathDataProvider */ public function testTooLongPath($operation, $param0 = null): void { - $this->expectException(\OCP\Files\InvalidPathException::class); + $this->expectException(InvalidPathException::class); $longPath = ''; @@ -1332,7 +1339,7 @@ class ViewTest extends \Test\TestCase { * @param string $pathPrefix */ public function testReadFromWriteLockedPath($rootPath, $pathPrefix): void { - $this->expectException(\OCP\Lock\LockedException::class); + $this->expectException(LockedException::class); $rootPath = str_replace('{folder}', 'files', $rootPath); $pathPrefix = str_replace('{folder}', 'files', $pathPrefix); @@ -1373,7 +1380,7 @@ class ViewTest extends \Test\TestCase { * @param string $pathPrefix */ public function testWriteToReadLockedFile($rootPath, $pathPrefix): void { - $this->expectException(\OCP\Lock\LockedException::class); + $this->expectException(LockedException::class); $rootPath = str_replace('{folder}', 'files', $rootPath); $pathPrefix = str_replace('{folder}', 'files', $pathPrefix); @@ -1408,7 +1415,7 @@ class ViewTest extends \Test\TestCase { * Test that locks are on mount point paths instead of mount root */ public function testLockLocalMountPointPathInsteadOfStorageRoot(): void { - $lockingProvider = \OC::$server->get(ILockingProvider::class); + $lockingProvider = Server::get(ILockingProvider::class); $view = new View('/testuser/files/'); $storage = new Temporary([]); Filesystem::mount($storage, [], '/'); @@ -1438,7 +1445,7 @@ class ViewTest extends \Test\TestCase { * Test that locks are on mount point paths and also mount root when requested */ public function testLockStorageRootButNotLocalMountPoint(): void { - $lockingProvider = \OC::$server->get(ILockingProvider::class); + $lockingProvider = Server::get(ILockingProvider::class); $view = new View('/testuser/files/'); $storage = new Temporary([]); Filesystem::mount($storage, [], '/'); @@ -1468,7 +1475,7 @@ class ViewTest extends \Test\TestCase { * Test that locks are on mount point paths and also mount root when requested */ public function testLockMountPointPathFailReleasesBoth(): void { - $lockingProvider = \OC::$server->get(ILockingProvider::class); + $lockingProvider = Server::get(ILockingProvider::class); $view = new View('/testuser/files/'); $storage = new Temporary([]); Filesystem::mount($storage, [], '/'); @@ -1611,7 +1618,7 @@ class ViewTest extends \Test\TestCase { ->getMock(); $storage->method('getId')->willReturn('non-null-id'); $storage->method('getStorageCache')->willReturnCallback(function () use ($storage) { - return new \OC\Files\Cache\Storage($storage, true, \OC::$server->get(IDBConnection::class)); + return new \OC\Files\Cache\Storage($storage, true, Server::get(IDBConnection::class)); }); $mounts[] = $this->getMockBuilder(TestMoveableMountPoint::class) @@ -1626,7 +1633,7 @@ class ViewTest extends \Test\TestCase { ->method('getMountsForUser') ->willReturn($mounts); - $mountProviderCollection = \OCP\Server::get(\OCP\Files\Config\IMountProviderCollection::class); + $mountProviderCollection = Server::get(IMountProviderCollection::class); $mountProviderCollection->registerProvider($mountProvider); return $mounts; @@ -1723,16 +1730,16 @@ class ViewTest extends \Test\TestCase { $view->mkdir('shareddir notshared'); $fileId = $view->getFileInfo('shareddir')->getId(); - $userObject = \OC::$server->getUserManager()->createUser('test2', 'IHateNonMockableStaticClasses'); + $userObject = Server::get(IUserManager::class)->createUser('test2', 'IHateNonMockableStaticClasses'); $userFolder = \OC::$server->getUserFolder($this->user); $shareDir = $userFolder->get('shareddir'); - $shareManager = \OC::$server->get(IShareManager::class); + $shareManager = Server::get(IShareManager::class); $share = $shareManager->newShare(); $share->setSharedWith('test2') ->setSharedBy($this->user) ->setShareType(IShare::TYPE_USER) - ->setPermissions(\OCP\Constants::PERMISSION_READ) + ->setPermissions(Constants::PERMISSION_READ) ->setNode($shareDir); $shareManager->createShare($share); @@ -2117,7 +2124,7 @@ class ViewTest extends \Test\TestCase { $storage->expects($this->once()) ->method($operation) ->willReturnCallback( - function () { + function (): void { throw new \Exception('Simulated exception'); } ); @@ -2231,13 +2238,13 @@ class ViewTest extends \Test\TestCase { $storage->expects($this->any()) ->method('getMetaData') - ->will($this->returnValue([ + ->willReturn([ 'mtime' => 1885434487, 'etag' => '', 'mimetype' => 'text/plain', 'permissions' => Constants::PERMISSION_ALL, 'size' => 3 - ])); + ]); $storage->expects($this->any()) ->method('filemtime') ->willReturn(123456789); @@ -2311,7 +2318,7 @@ class ViewTest extends \Test\TestCase { $storage->expects($this->once()) ->method('copy') ->willReturnCallback( - function () { + function (): void { throw new \Exception(); } ); @@ -2426,13 +2433,13 @@ class ViewTest extends \Test\TestCase { $storage2->expects($this->any()) ->method('getMetaData') - ->will($this->returnValue([ + ->willReturn([ 'mtime' => 1885434487, 'etag' => '', 'mimetype' => 'text/plain', 'permissions' => Constants::PERMISSION_ALL, 'size' => 3 - ])); + ]); $storage2->expects($this->any()) ->method('filemtime') ->willReturn(123456789); @@ -2566,14 +2573,14 @@ class ViewTest extends \Test\TestCase { $eventHandler->expects($this->any()) ->method('preCallback') ->willReturnCallback( - function () use ($view, $path, $onMountPoint, &$lockTypePre) { + function () use ($view, $path, $onMountPoint, &$lockTypePre): void { $lockTypePre = $this->getFileLockType($view, $path, $onMountPoint); } ); $eventHandler->expects($this->any()) ->method('postCallback') ->willReturnCallback( - function () use ($view, $path, $onMountPoint, &$lockTypePost) { + function () use ($view, $path, $onMountPoint, &$lockTypePost): void { $lockTypePost = $this->getFileLockType($view, $path, $onMountPoint); } ); @@ -2794,7 +2801,7 @@ class ViewTest extends \Test\TestCase { $calls = ['/new/folder', '/new/folder/structure']; $view->expects($this->exactly(2)) ->method('mkdir') - ->willReturnCallback(function ($dir) use (&$calls) { + ->willReturnCallback(function ($dir) use (&$calls): void { $expected = array_shift($calls); $this->assertEquals($expected, $dir); }); diff --git a/tests/lib/Group/DatabaseTest.php b/tests/lib/Group/DatabaseTest.php index 593fbe60bf9..d748890b4de 100644 --- a/tests/lib/Group/DatabaseTest.php +++ b/tests/lib/Group/DatabaseTest.php @@ -7,6 +7,8 @@ namespace Test\Group; +use OC\Group\Database; + /** * Class Database * @@ -27,7 +29,7 @@ class DatabaseTest extends Backend { protected function setUp(): void { parent::setUp(); - $this->backend = new \OC\Group\Database(); + $this->backend = new Database(); } protected function tearDown(): void { @@ -42,7 +44,7 @@ class DatabaseTest extends Backend { $this->backend->createGroup($group); - $backend = new \OC\Group\Database(); + $backend = new Database(); $this->assertNull($backend->createGroup($group)); } diff --git a/tests/lib/Group/GroupTest.php b/tests/lib/Group/GroupTest.php index 0730f827c64..baae814675c 100644 --- a/tests/lib/Group/GroupTest.php +++ b/tests/lib/Group/GroupTest.php @@ -8,6 +8,7 @@ namespace Test\Group; +use OC\Group\Group; use OC\User\User; use OCP\EventDispatcher\IEventDispatcher; use OCP\IUser; @@ -65,7 +66,7 @@ class GroupTest extends \Test\TestCase { ->disableOriginalConstructor() ->getMock(); $userManager = $this->getUserManager(); - $group = new \OC\Group\Group('group1', [$backend], $this->dispatcher, $userManager); + $group = new Group('group1', [$backend], $this->dispatcher, $userManager); $backend->expects($this->once()) ->method('usersInGroup') @@ -89,7 +90,7 @@ class GroupTest extends \Test\TestCase { ->disableOriginalConstructor() ->getMock(); $userManager = $this->getUserManager(); - $group = new \OC\Group\Group('group1', [$backend1, $backend2], $this->dispatcher, $userManager); + $group = new Group('group1', [$backend1, $backend2], $this->dispatcher, $userManager); $backend1->expects($this->once()) ->method('usersInGroup') @@ -120,7 +121,7 @@ class GroupTest extends \Test\TestCase { $userBackend = $this->getMockBuilder('\OC\User\Backend') ->disableOriginalConstructor() ->getMock(); - $group = new \OC\Group\Group('group1', [$backend], $this->dispatcher, $userManager); + $group = new Group('group1', [$backend], $this->dispatcher, $userManager); $backend->expects($this->once()) ->method('inGroup') @@ -141,7 +142,7 @@ class GroupTest extends \Test\TestCase { $userBackend = $this->getMockBuilder(\OC\User\Backend::class) ->disableOriginalConstructor() ->getMock(); - $group = new \OC\Group\Group('group1', [$backend1, $backend2], $this->dispatcher, $userManager); + $group = new Group('group1', [$backend1, $backend2], $this->dispatcher, $userManager); $backend1->expects($this->once()) ->method('inGroup') @@ -164,7 +165,7 @@ class GroupTest extends \Test\TestCase { $userBackend = $this->getMockBuilder('\OC\User\Backend') ->disableOriginalConstructor() ->getMock(); - $group = new \OC\Group\Group('group1', [$backend], $this->dispatcher, $userManager); + $group = new Group('group1', [$backend], $this->dispatcher, $userManager); $backend->expects($this->once()) ->method('inGroup') @@ -189,7 +190,7 @@ class GroupTest extends \Test\TestCase { $userBackend = $this->getMockBuilder('\OC\User\Backend') ->disableOriginalConstructor() ->getMock(); - $group = new \OC\Group\Group('group1', [$backend], $this->dispatcher, $userManager); + $group = new Group('group1', [$backend], $this->dispatcher, $userManager); $backend->expects($this->once()) ->method('inGroup') @@ -213,7 +214,7 @@ class GroupTest extends \Test\TestCase { $userBackend = $this->getMockBuilder('\OC\User\Backend') ->disableOriginalConstructor() ->getMock(); - $group = new \OC\Group\Group('group1', [$backend], $this->dispatcher, $userManager); + $group = new Group('group1', [$backend], $this->dispatcher, $userManager); $backend->expects($this->once()) ->method('inGroup') @@ -238,7 +239,7 @@ class GroupTest extends \Test\TestCase { $userBackend = $this->getMockBuilder(\OC\User\Backend::class) ->disableOriginalConstructor() ->getMock(); - $group = new \OC\Group\Group('group1', [$backend], $this->dispatcher, $userManager); + $group = new Group('group1', [$backend], $this->dispatcher, $userManager); $backend->expects($this->once()) ->method('inGroup') @@ -265,7 +266,7 @@ class GroupTest extends \Test\TestCase { $userBackend = $this->getMockBuilder('\OC\User\Backend') ->disableOriginalConstructor() ->getMock(); - $group = new \OC\Group\Group('group1', [$backend1, $backend2], $this->dispatcher, $userManager); + $group = new Group('group1', [$backend1, $backend2], $this->dispatcher, $userManager); $backend1->expects($this->once()) ->method('inGroup') @@ -299,12 +300,12 @@ class GroupTest extends \Test\TestCase { ->disableOriginalConstructor() ->getMock(); $userManager = $this->getUserManager(); - $group = new \OC\Group\Group('group1', [$backend], $this->dispatcher, $userManager); + $group = new Group('group1', [$backend], $this->dispatcher, $userManager); $backend->expects($this->once()) ->method('searchInGroup') ->with('group1', '2') - ->willReturn(['user2' => new \OC\User\User('user2', null, $this->dispatcher)]); + ->willReturn(['user2' => new User('user2', null, $this->dispatcher)]); $users = $group->searchUsers('2'); @@ -321,16 +322,16 @@ class GroupTest extends \Test\TestCase { ->disableOriginalConstructor() ->getMock(); $userManager = $this->getUserManager(); - $group = new \OC\Group\Group('group1', [$backend1, $backend2], $this->dispatcher, $userManager); + $group = new Group('group1', [$backend1, $backend2], $this->dispatcher, $userManager); $backend1->expects($this->once()) ->method('searchInGroup') ->with('group1', '2') - ->willReturn(['user2' => new \OC\User\User('user2', null, $this->dispatcher)]); + ->willReturn(['user2' => new User('user2', null, $this->dispatcher)]); $backend2->expects($this->once()) ->method('searchInGroup') ->with('group1', '2') - ->willReturn(['user2' => new \OC\User\User('user2', null, $this->dispatcher)]); + ->willReturn(['user2' => new User('user2', null, $this->dispatcher)]); $users = $group->searchUsers('2'); @@ -344,12 +345,12 @@ class GroupTest extends \Test\TestCase { ->disableOriginalConstructor() ->getMock(); $userManager = $this->getUserManager(); - $group = new \OC\Group\Group('group1', [$backend], $this->dispatcher, $userManager); + $group = new Group('group1', [$backend], $this->dispatcher, $userManager); $backend->expects($this->once()) ->method('searchInGroup') ->with('group1', 'user', 1, 1) - ->willReturn(['user2' => new \OC\User\User('user2', null, $this->dispatcher)]); + ->willReturn(['user2' => new User('user2', null, $this->dispatcher)]); $users = $group->searchUsers('user', 1, 1); @@ -366,16 +367,16 @@ class GroupTest extends \Test\TestCase { ->disableOriginalConstructor() ->getMock(); $userManager = $this->getUserManager(); - $group = new \OC\Group\Group('group1', [$backend1, $backend2], $this->dispatcher, $userManager); + $group = new Group('group1', [$backend1, $backend2], $this->dispatcher, $userManager); $backend1->expects($this->once()) ->method('searchInGroup') ->with('group1', 'user', 2, 1) - ->willReturn(['user2' => new \OC\User\User('user2', null, $this->dispatcher)]); + ->willReturn(['user2' => new User('user2', null, $this->dispatcher)]); $backend2->expects($this->once()) ->method('searchInGroup') ->with('group1', 'user', 2, 1) - ->willReturn(['user1' => new \OC\User\User('user1', null, $this->dispatcher)]); + ->willReturn(['user1' => new User('user1', null, $this->dispatcher)]); $users = $group->searchUsers('user', 2, 1); @@ -391,7 +392,7 @@ class GroupTest extends \Test\TestCase { ->disableOriginalConstructor() ->getMock(); $userManager = $this->getUserManager(); - $group = new \OC\Group\Group('group1', [$backend1], $this->dispatcher, $userManager); + $group = new Group('group1', [$backend1], $this->dispatcher, $userManager); $backend1->expects($this->once()) ->method('countUsersInGroup') @@ -415,7 +416,7 @@ class GroupTest extends \Test\TestCase { ->disableOriginalConstructor() ->getMock(); $userManager = $this->getUserManager(); - $group = new \OC\Group\Group('group1', [$backend1, $backend2], $this->dispatcher, $userManager); + $group = new Group('group1', [$backend1, $backend2], $this->dispatcher, $userManager); $backend1->expects($this->once()) ->method('countUsersInGroup') @@ -443,7 +444,7 @@ class GroupTest extends \Test\TestCase { ->disableOriginalConstructor() ->getMock(); $userManager = $this->getUserManager(); - $group = new \OC\Group\Group('group1', [$backend1], $this->dispatcher, $userManager); + $group = new Group('group1', [$backend1], $this->dispatcher, $userManager); $backend1->expects($this->never()) ->method('countUsersInGroup'); @@ -461,7 +462,7 @@ class GroupTest extends \Test\TestCase { ->disableOriginalConstructor() ->getMock(); $userManager = $this->getUserManager(); - $group = new \OC\Group\Group('group1', [$backend], $this->dispatcher, $userManager); + $group = new Group('group1', [$backend], $this->dispatcher, $userManager); $backend->expects($this->once()) ->method('deleteGroup') diff --git a/tests/lib/Group/MetaDataTest.php b/tests/lib/Group/MetaDataTest.php index 70f2022ae78..1b58432fd88 100644 --- a/tests/lib/Group/MetaDataTest.php +++ b/tests/lib/Group/MetaDataTest.php @@ -7,12 +7,13 @@ namespace Test\Group; +use OC\Group\MetaData; use OCP\IUserSession; class MetaDataTest extends \Test\TestCase { private \OC\Group\Manager $groupManager; private IUserSession $userSession; - private \OC\Group\MetaData $groupMetadata; + private MetaData $groupMetadata; private bool $isAdmin = true; private bool $isDelegatedAdmin = true; @@ -22,7 +23,7 @@ class MetaDataTest extends \Test\TestCase { ->disableOriginalConstructor() ->getMock(); $this->userSession = $this->createMock(IUserSession::class); - $this->groupMetadata = new \OC\Group\MetaData( + $this->groupMetadata = new MetaData( 'foo', $this->isAdmin, $this->isDelegatedAdmin, @@ -37,23 +38,14 @@ class MetaDataTest extends \Test\TestCase { ->getMock(); $group->expects($this->exactly(6)) - ->method('getGID') - ->will($this->onConsecutiveCalls( - 'admin', 'admin', - 'g2', 'g2', - 'g3', 'g3')); + ->method('getGID')->willReturnOnConsecutiveCalls('admin', 'admin', 'g2', 'g2', 'g3', 'g3'); $group->expects($this->exactly(3)) - ->method('getDisplayName') - ->will($this->onConsecutiveCalls( - 'admin', - 'g2', - 'g3')); + ->method('getDisplayName')->willReturnOnConsecutiveCalls('admin', 'g2', 'g3'); $group->expects($this->exactly($countCallCount)) ->method('count') - ->with('') - ->will($this->onConsecutiveCalls(2, 3, 5)); + ->with('')->willReturnOnConsecutiveCalls(2, 3, 5); return $group; } diff --git a/tests/lib/HelperStorageTest.php b/tests/lib/HelperStorageTest.php index 628e77e935a..b3474a25b9b 100644 --- a/tests/lib/HelperStorageTest.php +++ b/tests/lib/HelperStorageTest.php @@ -7,9 +7,12 @@ namespace Test; +use OC\Files\Filesystem; use OC\Files\Storage\Temporary; +use OC\Files\Storage\Wrapper\Quota; use OCP\Files\Mount\IMountManager; use OCP\IConfig; +use OCP\Server; use Test\Traits\UserTrait; /** @@ -35,12 +38,12 @@ class HelperStorageTest extends \Test\TestCase { $this->createUser($this->user, $this->user); $this->savedQuotaIncludeExternalStorage = $this->getIncludeExternalStorage(); - \OC\Files\Filesystem::tearDown(); + Filesystem::tearDown(); \OC_User::setUserId($this->user); - \OC\Files\Filesystem::init($this->user, '/' . $this->user . '/files'); + Filesystem::init($this->user, '/' . $this->user . '/files'); /** @var IMountManager $manager */ - $manager = \OC::$server->get(IMountManager::class); + $manager = Server::get(IMountManager::class); $manager->removeMount('/' . $this->user); $this->storageMock = null; @@ -54,10 +57,10 @@ class HelperStorageTest extends \Test\TestCase { $this->storageMock->getCache()->clear(); $this->storageMock = null; } - \OC\Files\Filesystem::tearDown(); + Filesystem::tearDown(); \OC_User::setUserId(''); - \OC::$server->getConfig()->deleteAllUserValues($this->user); + Server::get(IConfig::class)->deleteAllUserValues($this->user); parent::tearDown(); } @@ -86,7 +89,7 @@ class HelperStorageTest extends \Test\TestCase { */ public function testGetStorageInfo(): void { $homeStorage = $this->getStorageMock(12); - \OC\Files\Filesystem::mount($homeStorage, [], '/' . $this->user . '/files'); + Filesystem::mount($homeStorage, [], '/' . $this->user . '/files'); $homeStorage->file_put_contents('test.txt', '01234'); $storageInfo = \OC_Helper::getStorageInfo(''); @@ -114,16 +117,16 @@ class HelperStorageTest extends \Test\TestCase { */ public function testGetStorageInfoExcludingExtStorage(): void { $homeStorage = $this->getStorageMock(12); - \OC\Files\Filesystem::mount($homeStorage, [], '/' . $this->user . '/files'); + Filesystem::mount($homeStorage, [], '/' . $this->user . '/files'); $homeStorage->file_put_contents('test.txt', '01234'); - $extStorage = new \OC\Files\Storage\Temporary([]); + $extStorage = new Temporary([]); $extStorage->file_put_contents('extfile.txt', 'abcdefghijklmnopq'); $extStorage->getScanner()->scan(''); // update root size $this->setIncludeExternalStorage(false); - \OC\Files\Filesystem::mount($extStorage, [], '/' . $this->user . '/files/ext'); + Filesystem::mount($extStorage, [], '/' . $this->user . '/files/ext'); $storageInfo = \OC_Helper::getStorageInfo(''); $this->assertEquals(12, $storageInfo['free']); @@ -135,19 +138,19 @@ class HelperStorageTest extends \Test\TestCase { * Test getting the storage info, including extra mount points */ public function testGetStorageInfoIncludingExtStorage(): void { - $homeStorage = new \OC\Files\Storage\Temporary([]); - \OC\Files\Filesystem::mount($homeStorage, [], '/' . $this->user . '/files'); + $homeStorage = new Temporary([]); + Filesystem::mount($homeStorage, [], '/' . $this->user . '/files'); $homeStorage->file_put_contents('test.txt', '01234'); - $extStorage = new \OC\Files\Storage\Temporary([]); + $extStorage = new Temporary([]); $extStorage->file_put_contents('extfile.txt', 'abcdefghijklmnopq'); $extStorage->getScanner()->scan(''); // update root size - \OC\Files\Filesystem::mount($extStorage, [], '/' . $this->user . '/files/ext'); + Filesystem::mount($extStorage, [], '/' . $this->user . '/files/ext'); $this->setIncludeExternalStorage(true); - $config = \OC::$server->get(IConfig::class); + $config = Server::get(IConfig::class); $config->setUserValue($this->user, 'files', 'quota', '25'); $storageInfo = \OC_Helper::getStorageInfo(''); @@ -165,16 +168,16 @@ class HelperStorageTest extends \Test\TestCase { */ public function testGetStorageInfoIncludingExtStorageWithNoUserQuota(): void { $homeStorage = $this->getStorageMock(12); - \OC\Files\Filesystem::mount($homeStorage, [], '/' . $this->user . '/files'); + Filesystem::mount($homeStorage, [], '/' . $this->user . '/files'); $homeStorage->file_put_contents('test.txt', '01234'); - $extStorage = new \OC\Files\Storage\Temporary([]); + $extStorage = new Temporary([]); $extStorage->file_put_contents('extfile.txt', 'abcdefghijklmnopq'); $extStorage->getScanner()->scan(''); // update root size - \OC\Files\Filesystem::mount($extStorage, [], '/' . $this->user . '/files/ext'); + Filesystem::mount($extStorage, [], '/' . $this->user . '/files/ext'); - $config = \OC::$server->getConfig(); + $config = Server::get(IConfig::class); $this->setIncludeExternalStorage(true); $storageInfo = \OC_Helper::getStorageInfo(''); @@ -190,13 +193,13 @@ class HelperStorageTest extends \Test\TestCase { public function testGetStorageInfoWithQuota(): void { $homeStorage = $this->getStorageMock(12); $homeStorage->file_put_contents('test.txt', '01234'); - $homeStorage = new \OC\Files\Storage\Wrapper\Quota( + $homeStorage = new Quota( [ 'storage' => $homeStorage, 'quota' => 7 ] ); - \OC\Files\Filesystem::mount($homeStorage, [], '/' . $this->user . '/files'); + Filesystem::mount($homeStorage, [], '/' . $this->user . '/files'); $storageInfo = \OC_Helper::getStorageInfo(''); $this->assertEquals(2, $storageInfo['free']); @@ -210,13 +213,13 @@ class HelperStorageTest extends \Test\TestCase { public function testGetStorageInfoWhenSizeExceedsQuota(): void { $homeStorage = $this->getStorageMock(12); $homeStorage->file_put_contents('test.txt', '0123456789'); - $homeStorage = new \OC\Files\Storage\Wrapper\Quota( + $homeStorage = new Quota( [ 'storage' => $homeStorage, 'quota' => 7 ] ); - \OC\Files\Filesystem::mount($homeStorage, [], '/' . $this->user . '/files'); + Filesystem::mount($homeStorage, [], '/' . $this->user . '/files'); $storageInfo = \OC_Helper::getStorageInfo(''); $this->assertEquals(0, $storageInfo['free']); @@ -232,13 +235,13 @@ class HelperStorageTest extends \Test\TestCase { public function testGetStorageInfoWhenFreeSpaceLessThanQuota(): void { $homeStorage = $this->getStorageMock(12); $homeStorage->file_put_contents('test.txt', '01234'); - $homeStorage = new \OC\Files\Storage\Wrapper\Quota( + $homeStorage = new Quota( [ 'storage' => $homeStorage, 'quota' => 18 ] ); - \OC\Files\Filesystem::mount($homeStorage, [], '/' . $this->user . '/files'); + Filesystem::mount($homeStorage, [], '/' . $this->user . '/files'); $storageInfo = \OC_Helper::getStorageInfo(''); $this->assertEquals(12, $storageInfo['free']); diff --git a/tests/lib/HookHelper.php b/tests/lib/HookHelper.php index 8b7d17a6766..ce3cb073047 100644 --- a/tests/lib/HookHelper.php +++ b/tests/lib/HookHelper.php @@ -8,6 +8,7 @@ namespace Test; use OC\Files\Filesystem; +use OCP\Util; /** * Helper class to register hooks on @@ -17,38 +18,38 @@ class HookHelper { public static function setUpHooks() { self::clear(); - \OCP\Util::connectHook( + Util::connectHook( Filesystem::CLASSNAME, Filesystem::signal_create, '\Test\HookHelper', 'createCallback' ); - \OCP\Util::connectHook( + Util::connectHook( Filesystem::CLASSNAME, Filesystem::signal_update, '\Test\HookHelper', 'updateCallback' ); - \OCP\Util::connectHook( + Util::connectHook( Filesystem::CLASSNAME, Filesystem::signal_write, '\Test\HookHelper', 'writeCallback' ); - \OCP\Util::connectHook( + Util::connectHook( Filesystem::CLASSNAME, Filesystem::signal_post_create, '\Test\HookHelper', 'postCreateCallback' ); - \OCP\Util::connectHook( + Util::connectHook( Filesystem::CLASSNAME, Filesystem::signal_post_update, '\Test\HookHelper', 'postUpdateCallback' ); - \OCP\Util::connectHook( + Util::connectHook( Filesystem::CLASSNAME, Filesystem::signal_post_write, '\Test\HookHelper', diff --git a/tests/lib/Hooks/BasicEmitterTest.php b/tests/lib/Hooks/BasicEmitterTest.php index 98f746d38ae..49845eb2fa9 100644 --- a/tests/lib/Hooks/BasicEmitterTest.php +++ b/tests/lib/Hooks/BasicEmitterTest.php @@ -7,6 +7,8 @@ namespace Test\Hooks; +use OC\Hooks\BasicEmitter; + /** * Class DummyEmitter * @@ -14,7 +16,7 @@ namespace Test\Hooks; * * @package Test\Hooks */ -class DummyEmitter extends \OC\Hooks\BasicEmitter { +class DummyEmitter extends BasicEmitter { public function emitEvent($scope, $method, $arguments = []) { $this->emit($scope, $method, $arguments); } @@ -49,17 +51,17 @@ class BasicEmitterTest extends \Test\TestCase { throw new EmittedException; } - + public function testAnonymousFunction(): void { $this->expectException(\Test\Hooks\EmittedException::class); - $this->emitter->listen('Test', 'test', function () { + $this->emitter->listen('Test', 'test', function (): void { throw new EmittedException; }); $this->emitter->emitEvent('Test', 'test'); } - + public function testStaticCallback(): void { $this->expectException(\Test\Hooks\EmittedException::class); @@ -67,7 +69,7 @@ class BasicEmitterTest extends \Test\TestCase { $this->emitter->emitEvent('Test', 'test'); } - + public function testNonStaticCallback(): void { $this->expectException(\Test\Hooks\EmittedException::class); @@ -77,7 +79,7 @@ class BasicEmitterTest extends \Test\TestCase { public function testOnlyCallOnce(): void { $count = 0; - $listener = function () use (&$count) { + $listener = function () use (&$count): void { $count++; }; $this->emitter->listen('Test', 'test', $listener); @@ -88,7 +90,7 @@ class BasicEmitterTest extends \Test\TestCase { public function testDifferentMethods(): void { $count = 0; - $listener = function () use (&$count) { + $listener = function () use (&$count): void { $count++; }; $this->emitter->listen('Test', 'test', $listener); @@ -100,7 +102,7 @@ class BasicEmitterTest extends \Test\TestCase { public function testDifferentScopes(): void { $count = 0; - $listener = function () use (&$count) { + $listener = function () use (&$count): void { $count++; }; $this->emitter->listen('Test', 'test', $listener); @@ -112,10 +114,10 @@ class BasicEmitterTest extends \Test\TestCase { public function testDifferentCallbacks(): void { $count = 0; - $listener1 = function () use (&$count) { + $listener1 = function () use (&$count): void { $count++; }; - $listener2 = function () use (&$count) { + $listener2 = function () use (&$count): void { $count++; }; $this->emitter->listen('Test', 'test', $listener1); @@ -124,11 +126,11 @@ class BasicEmitterTest extends \Test\TestCase { $this->assertEquals(2, $count, 'Listener called an invalid number of times (' . $count . ') expected 2'); } - + public function testArguments(): void { $this->expectException(\Test\Hooks\EmittedException::class); - $this->emitter->listen('Test', 'test', function ($foo, $bar) { + $this->emitter->listen('Test', 'test', function ($foo, $bar): void { if ($foo == 'foo' and $bar == 'bar') { throw new EmittedException; } @@ -136,11 +138,11 @@ class BasicEmitterTest extends \Test\TestCase { $this->emitter->emitEvent('Test', 'test', ['foo', 'bar']); } - + public function testNamedArguments(): void { $this->expectException(\Test\Hooks\EmittedException::class); - $this->emitter->listen('Test', 'test', function ($foo, $bar) { + $this->emitter->listen('Test', 'test', function ($foo, $bar): void { if ($foo == 'foo' and $bar == 'bar') { throw new EmittedException; } @@ -149,7 +151,7 @@ class BasicEmitterTest extends \Test\TestCase { } public function testRemoveAllSpecified(): void { - $listener = function () { + $listener = function (): void { throw new EmittedException; }; $this->emitter->listen('Test', 'test', $listener); @@ -160,10 +162,10 @@ class BasicEmitterTest extends \Test\TestCase { } public function testRemoveWildcardListener(): void { - $listener1 = function () { + $listener1 = function (): void { throw new EmittedException; }; - $listener2 = function () { + $listener2 = function (): void { throw new EmittedException; }; $this->emitter->listen('Test', 'test', $listener1); @@ -175,7 +177,7 @@ class BasicEmitterTest extends \Test\TestCase { } public function testRemoveWildcardMethod(): void { - $listener = function () { + $listener = function (): void { throw new EmittedException; }; $this->emitter->listen('Test', 'test', $listener); @@ -188,7 +190,7 @@ class BasicEmitterTest extends \Test\TestCase { } public function testRemoveWildcardScope(): void { - $listener = function () { + $listener = function (): void { throw new EmittedException; }; $this->emitter->listen('Test', 'test', $listener); @@ -201,7 +203,7 @@ class BasicEmitterTest extends \Test\TestCase { } public function testRemoveWildcardScopeAndMethod(): void { - $listener = function () { + $listener = function (): void { throw new EmittedException; }; $this->emitter->listen('Test', 'test', $listener); @@ -215,14 +217,14 @@ class BasicEmitterTest extends \Test\TestCase { $this->addToAssertionCount(1); } - + public function testRemoveKeepOtherCallback(): void { $this->expectException(\Test\Hooks\EmittedException::class); - $listener1 = function () { + $listener1 = function (): void { throw new EmittedException; }; - $listener2 = function () { + $listener2 = function (): void { throw new EmittedException; }; $this->emitter->listen('Test', 'test', $listener1); @@ -233,11 +235,11 @@ class BasicEmitterTest extends \Test\TestCase { $this->addToAssertionCount(1); } - + public function testRemoveKeepOtherMethod(): void { $this->expectException(\Test\Hooks\EmittedException::class); - $listener = function () { + $listener = function (): void { throw new EmittedException; }; $this->emitter->listen('Test', 'test', $listener); @@ -248,11 +250,11 @@ class BasicEmitterTest extends \Test\TestCase { $this->addToAssertionCount(1); } - + public function testRemoveKeepOtherScope(): void { $this->expectException(\Test\Hooks\EmittedException::class); - $listener = function () { + $listener = function (): void { throw new EmittedException; }; $this->emitter->listen('Test', 'test', $listener); @@ -263,11 +265,11 @@ class BasicEmitterTest extends \Test\TestCase { $this->addToAssertionCount(1); } - + public function testRemoveNonExistingName(): void { $this->expectException(\Test\Hooks\EmittedException::class); - $listener = function () { + $listener = function (): void { throw new EmittedException; }; $this->emitter->listen('Test', 'test', $listener); diff --git a/tests/lib/Http/Client/ClientServiceTest.php b/tests/lib/Http/Client/ClientServiceTest.php index 7c9cd55a6cc..fd5b155ca69 100644 --- a/tests/lib/Http/Client/ClientServiceTest.php +++ b/tests/lib/Http/Client/ClientServiceTest.php @@ -40,7 +40,7 @@ class ClientServiceTest extends \Test\TestCase { $dnsPinMiddleware ->expects($this->atLeastOnce()) ->method('addDnsPinning') - ->willReturn(function () { + ->willReturn(function (): void { }); $remoteHostValidator = $this->createMock(IRemoteHostValidator::class); $eventLogger = $this->createMock(IEventLogger::class); @@ -58,9 +58,9 @@ class ClientServiceTest extends \Test\TestCase { $handler = new CurlHandler(); $stack = HandlerStack::create($handler); $stack->push($dnsPinMiddleware->addDnsPinning()); - $stack->push(Middleware::tap(function (RequestInterface $request) use ($eventLogger) { + $stack->push(Middleware::tap(function (RequestInterface $request) use ($eventLogger): void { $eventLogger->start('http:request', $request->getMethod() . ' request to ' . $request->getRequestTarget()); - }, function () use ($eventLogger) { + }, function () use ($eventLogger): void { $eventLogger->end('http:request'); }), 'event logger'); $guzzleClient = new GuzzleClient(['handler' => $stack]); @@ -89,7 +89,7 @@ class ClientServiceTest extends \Test\TestCase { $dnsPinMiddleware ->expects($this->never()) ->method('addDnsPinning') - ->willReturn(function () { + ->willReturn(function (): void { }); $remoteHostValidator = $this->createMock(IRemoteHostValidator::class); $eventLogger = $this->createMock(IEventLogger::class); @@ -106,9 +106,9 @@ class ClientServiceTest extends \Test\TestCase { $handler = new CurlHandler(); $stack = HandlerStack::create($handler); - $stack->push(Middleware::tap(function (RequestInterface $request) use ($eventLogger) { + $stack->push(Middleware::tap(function (RequestInterface $request) use ($eventLogger): void { $eventLogger->start('http:request', $request->getMethod() . ' request to ' . $request->getRequestTarget()); - }, function () use ($eventLogger) { + }, function () use ($eventLogger): void { $eventLogger->end('http:request'); }), 'event logger'); $guzzleClient = new GuzzleClient(['handler' => $stack]); diff --git a/tests/lib/Http/Client/ClientTest.php b/tests/lib/Http/Client/ClientTest.php index 92e5f04d7f0..2c0f982c51c 100644 --- a/tests/lib/Http/Client/ClientTest.php +++ b/tests/lib/Http/Client/ClientTest.php @@ -66,16 +66,16 @@ class ClientTest extends \Test\TestCase { public function testGetProxyUriProxyHostEmptyPassword(): void { $this->config ->method('getSystemValue') - ->will($this->returnValueMap([ + ->willReturnMap([ ['proxyexclude', [], []], - ])); + ]); $this->config ->method('getSystemValueString') - ->will($this->returnValueMap([ + ->willReturnMap([ ['proxy', '', 'foo'], ['proxyuserpwd', '', ''], - ])); + ]); $this->assertEquals([ 'http' => 'foo', @@ -254,21 +254,21 @@ class ClientTest extends \Test\TestCase { private function setUpDefaultRequestOptions(): void { $this->config ->method('getSystemValue') - ->will($this->returnValueMap([ + ->willReturnMap([ ['proxyexclude', [], []], - ])); + ]); $this->config ->method('getSystemValueString') - ->will($this->returnValueMap([ + ->willReturnMap([ ['proxy', '', 'foo'], ['proxyuserpwd', '', ''], - ])); + ]); $this->config ->method('getSystemValueBool') - ->will($this->returnValueMap([ + ->willReturnMap([ ['installed', false, true], ['allow_local_remote_servers', false, true], - ])); + ]); $this->certificateManager ->expects($this->once()) @@ -481,7 +481,7 @@ class ClientTest extends \Test\TestCase { \Psr\Http\Message\RequestInterface $request, \Psr\Http\Message\ResponseInterface $response, \Psr\Http\Message\UriInterface $uri, - ) { + ): void { }, ], ], self::invokePrivate($this->client, 'buildRequestOptions', [[]])); @@ -532,7 +532,7 @@ class ClientTest extends \Test\TestCase { \Psr\Http\Message\RequestInterface $request, \Psr\Http\Message\ResponseInterface $response, \Psr\Http\Message\UriInterface $uri, - ) { + ): void { }, ], ], self::invokePrivate($this->client, 'buildRequestOptions', [[]])); @@ -584,7 +584,7 @@ class ClientTest extends \Test\TestCase { \Psr\Http\Message\RequestInterface $request, \Psr\Http\Message\ResponseInterface $response, \Psr\Http\Message\UriInterface $uri, - ) { + ): void { }, ], ], self::invokePrivate($this->client, 'buildRequestOptions', [[]])); diff --git a/tests/lib/Http/Client/DnsPinMiddlewareTest.php b/tests/lib/Http/Client/DnsPinMiddlewareTest.php index 88059d44121..9c0aa198cd8 100644 --- a/tests/lib/Http/Client/DnsPinMiddlewareTest.php +++ b/tests/lib/Http/Client/DnsPinMiddlewareTest.php @@ -273,7 +273,7 @@ class DnsPinMiddlewareTest extends TestCase { $this->expectExceptionMessage('violates local access rules'); $mockHandler = new MockHandler([ - static function (RequestInterface $request, array $options) { + static function (RequestInterface $request, array $options): void { // The handler should not be called }, ]); @@ -320,7 +320,7 @@ class DnsPinMiddlewareTest extends TestCase { $this->expectExceptionMessage('violates local access rules'); $mockHandler = new MockHandler([ - static function (RequestInterface $request, array $options) { + static function (RequestInterface $request, array $options): void { // The handler should not be called }, ]); @@ -367,7 +367,7 @@ class DnsPinMiddlewareTest extends TestCase { $this->expectExceptionMessage('violates local access rules'); $mockHandler = new MockHandler([ - static function (RequestInterface $request, array $options) { + static function (RequestInterface $request, array $options): void { // The handler should not be called }, ]); @@ -457,7 +457,7 @@ class DnsPinMiddlewareTest extends TestCase { $this->expectExceptionMessage('No DNS record found for www.example.com'); $mockHandler = new MockHandler([ - static function (RequestInterface $request, array $options) { + static function (RequestInterface $request, array $options): void { // The handler should not be called }, ]); @@ -480,7 +480,7 @@ class DnsPinMiddlewareTest extends TestCase { public function testIgnoreSubdomainForSoaQuery(): void { $mockHandler = new MockHandler([ - static function (RequestInterface $request, array $options) { + static function (RequestInterface $request, array $options): void { // The handler should not be called }, ]); diff --git a/tests/lib/InfoXmlTest.php b/tests/lib/InfoXmlTest.php index ffc367d4471..151b629f50b 100644 --- a/tests/lib/InfoXmlTest.php +++ b/tests/lib/InfoXmlTest.php @@ -7,6 +7,7 @@ namespace Test; use OCP\App\IAppManager; +use OCP\AppFramework\App; use OCP\Server; /** @@ -58,75 +59,75 @@ class InfoXmlTest extends TestCase { \OC_App::registerAutoloading($app, $appPath); //Add the appcontainer - $applicationClassName = \OCP\AppFramework\App::buildAppNamespace($app) . '\\AppInfo\\Application'; + $applicationClassName = App::buildAppNamespace($app) . '\\AppInfo\\Application'; if (class_exists($applicationClassName)) { $application = new $applicationClassName(); $this->addToAssertionCount(1); } else { - $application = new \OCP\AppFramework\App($app); + $application = new App($app); $this->addToAssertionCount(1); } if (isset($appInfo['background-jobs'])) { foreach ($appInfo['background-jobs'] as $job) { $this->assertTrue(class_exists($job), 'Asserting background job "' . $job . '" exists'); - $this->assertInstanceOf($job, \OC::$server->query($job)); + $this->assertInstanceOf($job, Server::get($job)); } } if (isset($appInfo['two-factor-providers'])) { foreach ($appInfo['two-factor-providers'] as $provider) { $this->assertTrue(class_exists($provider), 'Asserting two-factor providers "' . $provider . '" exists'); - $this->assertInstanceOf($provider, \OC::$server->query($provider)); + $this->assertInstanceOf($provider, Server::get($provider)); } } if (isset($appInfo['commands'])) { foreach ($appInfo['commands'] as $command) { $this->assertTrue(class_exists($command), 'Asserting command "' . $command . '" exists'); - $this->assertInstanceOf($command, \OC::$server->query($command)); + $this->assertInstanceOf($command, Server::get($command)); } } if (isset($appInfo['repair-steps']['pre-migration'])) { foreach ($appInfo['repair-steps']['pre-migration'] as $migration) { $this->assertTrue(class_exists($migration), 'Asserting pre-migration "' . $migration . '" exists'); - $this->assertInstanceOf($migration, \OC::$server->query($migration)); + $this->assertInstanceOf($migration, Server::get($migration)); } } if (isset($appInfo['repair-steps']['post-migration'])) { foreach ($appInfo['repair-steps']['post-migration'] as $migration) { $this->assertTrue(class_exists($migration), 'Asserting post-migration "' . $migration . '" exists'); - $this->assertInstanceOf($migration, \OC::$server->query($migration)); + $this->assertInstanceOf($migration, Server::get($migration)); } } if (isset($appInfo['repair-steps']['live-migration'])) { foreach ($appInfo['repair-steps']['live-migration'] as $migration) { $this->assertTrue(class_exists($migration), 'Asserting live-migration "' . $migration . '" exists'); - $this->assertInstanceOf($migration, \OC::$server->query($migration)); + $this->assertInstanceOf($migration, Server::get($migration)); } } if (isset($appInfo['repair-steps']['install'])) { foreach ($appInfo['repair-steps']['install'] as $migration) { $this->assertTrue(class_exists($migration), 'Asserting install-migration "' . $migration . '" exists'); - $this->assertInstanceOf($migration, \OC::$server->query($migration)); + $this->assertInstanceOf($migration, Server::get($migration)); } } if (isset($appInfo['repair-steps']['uninstall'])) { foreach ($appInfo['repair-steps']['uninstall'] as $migration) { $this->assertTrue(class_exists($migration), 'Asserting uninstall-migration "' . $migration . '" exists'); - $this->assertInstanceOf($migration, \OC::$server->query($migration)); + $this->assertInstanceOf($migration, Server::get($migration)); } } if (isset($appInfo['commands'])) { foreach ($appInfo['commands'] as $command) { $this->assertTrue(class_exists($command), 'Asserting command "' . $command . '"exists'); - $this->assertInstanceOf($command, \OC::$server->query($command)); + $this->assertInstanceOf($command, Server::get($command)); } } } diff --git a/tests/lib/InstallerTest.php b/tests/lib/InstallerTest.php index 9e77cb6a4fc..c05c65cba85 100644 --- a/tests/lib/InstallerTest.php +++ b/tests/lib/InstallerTest.php @@ -15,6 +15,7 @@ use OCP\Http\Client\IClient; use OCP\Http\Client\IClientService; use OCP\IConfig; use OCP\ITempManager; +use OCP\Server; use Psr\Log\LoggerInterface; /** @@ -46,14 +47,14 @@ class InstallerTest extends TestCase { $this->logger = $this->createMock(LoggerInterface::class); $this->config = $this->createMock(IConfig::class); - $config = \OC::$server->getConfig(); + $config = Server::get(IConfig::class); $this->appstore = $config->setSystemValue('appstoreenabled', true); $config->setSystemValue('appstoreenabled', true); $installer = new Installer( - \OC::$server->get(AppFetcher::class), - \OC::$server->get(IClientService::class), - \OC::$server->getTempManager(), - \OC::$server->get(LoggerInterface::class), + Server::get(AppFetcher::class), + Server::get(IClientService::class), + Server::get(ITempManager::class), + Server::get(LoggerInterface::class), $config, false ); @@ -73,22 +74,22 @@ class InstallerTest extends TestCase { protected function tearDown(): void { $installer = new Installer( - \OC::$server->get(AppFetcher::class), - \OC::$server->get(IClientService::class), - \OC::$server->getTempManager(), - \OC::$server->get(LoggerInterface::class), - \OC::$server->getConfig(), + Server::get(AppFetcher::class), + Server::get(IClientService::class), + Server::get(ITempManager::class), + Server::get(LoggerInterface::class), + Server::get(IConfig::class), false ); $installer->removeApp(self::$appid); - \OC::$server->getConfig()->setSystemValue('appstoreenabled', $this->appstore); + Server::get(IConfig::class)->setSystemValue('appstoreenabled', $this->appstore); parent::tearDown(); } public function testInstallApp(): void { // Read the current version of the app to check for bug #2572 - \OCP\Server::get(IAppManager::class)->getAppVersion('testapp', true); + Server::get(IAppManager::class)->getAppVersion('testapp', true); // Extract app $pathOfTestApp = __DIR__ . '/../data/testapp.zip'; @@ -97,17 +98,17 @@ class InstallerTest extends TestCase { // Install app $installer = new Installer( - \OC::$server->get(AppFetcher::class), - \OC::$server->get(IClientService::class), - \OC::$server->getTempManager(), - \OC::$server->get(LoggerInterface::class), - \OC::$server->getConfig(), + Server::get(AppFetcher::class), + Server::get(IClientService::class), + Server::get(ITempManager::class), + Server::get(LoggerInterface::class), + Server::get(IConfig::class), false ); - $this->assertNull(\OC::$server->getConfig()->getAppValue('testapp', 'enabled', null), 'Check that the app is not listed before installation'); + $this->assertNull(Server::get(IConfig::class)->getAppValue('testapp', 'enabled', null), 'Check that the app is not listed before installation'); $this->assertSame('testapp', $installer->installApp(self::$appid)); - $this->assertSame('no', \OC::$server->getConfig()->getAppValue('testapp', 'enabled', null), 'Check that the app is listed after installation'); - $this->assertSame('0.9', \OC::$server->getConfig()->getAppValue('testapp', 'installed_version')); + $this->assertSame('no', Server::get(IConfig::class)->getAppValue('testapp', 'enabled', null), 'Check that the app is listed after installation'); + $this->assertSame('0.9', Server::get(IConfig::class)->getAppValue('testapp', 'installed_version')); $installer->removeApp(self::$appid); } @@ -337,7 +338,7 @@ u/spPSSVhaun5BA1FlphB2TkgnzlCmxJa63nFY045e/Jq+IKMcqqZl/092gbI2EQ ->expects($this->once()) ->method('get') ->willReturn($appArray); - $realTmpFile = \OC::$server->getTempManager()->getTemporaryFile('.tar.gz'); + $realTmpFile = Server::get(ITempManager::class)->getTemporaryFile('.tar.gz'); copy(__DIR__ . '/../data/testapp.tar.gz', $realTmpFile); $this->tempManager ->expects($this->once()) @@ -415,14 +416,14 @@ YwDVP+QmNRzx72jtqAN/Kc3CvQ9nkgYhU65B95aX0xA=', ->expects($this->once()) ->method('get') ->willReturn($appArray); - $realTmpFile = \OC::$server->getTempManager()->getTemporaryFile('.tar.gz'); + $realTmpFile = Server::get(ITempManager::class)->getTemporaryFile('.tar.gz'); copy(__DIR__ . '/../data/testapp1.tar.gz', $realTmpFile); $this->tempManager ->expects($this->once()) ->method('getTemporaryFile') ->with('.tar.gz') ->willReturn($realTmpFile); - $realTmpFolder = \OC::$server->getTempManager()->getTemporaryFolder(); + $realTmpFolder = Server::get(ITempManager::class)->getTemporaryFolder(); mkdir($realTmpFolder . '/testfolder'); $this->tempManager ->expects($this->once()) @@ -499,14 +500,14 @@ YwDVP+QmNRzx72jtqAN/Kc3CvQ9nkgYhU65B95aX0xA=', ->expects($this->once()) ->method('get') ->willReturn($appArray); - $realTmpFile = \OC::$server->getTempManager()->getTemporaryFile('.tar.gz'); + $realTmpFile = Server::get(ITempManager::class)->getTemporaryFile('.tar.gz'); copy(__DIR__ . '/../data/testapp1.tar.gz', $realTmpFile); $this->tempManager ->expects($this->once()) ->method('getTemporaryFile') ->with('.tar.gz') ->willReturn($realTmpFile); - $realTmpFolder = \OC::$server->getTempManager()->getTemporaryFolder(); + $realTmpFolder = Server::get(ITempManager::class)->getTemporaryFolder(); $this->tempManager ->expects($this->once()) ->method('getTemporaryFolder') @@ -578,14 +579,14 @@ MPLX6f5V9tCJtlH6ztmEcDROfvuVc0U3rEhqx2hphoyo+MZrPFpdcJL8KkIdMKbY ->expects($this->once()) ->method('get') ->willReturn($appArray); - $realTmpFile = \OC::$server->getTempManager()->getTemporaryFile('.tar.gz'); + $realTmpFile = Server::get(ITempManager::class)->getTemporaryFile('.tar.gz'); copy(__DIR__ . '/../data/testapp.tar.gz', $realTmpFile); $this->tempManager ->expects($this->once()) ->method('getTemporaryFile') ->with('.tar.gz') ->willReturn($realTmpFile); - $realTmpFolder = \OC::$server->getTempManager()->getTemporaryFolder(); + $realTmpFolder = Server::get(ITempManager::class)->getTemporaryFolder(); $this->tempManager ->expects($this->once()) ->method('getTemporaryFolder') @@ -672,14 +673,14 @@ JXhrdaWDZ8fzpUjugrtC3qslsqL0dzgU37anS3HwrT8=', ->expects($this->once()) ->method('get') ->willReturn($appArray); - $realTmpFile = \OC::$server->getTempManager()->getTemporaryFile('.tar.gz'); + $realTmpFile = Server::get(ITempManager::class)->getTemporaryFile('.tar.gz'); copy(__DIR__ . '/../data/testapp.0.8.tar.gz', $realTmpFile); $this->tempManager ->expects($this->once()) ->method('getTemporaryFile') ->with('.tar.gz') ->willReturn($realTmpFile); - $realTmpFolder = \OC::$server->getTempManager()->getTemporaryFolder(); + $realTmpFolder = Server::get(ITempManager::class)->getTemporaryFolder(); $this->tempManager ->expects($this->once()) ->method('getTemporaryFolder') diff --git a/tests/lib/IntegrityCheck/CheckerTest.php b/tests/lib/IntegrityCheck/CheckerTest.php index 8414a531464..fc540707c70 100644 --- a/tests/lib/IntegrityCheck/CheckerTest.php +++ b/tests/lib/IntegrityCheck/CheckerTest.php @@ -8,6 +8,7 @@ namespace Test\IntegrityCheck; use OC\Core\Command\Maintenance\Mimetype\GenerateMimetypeFileBuilder; +use OC\Files\Type\Detection; use OC\IntegrityCheck\Checker; use OC\IntegrityCheck\Helpers\AppLocator; use OC\IntegrityCheck\Helpers\EnvironmentHelper; @@ -54,7 +55,7 @@ class CheckerTest extends TestCase { $this->appConfig = $this->createMock(IAppConfig::class); $this->cacheFactory = $this->createMock(ICacheFactory::class); $this->appManager = $this->createMock(IAppManager::class); - $this->mimeTypeDetector = $this->createMock(\OC\Files\Type\Detection::class); + $this->mimeTypeDetector = $this->createMock(Detection::class); $this->config->method('getAppValue') ->willReturnArgument(2); @@ -111,7 +112,7 @@ class CheckerTest extends TestCase { $this->fileAccessHelper ->expects($this->once()) ->method('file_put_contents') - ->will($this->throwException(new \Exception('Exception message'))); + ->willThrowException(new \Exception('Exception message')); $keyBundle = file_get_contents(__DIR__ . '/../../data/integritycheck/SomeApp.crt'); $rsaPrivateKey = file_get_contents(__DIR__ . '/../../data/integritycheck/SomeApp.key'); @@ -445,7 +446,7 @@ class CheckerTest extends TestCase { $this->fileAccessHelper ->expects($this->once()) ->method('assertDirectoryExists') - ->will($this->throwException(new \Exception('Exception message'))); + ->willThrowException(new \Exception('Exception message')); $this->fileAccessHelper ->expects($this->once()) ->method('is_writable') @@ -469,7 +470,7 @@ class CheckerTest extends TestCase { $this->fileAccessHelper ->expects($this->once()) ->method('assertDirectoryExists') - ->will($this->throwException(new \Exception('Exception message'))); + ->willThrowException(new \Exception('Exception message')); $this->fileAccessHelper ->expects($this->once()) ->method('is_writable') diff --git a/tests/lib/IntegrityCheck/Helpers/FileAccessHelperTest.php b/tests/lib/IntegrityCheck/Helpers/FileAccessHelperTest.php index 866850b7cff..ef537155388 100644 --- a/tests/lib/IntegrityCheck/Helpers/FileAccessHelperTest.php +++ b/tests/lib/IntegrityCheck/Helpers/FileAccessHelperTest.php @@ -8,6 +8,8 @@ namespace Test\IntegrityCheck\Helpers; use OC\IntegrityCheck\Helpers\FileAccessHelper; +use OCP\ITempManager; +use OCP\Server; use Test\TestCase; class FileAccessHelperTest extends TestCase { @@ -20,7 +22,7 @@ class FileAccessHelperTest extends TestCase { } public function testReadAndWrite(): void { - $tempManager = \OC::$server->getTempManager(); + $tempManager = Server::get(ITempManager::class); $filePath = $tempManager->getTemporaryFile(); $data = 'SomeDataGeneratedByIntegrityCheck'; @@ -38,7 +40,7 @@ class FileAccessHelperTest extends TestCase { public function testIs_writable(): void { $this->assertFalse($this->fileAccessHelper->is_writable('/anabsolutelynotexistingfolder/on/the/system.txt')); - $this->assertTrue($this->fileAccessHelper->is_writable(\OC::$server->getTempManager()->getTemporaryFile('MyFile'))); + $this->assertTrue($this->fileAccessHelper->is_writable(Server::get(ITempManager::class)->getTemporaryFile('MyFile'))); } @@ -50,7 +52,7 @@ class FileAccessHelperTest extends TestCase { } public function testAssertDirectoryExists(): void { - $this->fileAccessHelper->assertDirectoryExists(\OC::$server->getTempManager()->getTemporaryFolder('/testfolder/')); + $this->fileAccessHelper->assertDirectoryExists(Server::get(ITempManager::class)->getTemporaryFolder('/testfolder/')); $this->addToAssertionCount(1); } } diff --git a/tests/lib/L10N/L10nTest.php b/tests/lib/L10N/L10nTest.php index a95a1241f4b..4b934661f76 100644 --- a/tests/lib/L10N/L10nTest.php +++ b/tests/lib/L10N/L10nTest.php @@ -16,6 +16,8 @@ use OCP\IConfig; use OCP\IRequest; use OCP\IUserSession; use OCP\L10N\IFactory; +use OCP\Server; +use OCP\Util; use Test\TestCase; /** @@ -203,12 +205,12 @@ class L10nTest extends TestCase { } public function testServiceGetLanguageCode(): void { - $l = \OCP\Util::getL10N('lib', 'de'); + $l = Util::getL10N('lib', 'de'); $this->assertEquals('de', $l->getLanguageCode()); } public function testWeekdayName(): void { - $l = \OCP\Util::getL10N('lib', 'de'); + $l = Util::getL10N('lib', 'de'); $this->assertEquals('Mo.', $l->l('weekdayName', new \DateTime('2017-11-6'), ['width' => 'abbreviated'])); } @@ -220,7 +222,7 @@ class L10nTest extends TestCase { public function testFindLanguageFromLocale($locale, $language): void { $this->assertEquals( $language, - \OC::$server->get(IFactory::class)->findLanguageFromLocale('lib', $locale) + Server::get(IFactory::class)->findLanguageFromLocale('lib', $locale) ); } diff --git a/tests/lib/LargeFileHelperGetFileSizeTest.php b/tests/lib/LargeFileHelperGetFileSizeTest.php index 7f6604bdb35..dbb8658d184 100644 --- a/tests/lib/LargeFileHelperGetFileSizeTest.php +++ b/tests/lib/LargeFileHelperGetFileSizeTest.php @@ -8,6 +8,9 @@ namespace Test; use bantu\IniGetWrapper\IniGetWrapper; +use OC\LargeFileHelper; +use OCP\Server; +use OCP\Util; /** * Tests whether LargeFileHelper is able to determine file size at all. @@ -23,7 +26,7 @@ class LargeFileHelperGetFileSizeTest extends TestCase { protected function setUp(): void { parent::setUp(); - $this->helper = new \OC\LargeFileHelper(); + $this->helper = new LargeFileHelper(); } public static function dataFileNameProvider(): array { @@ -44,7 +47,7 @@ class LargeFileHelperGetFileSizeTest extends TestCase { 'The PHP curl extension is required for this test.' ); } - if (\OC::$server->get(IniGetWrapper::class)->getString('open_basedir') !== '') { + if (Server::get(IniGetWrapper::class)->getString('open_basedir') !== '') { $this->markTestSkipped( 'The PHP curl extension does not work with the file:// protocol when open_basedir is enabled.' ); @@ -62,7 +65,7 @@ class LargeFileHelperGetFileSizeTest extends TestCase { if (escapeshellarg('strängé') !== '\'strängé\'') { $this->markTestSkipped('Your escapeshell args removes accents'); } - if (!\OCP\Util::isFunctionEnabled('exec')) { + if (!Util::isFunctionEnabled('exec')) { $this->markTestSkipped( 'The exec() function needs to be enabled for this test.' ); diff --git a/tests/lib/LargeFileHelperTest.php b/tests/lib/LargeFileHelperTest.php index 2cccfa441ab..0745c19f158 100644 --- a/tests/lib/LargeFileHelperTest.php +++ b/tests/lib/LargeFileHelperTest.php @@ -7,12 +7,14 @@ namespace Test; +use OC\LargeFileHelper; + class LargeFileHelperTest extends TestCase { protected $helper; protected function setUp(): void { parent::setUp(); - $this->helper = new \OC\LargeFileHelper; + $this->helper = new LargeFileHelper; } public function testFormatUnsignedIntegerFloat(): void { diff --git a/tests/lib/Lock/DBLockingProviderTest.php b/tests/lib/Lock/DBLockingProviderTest.php index 1c02e8d7d77..1216d42f343 100644 --- a/tests/lib/Lock/DBLockingProviderTest.php +++ b/tests/lib/Lock/DBLockingProviderTest.php @@ -7,8 +7,11 @@ namespace Test\Lock; +use OC\Lock\DBLockingProvider; use OCP\AppFramework\Utility\ITimeFactory; +use OCP\IDBConnection; use OCP\Lock\ILockingProvider; +use OCP\Server; /** * Class DBLockingProvider @@ -50,8 +53,8 @@ class DBLockingProviderTest extends LockingProvider { * @return \OCP\Lock\ILockingProvider */ protected function getInstance() { - $this->connection = \OC::$server->getDatabaseConnection(); - return new \OC\Lock\DBLockingProvider($this->connection, $this->timeFactory, 3600); + $this->connection = Server::get(IDBConnection::class); + return new DBLockingProvider($this->connection, $this->timeFactory, 3600); } protected function tearDown(): void { diff --git a/tests/lib/Lock/LockingProvider.php b/tests/lib/Lock/LockingProvider.php index b7e301c55a6..2f4407a8659 100644 --- a/tests/lib/Lock/LockingProvider.php +++ b/tests/lib/Lock/LockingProvider.php @@ -61,7 +61,7 @@ abstract class LockingProvider extends TestCase { public function testDoubleExclusiveLock(): void { - $this->expectException(\OCP\Lock\LockedException::class); + $this->expectException(LockedException::class); $this->instance->acquireLock('foo', ILockingProvider::LOCK_EXCLUSIVE); $this->assertTrue($this->instance->isLocked('foo', ILockingProvider::LOCK_EXCLUSIVE)); @@ -78,7 +78,7 @@ abstract class LockingProvider extends TestCase { public function testExclusiveLockAfterShared(): void { - $this->expectException(\OCP\Lock\LockedException::class); + $this->expectException(LockedException::class); $this->instance->acquireLock('foo', ILockingProvider::LOCK_SHARED); $this->assertTrue($this->instance->isLocked('foo', ILockingProvider::LOCK_SHARED)); @@ -152,7 +152,7 @@ abstract class LockingProvider extends TestCase { public function testSharedLockAfterExclusive(): void { - $this->expectException(\OCP\Lock\LockedException::class); + $this->expectException(LockedException::class); $this->instance->acquireLock('foo', ILockingProvider::LOCK_EXCLUSIVE); $this->assertTrue($this->instance->isLocked('foo', ILockingProvider::LOCK_EXCLUSIVE)); @@ -199,7 +199,7 @@ abstract class LockingProvider extends TestCase { public function testChangeLockToExclusiveDoubleShared(): void { - $this->expectException(\OCP\Lock\LockedException::class); + $this->expectException(LockedException::class); $this->instance->acquireLock('foo', ILockingProvider::LOCK_SHARED); $this->instance->acquireLock('foo', ILockingProvider::LOCK_SHARED); @@ -208,14 +208,14 @@ abstract class LockingProvider extends TestCase { public function testChangeLockToExclusiveNoShared(): void { - $this->expectException(\OCP\Lock\LockedException::class); + $this->expectException(LockedException::class); $this->instance->changeLock('foo', ILockingProvider::LOCK_EXCLUSIVE); } public function testChangeLockToExclusiveFromExclusive(): void { - $this->expectException(\OCP\Lock\LockedException::class); + $this->expectException(LockedException::class); $this->instance->acquireLock('foo', ILockingProvider::LOCK_EXCLUSIVE); $this->instance->changeLock('foo', ILockingProvider::LOCK_EXCLUSIVE); @@ -223,14 +223,14 @@ abstract class LockingProvider extends TestCase { public function testChangeLockToSharedNoExclusive(): void { - $this->expectException(\OCP\Lock\LockedException::class); + $this->expectException(LockedException::class); $this->instance->changeLock('foo', ILockingProvider::LOCK_SHARED); } public function testChangeLockToSharedFromShared(): void { - $this->expectException(\OCP\Lock\LockedException::class); + $this->expectException(LockedException::class); $this->instance->acquireLock('foo', ILockingProvider::LOCK_SHARED); $this->instance->changeLock('foo', ILockingProvider::LOCK_SHARED); diff --git a/tests/lib/Lock/MemcacheLockingProviderTest.php b/tests/lib/Lock/MemcacheLockingProviderTest.php index a698be65aaf..ec8ded11d1e 100644 --- a/tests/lib/Lock/MemcacheLockingProviderTest.php +++ b/tests/lib/Lock/MemcacheLockingProviderTest.php @@ -7,8 +7,10 @@ namespace Test\Lock; +use OC\Lock\MemcacheLockingProvider; use OC\Memcache\ArrayCache; use OCP\AppFramework\Utility\ITimeFactory; +use OCP\Server; class MemcacheLockingProviderTest extends LockingProvider { /** @@ -21,8 +23,8 @@ class MemcacheLockingProviderTest extends LockingProvider { */ protected function getInstance() { $this->memcache = new ArrayCache(); - $timeProvider = \OC::$server->get(ITimeFactory::class); - return new \OC\Lock\MemcacheLockingProvider($this->memcache, $timeProvider); + $timeProvider = Server::get(ITimeFactory::class); + return new MemcacheLockingProvider($this->memcache, $timeProvider); } protected function tearDown(): void { diff --git a/tests/lib/Lock/NonCachingDBLockingProviderTest.php b/tests/lib/Lock/NonCachingDBLockingProviderTest.php index b79709a08e7..ad4100a3afd 100644 --- a/tests/lib/Lock/NonCachingDBLockingProviderTest.php +++ b/tests/lib/Lock/NonCachingDBLockingProviderTest.php @@ -6,7 +6,10 @@ namespace Test\Lock; +use OC\Lock\DBLockingProvider; +use OCP\IDBConnection; use OCP\Lock\ILockingProvider; +use OCP\Server; /** * @group DB @@ -18,8 +21,8 @@ class NonCachingDBLockingProviderTest extends DBLockingProviderTest { * @return \OCP\Lock\ILockingProvider */ protected function getInstance() { - $this->connection = \OC::$server->getDatabaseConnection(); - return new \OC\Lock\DBLockingProvider($this->connection, $this->timeFactory, 3600, false); + $this->connection = Server::get(IDBConnection::class); + return new DBLockingProvider($this->connection, $this->timeFactory, 3600, false); } public function testDoubleShared(): void { diff --git a/tests/lib/Lockdown/Filesystem/NoFSTest.php b/tests/lib/Lockdown/Filesystem/NoFSTest.php index dedcf580992..ee6db48b47c 100644 --- a/tests/lib/Lockdown/Filesystem/NoFSTest.php +++ b/tests/lib/Lockdown/Filesystem/NoFSTest.php @@ -10,6 +10,7 @@ use OC\Authentication\Token\PublicKeyToken; use OC\Files\Filesystem; use OC\Lockdown\Filesystem\NullStorage; use OCP\Authentication\Token\IToken; +use OCP\Server; use Test\Traits\UserTrait; /** @@ -23,7 +24,7 @@ class NoFSTest extends \Test\TestCase { $token->setScope([ IToken::SCOPE_FILESYSTEM => true ]); - \OC::$server->get('LockdownManager')->setToken($token); + Server::get('LockdownManager')->setToken($token); parent::tearDown(); } @@ -34,7 +35,7 @@ class NoFSTest extends \Test\TestCase { IToken::SCOPE_FILESYSTEM => false ]); - \OC::$server->get('LockdownManager')->setToken($token); + Server::get('LockdownManager')->setToken($token); $this->createUser('foo', 'var'); } diff --git a/tests/lib/Log/FileTest.php b/tests/lib/Log/FileTest.php index b483da969f4..32ab4a1fdb6 100644 --- a/tests/lib/Log/FileTest.php +++ b/tests/lib/Log/FileTest.php @@ -8,8 +8,10 @@ namespace Test\Log; use OC\Log\File; +use OC\SystemConfig; use OCP\IConfig; use OCP\ILogger; +use OCP\Server; use Test\TestCase; /** @@ -24,7 +26,7 @@ class FileTest extends TestCase { protected function setUp(): void { parent::setUp(); - $config = \OC::$server->getSystemConfig(); + $config = Server::get(SystemConfig::class); $this->restore_logfile = $config->getValue('logfile'); $this->restore_logdateformat = $config->getValue('logdateformat'); @@ -32,7 +34,7 @@ class FileTest extends TestCase { $this->logFile = new File($config->getValue('datadirectory') . '/logtest.log', '', $config); } protected function tearDown(): void { - $config = \OC::$server->getSystemConfig(); + $config = Server::get(SystemConfig::class); if (isset($this->restore_logfile)) { $config->getValue('logfile', $this->restore_logfile); } else { @@ -48,7 +50,7 @@ class FileTest extends TestCase { } public function testLogging(): void { - $config = \OC::$server->get(IConfig::class); + $config = Server::get(IConfig::class); # delete old logfile unlink($config->getSystemValue('logfile')); @@ -69,7 +71,7 @@ class FileTest extends TestCase { } public function testMicrosecondsLogTimestamp(): void { - $config = \OC::$server->getConfig(); + $config = Server::get(IConfig::class); # delete old logfile unlink($config->getSystemValue('logfile')); diff --git a/tests/lib/LoggerTest.php b/tests/lib/LoggerTest.php index 5c8345b392b..972626eccb4 100644 --- a/tests/lib/LoggerTest.php +++ b/tests/lib/LoggerTest.php @@ -38,9 +38,9 @@ class LoggerTest extends TestCase implements IWriter { private function mockDefaultLogLevel(): void { $this->config->expects($this->any()) ->method('getValue') - ->will(($this->returnValueMap([ + ->willReturnMap([ ['loglevel', ILogger::WARN, ILogger::WARN], - ]))); + ]); } public function testInterpolation(): void { @@ -55,10 +55,10 @@ class LoggerTest extends TestCase implements IWriter { public function testAppCondition(): void { $this->config->expects($this->any()) ->method('getValue') - ->will(($this->returnValueMap([ + ->willReturnMap([ ['loglevel', ILogger::WARN, ILogger::WARN], ['log.condition', [], ['apps' => ['files']]] - ]))); + ]); $logger = $this->logger; $logger->info('Don\'t display info messages'); @@ -291,7 +291,7 @@ class LoggerTest extends TestCase implements IWriter { */ public function testDetectclosure(string $user, string $password): void { $this->mockDefaultLogLevel(); - $a = function ($user, $password) { + $a = function ($user, $password): void { throw new \Exception('test'); }; $this->registry->expects($this->once()) diff --git a/tests/lib/Mail/MailerTest.php b/tests/lib/Mail/MailerTest.php index 76a06e58c65..ffc0ee17256 100644 --- a/tests/lib/Mail/MailerTest.php +++ b/tests/lib/Mail/MailerTest.php @@ -18,6 +18,7 @@ use OCP\IL10N; use OCP\IURLGenerator; use OCP\L10N\IFactory; use OCP\Mail\Events\BeforeMessageSent; +use OCP\Server; use PHPUnit\Framework\MockObject\MockObject; use Psr\Log\LoggerInterface; use Symfony\Component\Mailer\Mailer as SymfonyMailer; @@ -87,7 +88,7 @@ class MailerTest extends TestCase { ['mail_sendmailmode', 'smtp', $sendmailMode], ]); - $path = \OCP\Server::get(IBinaryFinder::class)->findBinaryPath('sendmail'); + $path = Server::get(IBinaryFinder::class)->findBinaryPath('sendmail'); if ($path === false) { $path = '/usr/sbin/sendmail'; } diff --git a/tests/lib/Memcache/APCuTest.php b/tests/lib/Memcache/APCuTest.php index cb465d1f07a..199bdf298f6 100644 --- a/tests/lib/Memcache/APCuTest.php +++ b/tests/lib/Memcache/APCuTest.php @@ -8,6 +8,8 @@ namespace Test\Memcache; +use OC\Memcache\APCu; + /** * @group Memcache * @group APCu @@ -16,11 +18,11 @@ class APCuTest extends Cache { protected function setUp(): void { parent::setUp(); - if (!\OC\Memcache\APCu::isAvailable()) { + if (!APCu::isAvailable()) { $this->markTestSkipped('The APCu extension is not available.'); return; } - $this->instance = new \OC\Memcache\APCu($this->getUniqueID()); + $this->instance = new APCu($this->getUniqueID()); } public function testCasIntChanged(): void { diff --git a/tests/lib/Memcache/ArrayCacheTest.php b/tests/lib/Memcache/ArrayCacheTest.php index 42b548355eb..e71c821729c 100644 --- a/tests/lib/Memcache/ArrayCacheTest.php +++ b/tests/lib/Memcache/ArrayCacheTest.php @@ -8,12 +8,14 @@ namespace Test\Memcache; +use OC\Memcache\ArrayCache; + /** * @group Memcache */ class ArrayCacheTest extends Cache { protected function setUp(): void { parent::setUp(); - $this->instance = new \OC\Memcache\ArrayCache(''); + $this->instance = new ArrayCache(''); } } diff --git a/tests/lib/Memcache/CasTraitTest.php b/tests/lib/Memcache/CasTraitTest.php index 129819045f2..57000049cc7 100644 --- a/tests/lib/Memcache/CasTraitTest.php +++ b/tests/lib/Memcache/CasTraitTest.php @@ -7,6 +7,7 @@ namespace Test\Memcache; +use OC\Memcache\ArrayCache; use Test\TestCase; /** @@ -17,7 +18,7 @@ class CasTraitTest extends TestCase { * @return \OC\Memcache\CasTrait */ private function getCache() { - $sourceCache = new \OC\Memcache\ArrayCache(); + $sourceCache = new ArrayCache(); $mock = $this->getMockForTrait('\OC\Memcache\CasTrait'); $mock->expects($this->any()) diff --git a/tests/lib/Memcache/FactoryTest.php b/tests/lib/Memcache/FactoryTest.php index cbf908e0cc6..afd17081660 100644 --- a/tests/lib/Memcache/FactoryTest.php +++ b/tests/lib/Memcache/FactoryTest.php @@ -7,7 +7,9 @@ namespace Test\Memcache; +use OC\Memcache\Factory; use OC\Memcache\NullCache; +use OCP\HintException; use OCP\Profiler\IProfiler; use Psr\Log\LoggerInterface; @@ -61,27 +63,27 @@ class FactoryTest extends \Test\TestCase { [ // local and distributed available self::AVAILABLE1, self::AVAILABLE2, null, - self::AVAILABLE1, self::AVAILABLE2, \OC\Memcache\Factory::NULL_CACHE + self::AVAILABLE1, self::AVAILABLE2, Factory::NULL_CACHE ], [ // local and distributed null null, null, null, - \OC\Memcache\Factory::NULL_CACHE, \OC\Memcache\Factory::NULL_CACHE, \OC\Memcache\Factory::NULL_CACHE + Factory::NULL_CACHE, Factory::NULL_CACHE, Factory::NULL_CACHE ], [ // local available, distributed null (most common scenario) self::AVAILABLE1, null, null, - self::AVAILABLE1, self::AVAILABLE1, \OC\Memcache\Factory::NULL_CACHE + self::AVAILABLE1, self::AVAILABLE1, Factory::NULL_CACHE ], [ // locking cache available null, null, self::AVAILABLE1, - \OC\Memcache\Factory::NULL_CACHE, \OC\Memcache\Factory::NULL_CACHE, self::AVAILABLE1 + Factory::NULL_CACHE, Factory::NULL_CACHE, self::AVAILABLE1 ], [ // locking cache unavailable: no exception here in the factory null, null, self::UNAVAILABLE1, - \OC\Memcache\Factory::NULL_CACHE, \OC\Memcache\Factory::NULL_CACHE, \OC\Memcache\Factory::NULL_CACHE + Factory::NULL_CACHE, Factory::NULL_CACHE, Factory::NULL_CACHE ] ]; } @@ -110,7 +112,7 @@ class FactoryTest extends \Test\TestCase { $expectedLocalCache, $expectedDistributedCache, $expectedLockingCache): void { $logger = $this->getMockBuilder(LoggerInterface::class)->getMock(); $profiler = $this->getMockBuilder(IProfiler::class)->getMock(); - $factory = new \OC\Memcache\Factory(fn () => 'abc', $logger, $profiler, $localCache, $distributedCache, $lockingCache); + $factory = new Factory(fn () => 'abc', $logger, $profiler, $localCache, $distributedCache, $lockingCache); $this->assertTrue(is_a($factory->createLocal(), $expectedLocalCache)); $this->assertTrue(is_a($factory->createDistributed(), $expectedDistributedCache)); $this->assertTrue(is_a($factory->createLocking(), $expectedLockingCache)); @@ -120,17 +122,17 @@ class FactoryTest extends \Test\TestCase { * @dataProvider cacheUnavailableProvider */ public function testCacheNotAvailableException($localCache, $distributedCache): void { - $this->expectException(\OCP\HintException::class); + $this->expectException(HintException::class); $logger = $this->getMockBuilder(LoggerInterface::class)->getMock(); $profiler = $this->getMockBuilder(IProfiler::class)->getMock(); - new \OC\Memcache\Factory(fn () => 'abc', $logger, $profiler, $localCache, $distributedCache); + new Factory(fn () => 'abc', $logger, $profiler, $localCache, $distributedCache); } public function testCreateInMemory(): void { $logger = $this->getMockBuilder(LoggerInterface::class)->getMock(); $profiler = $this->getMockBuilder(IProfiler::class)->getMock(); - $factory = new \OC\Memcache\Factory(fn () => 'abc', $logger, $profiler, null, null, null); + $factory = new Factory(fn () => 'abc', $logger, $profiler, null, null, null); $cache = $factory->createInMemory(); $cache->set('test', 48); diff --git a/tests/lib/Memcache/MemcachedTest.php b/tests/lib/Memcache/MemcachedTest.php index 346530e191d..61e2f42e3d6 100644 --- a/tests/lib/Memcache/MemcachedTest.php +++ b/tests/lib/Memcache/MemcachedTest.php @@ -8,6 +8,8 @@ namespace Test\Memcache; +use OC\Memcache\Memcached; + /** * @group Memcache * @group Memcached @@ -16,10 +18,10 @@ class MemcachedTest extends Cache { public static function setUpBeforeClass(): void { parent::setUpBeforeClass(); - if (!\OC\Memcache\Memcached::isAvailable()) { + if (!Memcached::isAvailable()) { self::markTestSkipped('The memcached extension is not available.'); } - $instance = new \OC\Memcache\Memcached(self::getUniqueID()); + $instance = new Memcached(self::getUniqueID()); if ($instance->set(self::getUniqueID(), self::getUniqueID()) === false) { self::markTestSkipped('memcached server seems to be down.'); } @@ -27,7 +29,7 @@ class MemcachedTest extends Cache { protected function setUp(): void { parent::setUp(); - $this->instance = new \OC\Memcache\Memcached($this->getUniqueID()); + $this->instance = new Memcached($this->getUniqueID()); } public function testClear(): void { diff --git a/tests/lib/Memcache/RedisTest.php b/tests/lib/Memcache/RedisTest.php index d76da03eb85..c1dcc954925 100644 --- a/tests/lib/Memcache/RedisTest.php +++ b/tests/lib/Memcache/RedisTest.php @@ -9,6 +9,8 @@ namespace Test\Memcache; use OC\Memcache\Redis; +use OCP\IConfig; +use OCP\Server; /** * @group Memcache @@ -23,24 +25,24 @@ class RedisTest extends Cache { public static function setUpBeforeClass(): void { parent::setUpBeforeClass(); - if (!\OC\Memcache\Redis::isAvailable()) { + if (!Redis::isAvailable()) { self::markTestSkipped('The redis extension is not available.'); } - if (\OC::$server->getConfig()->getSystemValue('redis', []) === []) { + if (Server::get(IConfig::class)->getSystemValue('redis', []) === []) { self::markTestSkipped('Redis not configured in config.php'); } $errorOccurred = false; set_error_handler( - function ($errno, $errstr) { + function ($errno, $errstr): void { throw new \RuntimeException($errstr, 123456789); }, E_WARNING ); $instance = null; try { - $instance = new \OC\Memcache\Redis(self::getUniqueID()); + $instance = new Redis(self::getUniqueID()); } catch (\RuntimeException $e) { $errorOccurred = $e->getCode() === 123456789 ? $e->getMessage() : false; } @@ -60,11 +62,11 @@ class RedisTest extends Cache { protected function setUp(): void { parent::setUp(); - $this->instance = new \OC\Memcache\Redis($this->getUniqueID()); + $this->instance = new Redis($this->getUniqueID()); } public function testScriptHashes(): void { - foreach (\OC\Memcache\Redis::LUA_SCRIPTS as $script) { + foreach (Redis::LUA_SCRIPTS as $script) { $this->assertEquals(sha1($script[0]), $script[1]); } } diff --git a/tests/lib/NaturalSortTest.php b/tests/lib/NaturalSortTest.php index 833e2f5e3be..dcf3da3d99a 100644 --- a/tests/lib/NaturalSortTest.php +++ b/tests/lib/NaturalSortTest.php @@ -7,6 +7,9 @@ namespace Test; +use OC\NaturalSort; +use OC\NaturalSort_DefaultCollator; + class NaturalSortTest extends \Test\TestCase { /** * @dataProvider naturalSortDataProvider @@ -16,7 +19,7 @@ class NaturalSortTest extends \Test\TestCase { $this->markTestSkipped('The intl module is not available, natural sorting might not work as expected.'); return; } - $comparator = \OC\NaturalSort::getInstance(); + $comparator = NaturalSort::getInstance(); usort($array, [$comparator, 'compare']); $this->assertEquals($sorted, $array); } @@ -25,7 +28,7 @@ class NaturalSortTest extends \Test\TestCase { * @dataProvider defaultCollatorDataProvider */ public function testDefaultCollatorCompare($array, $sorted): void { - $comparator = new \OC\NaturalSort(new \OC\NaturalSort_DefaultCollator()); + $comparator = new NaturalSort(new NaturalSort_DefaultCollator()); usort($array, [$comparator, 'compare']); $this->assertEquals($sorted, $array); } diff --git a/tests/lib/NavigationManagerTest.php b/tests/lib/NavigationManagerTest.php index 986d2183a14..9ec1081bd97 100644 --- a/tests/lib/NavigationManagerTest.php +++ b/tests/lib/NavigationManagerTest.php @@ -20,6 +20,7 @@ use OCP\IUser; use OCP\IUserSession; use OCP\L10N\IFactory; use OCP\Navigation\Events\LoadAdditionalEntriesEvent; +use OCP\Util; use PHPUnit\Framework\MockObject\MockObject; use Psr\Log\LoggerInterface; @@ -265,7 +266,7 @@ class NavigationManagerTest extends TestCase { $this->navigationManager->clear(); $this->dispatcher->expects($this->once()) ->method('dispatchTyped') - ->willReturnCallback(function ($event) { + ->willReturnCallback(function ($event): void { $this->assertInstanceOf(LoadAdditionalEntriesEvent::class, $event); }); $entries = $this->navigationManager->getAll('all'); @@ -323,7 +324,7 @@ class NavigationManagerTest extends TestCase { 'logout' => [ 'id' => 'logout', 'order' => 99999, - 'href' => 'https://example.com/logout?requesttoken=' . urlencode(\OCP\Util::callRegister()), + 'href' => 'https://example.com/logout?requesttoken=' . urlencode(Util::callRegister()), 'icon' => '/apps/core/img/actions/logout.svg', 'name' => 'Log out', 'active' => false, @@ -572,7 +573,7 @@ class NavigationManagerTest extends TestCase { $this->navigationManager->clear(); $this->dispatcher->expects($this->once()) ->method('dispatchTyped') - ->willReturnCallback(function ($event) { + ->willReturnCallback(function ($event): void { $this->assertInstanceOf(LoadAdditionalEntriesEvent::class, $event); }); $entries = $this->navigationManager->getAll(); diff --git a/tests/lib/OCS/ProviderTest.php b/tests/lib/OCS/ProviderTest.php index ce028ce764a..ca7ba254ab9 100644 --- a/tests/lib/OCS/ProviderTest.php +++ b/tests/lib/OCS/ProviderTest.php @@ -8,6 +8,7 @@ namespace Test\OCS; use OC\OCS\Provider; +use OCP\AppFramework\Http\JSONResponse; class ProviderTest extends \Test\TestCase { /** @var \OCP\IRequest */ @@ -36,7 +37,7 @@ class ProviderTest extends \Test\TestCase { ['provisioning_api', null, false], ]); - $expected = new \OCP\AppFramework\Http\JSONResponse( + $expected = new JSONResponse( [ 'version' => 2, 'services' => [ @@ -66,7 +67,7 @@ class ProviderTest extends \Test\TestCase { ['provisioning_api', null, false], ]); - $expected = new \OCP\AppFramework\Http\JSONResponse( + $expected = new JSONResponse( [ 'version' => 2, 'services' => [ @@ -109,7 +110,7 @@ class ProviderTest extends \Test\TestCase { ['provisioning_api', null, false], ]); - $expected = new \OCP\AppFramework\Http\JSONResponse( + $expected = new JSONResponse( [ 'version' => 2, 'services' => [ @@ -142,7 +143,7 @@ class ProviderTest extends \Test\TestCase { ->method('isEnabledForUser') ->willReturn(true); - $expected = new \OCP\AppFramework\Http\JSONResponse( + $expected = new JSONResponse( [ 'version' => 2, 'services' => [ diff --git a/tests/lib/Preview/BackgroundCleanupJobTest.php b/tests/lib/Preview/BackgroundCleanupJobTest.php index cecb4a7a212..ab904f2b499 100644 --- a/tests/lib/Preview/BackgroundCleanupJobTest.php +++ b/tests/lib/Preview/BackgroundCleanupJobTest.php @@ -7,11 +7,14 @@ namespace Test\Preview; +use OC\Files\Storage\Temporary; use OC\Preview\BackgroundCleanupJob; use OC\Preview\Storage\Root; use OC\PreviewManager; +use OC\SystemConfig; use OCP\App\IAppManager; use OCP\AppFramework\Utility\ITimeFactory; +use OCP\Files\AppData\IAppDataFactory; use OCP\Files\File; use OCP\Files\IMimeTypeLoader; use OCP\Files\IRootFolder; @@ -46,7 +49,7 @@ class BackgroundCleanupJobTest extends \Test\TestCase { $this->userId = $this->getUniqueID(); $user = $this->createUser($this->userId, $this->userId); - $storage = new \OC\Files\Storage\Temporary([]); + $storage = new Temporary([]); $this->registerMount($this->userId, $storage, ''); $this->loginAsUser($this->userId); @@ -77,8 +80,8 @@ class BackgroundCleanupJobTest extends \Test\TestCase { private function getRoot(): Root { return new Root( - \OC::$server->get(IRootFolder::class), - \OC::$server->getSystemConfig() + Server::get(IRootFolder::class), + Server::get(SystemConfig::class) ); } @@ -173,7 +176,7 @@ class BackgroundCleanupJobTest extends \Test\TestCase { $this->markTestSkipped('old previews are not supported for sharded setups'); return; } - $appdata = \OC::$server->getAppDataDir('preview'); + $appdata = Server::get(IAppDataFactory::class)->get('preview'); $f1 = $appdata->newFolder('123456781'); $f1->newFile('foo.jpg', 'foo'); @@ -189,7 +192,7 @@ class BackgroundCleanupJobTest extends \Test\TestCase { $appdata->getFolder('/')->newFile('not-a-directory', 'foo'); $appdata->getFolder('/')->newFile('133742', 'bar'); - $appdata = \OC::$server->getAppDataDir('preview'); + $appdata = Server::get(IAppDataFactory::class)->get('preview'); // AppData::getDirectoryListing filters all non-folders $this->assertSame(3, count($appdata->getDirectoryListing())); try { @@ -206,7 +209,7 @@ class BackgroundCleanupJobTest extends \Test\TestCase { $job = new BackgroundCleanupJob($this->timeFactory, $this->connection, $this->getRoot(), $this->mimeTypeLoader, true); $job->run([]); - $appdata = \OC::$server->getAppDataDir('preview'); + $appdata = Server::get(IAppDataFactory::class)->get('preview'); // Check if the files created above are still present // Remember: AppData::getDirectoryListing filters all non-folders diff --git a/tests/lib/Preview/BitmapTest.php b/tests/lib/Preview/BitmapTest.php index c4f3f8d3cf5..f442ae73b2e 100644 --- a/tests/lib/Preview/BitmapTest.php +++ b/tests/lib/Preview/BitmapTest.php @@ -7,6 +7,8 @@ namespace Test\Preview; +use OC\Preview\Postscript; + /** * Class BitmapTest * @@ -22,6 +24,6 @@ class BitmapTest extends Provider { $this->imgPath = $this->prepareTestFile($fileName, \OC::$SERVERROOT . '/tests/data/' . $fileName); $this->width = 2400; $this->height = 1707; - $this->provider = new \OC\Preview\Postscript; + $this->provider = new Postscript; } } diff --git a/tests/lib/Preview/HEICTest.php b/tests/lib/Preview/HEICTest.php index 5df7b63dd03..61dede00e6b 100644 --- a/tests/lib/Preview/HEICTest.php +++ b/tests/lib/Preview/HEICTest.php @@ -6,6 +6,8 @@ namespace Test\Preview; +use OC\Preview\HEIC; + /** * Class BitmapTest * @@ -24,7 +26,7 @@ class HEICTest extends Provider { $this->imgPath = $this->prepareTestFile($fileName, \OC::$SERVERROOT . '/tests/data/' . $fileName); $this->width = 1680; $this->height = 1050; - $this->provider = new \OC\Preview\HEIC; + $this->provider = new HEIC; } } } diff --git a/tests/lib/Preview/ImageTest.php b/tests/lib/Preview/ImageTest.php index f4b8e7e1dd4..03f3403b1b3 100644 --- a/tests/lib/Preview/ImageTest.php +++ b/tests/lib/Preview/ImageTest.php @@ -7,6 +7,8 @@ namespace Test\Preview; +use OC\Preview\JPEG; + /** * Class ImageTest * @@ -22,6 +24,6 @@ class ImageTest extends Provider { $this->imgPath = $this->prepareTestFile($fileName, \OC::$SERVERROOT . '/tests/data/' . $fileName); $this->width = 1680; $this->height = 1050; - $this->provider = new \OC\Preview\JPEG(); + $this->provider = new JPEG(); } } diff --git a/tests/lib/Preview/MP3Test.php b/tests/lib/Preview/MP3Test.php index 6f40b862b7b..3f1c9aff61c 100644 --- a/tests/lib/Preview/MP3Test.php +++ b/tests/lib/Preview/MP3Test.php @@ -7,6 +7,8 @@ namespace Test\Preview; +use OC\Preview\MP3; + /** * Class MP3Test * @@ -22,6 +24,6 @@ class MP3Test extends Provider { $this->imgPath = $this->prepareTestFile($fileName, \OC::$SERVERROOT . '/tests/data/' . $fileName); $this->width = 200; $this->height = 200; - $this->provider = new \OC\Preview\MP3; + $this->provider = new MP3; } } diff --git a/tests/lib/Preview/MovieTest.php b/tests/lib/Preview/MovieTest.php index 6009943b89d..de7ff45988c 100644 --- a/tests/lib/Preview/MovieTest.php +++ b/tests/lib/Preview/MovieTest.php @@ -7,6 +7,7 @@ namespace Test\Preview; +use OC\Preview\Movie; use OCP\IBinaryFinder; use OCP\Server; @@ -33,7 +34,7 @@ class MovieTest extends Provider { parent::setUp(); $this->imgPath = $this->prepareTestFile($this->fileName, \OC::$SERVERROOT . '/tests/data/' . $this->fileName); - $this->provider = new \OC\Preview\Movie(['movieBinary' => $movieBinary]); + $this->provider = new Movie(['movieBinary' => $movieBinary]); } else { $this->markTestSkipped('No Movie provider present'); } diff --git a/tests/lib/Preview/OfficeTest.php b/tests/lib/Preview/OfficeTest.php index 167c442dd34..471ff0d2367 100644 --- a/tests/lib/Preview/OfficeTest.php +++ b/tests/lib/Preview/OfficeTest.php @@ -7,6 +7,7 @@ namespace Test\Preview; +use OC\Preview\OpenDocument; use OCP\IBinaryFinder; use OCP\Server; @@ -30,7 +31,7 @@ class OfficeTest extends Provider { $this->imgPath = $this->prepareTestFile($fileName, \OC::$SERVERROOT . '/tests/data/' . $fileName); $this->width = 595; $this->height = 842; - $this->provider = new \OC\Preview\OpenDocument; + $this->provider = new OpenDocument; } else { $this->markTestSkipped('No Office provider present'); } diff --git a/tests/lib/Preview/Provider.php b/tests/lib/Preview/Provider.php index a7f55151354..daa069483fd 100644 --- a/tests/lib/Preview/Provider.php +++ b/tests/lib/Preview/Provider.php @@ -8,9 +8,15 @@ namespace Test\Preview; +use OC\Files\Filesystem; use OC\Files\Node\File; +use OC\Files\Storage\Storage; +use OC\Files\Storage\Temporary; +use OC\Files\View; +use OC\Preview\TXT; use OCP\Files\IRootFolder; use OCP\IUserManager; +use OCP\Server; abstract class Provider extends \Test\TestCase { protected string $imgPath; @@ -22,13 +28,13 @@ abstract class Provider extends \Test\TestCase { protected int $maxHeight = 1024; protected bool $scalingUp = false; protected string $userId; - protected \OC\Files\View $rootView; - protected \OC\Files\Storage\Storage $storage; + protected View $rootView; + protected Storage $storage; protected function setUp(): void { parent::setUp(); - $userManager = \OCP\Server::get(IUserManager::class); + $userManager = Server::get(IUserManager::class); $userManager->clearBackends(); $backend = new \Test\Util\User\Dummy(); $userManager->registerBackend($backend); @@ -37,10 +43,10 @@ abstract class Provider extends \Test\TestCase { $backend->createUser($userId, $userId); $this->loginAsUser($userId); - $this->storage = new \OC\Files\Storage\Temporary([]); - \OC\Files\Filesystem::mount($this->storage, [], '/' . $userId . '/'); + $this->storage = new Temporary([]); + Filesystem::mount($this->storage, [], '/' . $userId . '/'); - $this->rootView = new \OC\Files\View(''); + $this->rootView = new View(''); $this->rootView->mkdir('/' . $userId); $this->rootView->mkdir('/' . $userId . '/files'); @@ -84,7 +90,7 @@ abstract class Provider extends \Test\TestCase { $preview = $this->getPreview($this->provider); // The TXT provider uses the max dimensions to create its canvas, // so the ratio will always be the one of the max dimension canvas - if (!$this->provider instanceof \OC\Preview\TXT) { + if (!$this->provider instanceof TXT) { $this->doesRatioMatch($preview, $ratio); } $this->doesPreviewFit($preview); @@ -117,7 +123,7 @@ abstract class Provider extends \Test\TestCase { * @return bool|\OCP\IImage */ private function getPreview($provider) { - $file = new File(\OC::$server->get(IRootFolder::class), $this->rootView, $this->imgPath); + $file = new File(Server::get(IRootFolder::class), $this->rootView, $this->imgPath); $preview = $provider->getThumbnail($file, $this->maxWidth, $this->maxHeight, $this->scalingUp); if (get_class($this) === BitmapTest::class && $preview === null) { diff --git a/tests/lib/Preview/SVGTest.php b/tests/lib/Preview/SVGTest.php index 14730bc8034..418ac33c3d6 100644 --- a/tests/lib/Preview/SVGTest.php +++ b/tests/lib/Preview/SVGTest.php @@ -7,6 +7,9 @@ namespace Test\Preview; +use OC\Preview\SVG; +use OCP\Files\File; + /** * Class SVGTest * @@ -24,7 +27,7 @@ class SVGTest extends Provider { $this->imgPath = $this->prepareTestFile($fileName, \OC::$SERVERROOT . '/tests/data/' . $fileName); $this->width = 3000; $this->height = 2000; - $this->provider = new \OC\Preview\SVG; + $this->provider = new SVG; } else { $this->markTestSkipped('No SVG provider present'); } @@ -52,7 +55,7 @@ class SVGTest extends Provider { </svg>'); rewind($handle); - $file = $this->createMock(\OCP\Files\File::class); + $file = $this->createMock(File::class); $file->method('fopen') ->willReturn($handle); diff --git a/tests/lib/Preview/TXTTest.php b/tests/lib/Preview/TXTTest.php index 7f5510eb60f..9541ec8f31c 100644 --- a/tests/lib/Preview/TXTTest.php +++ b/tests/lib/Preview/TXTTest.php @@ -7,6 +7,8 @@ namespace Test\Preview; +use OC\Preview\TXT; + /** * Class TXTTest * @@ -23,6 +25,6 @@ class TXTTest extends Provider { // Arbitrary width and length which won't be used to calculate the ratio $this->width = 500; $this->height = 200; - $this->provider = new \OC\Preview\TXT; + $this->provider = new TXT; } } diff --git a/tests/lib/Remote/Api/OCSTest.php b/tests/lib/Remote/Api/OCSTest.php index 3fcc486f246..142cb98c5e0 100644 --- a/tests/lib/Remote/Api/OCSTest.php +++ b/tests/lib/Remote/Api/OCSTest.php @@ -6,6 +6,7 @@ namespace Test\Remote\Api; +use OC\ForbiddenException; use OC\Memcache\ArrayCache; use OC\Remote\Api\OCS; use OC\Remote\Credentials; @@ -68,7 +69,7 @@ class OCSTest extends TestCase { public function testInvalidPassword(): void { - $this->expectException(\OC\ForbiddenException::class); + $this->expectException(ForbiddenException::class); $client = $this->getOCSClient(); diff --git a/tests/lib/Repair/CleanTagsTest.php b/tests/lib/Repair/CleanTagsTest.php index adb14b16fc4..5964fdb7f63 100644 --- a/tests/lib/Repair/CleanTagsTest.php +++ b/tests/lib/Repair/CleanTagsTest.php @@ -7,10 +7,12 @@ namespace Test\Repair; +use OC\Repair\CleanTags; use OCP\DB\QueryBuilder\IQueryBuilder; use OCP\IDBConnection; use OCP\IUserManager; use OCP\Migration\IOutput; +use OCP\Server; use PHPUnit\Framework\MockObject\MockObject; /** @@ -23,7 +25,7 @@ use PHPUnit\Framework\MockObject\MockObject; class CleanTagsTest extends \Test\TestCase { private ?int $createdFile = null; - private \OC\Repair\CleanTags $repair; + private CleanTags $repair; private IDBConnection $connection; private IUserManager&MockObject $userManager; @@ -40,8 +42,8 @@ class CleanTagsTest extends \Test\TestCase { ->disableOriginalConstructor() ->getMock(); - $this->connection = \OCP\Server::get(IDBConnection::class); - $this->repair = new \OC\Repair\CleanTags($this->connection, $this->userManager); + $this->connection = Server::get(IDBConnection::class); + $this->repair = new CleanTags($this->connection, $this->userManager); $this->cleanUpTables(); } diff --git a/tests/lib/Repair/ClearFrontendCachesTest.php b/tests/lib/Repair/ClearFrontendCachesTest.php index 2e4681c6e5d..4586ecd5ae9 100644 --- a/tests/lib/Repair/ClearFrontendCachesTest.php +++ b/tests/lib/Repair/ClearFrontendCachesTest.php @@ -6,6 +6,7 @@ namespace Test\Repair; +use OC\Repair\ClearFrontendCaches; use OC\Template\JSCombiner; use OCP\ICache; use OCP\ICacheFactory; @@ -18,7 +19,7 @@ class ClearFrontendCachesTest extends \Test\TestCase { private JSCombiner&MockObject $jsCombiner; private IOutput&MockObject $outputMock; - protected \OC\Repair\ClearFrontendCaches $repair; + protected ClearFrontendCaches $repair; protected function setUp(): void { parent::setUp(); @@ -28,7 +29,7 @@ class ClearFrontendCachesTest extends \Test\TestCase { $this->cacheFactory = $this->createMock(ICacheFactory::class); $this->jsCombiner = $this->createMock(JSCombiner::class); - $this->repair = new \OC\Repair\ClearFrontendCaches($this->cacheFactory, $this->jsCombiner); + $this->repair = new ClearFrontendCaches($this->cacheFactory, $this->jsCombiner); } diff --git a/tests/lib/Repair/NC29/SanitizeAccountPropertiesJobTest.php b/tests/lib/Repair/NC29/SanitizeAccountPropertiesJobTest.php index e0f4eb3cbc1..c81cf21226c 100644 --- a/tests/lib/Repair/NC29/SanitizeAccountPropertiesJobTest.php +++ b/tests/lib/Repair/NC29/SanitizeAccountPropertiesJobTest.php @@ -104,7 +104,7 @@ class SanitizeAccountPropertiesJobTest extends TestCase { $valid = false; $this->accountManager->expects(self::exactly(3)) ->method('updateAccount') - ->willReturnCallback(function (IAccount $account) use (&$account1, &$valid) { + ->willReturnCallback(function (IAccount $account) use (&$account1, &$valid): void { if (!$valid && $account === $account1) { $valid = true; throw new InvalidArgumentException(IAccountManager::PROPERTY_PHONE); diff --git a/tests/lib/Repair/OldGroupMembershipSharesTest.php b/tests/lib/Repair/OldGroupMembershipSharesTest.php index 594a8bf0b66..b78f4c567b4 100644 --- a/tests/lib/Repair/OldGroupMembershipSharesTest.php +++ b/tests/lib/Repair/OldGroupMembershipSharesTest.php @@ -11,6 +11,7 @@ use OC\Repair\OldGroupMembershipShares; use OCP\IDBConnection; use OCP\IGroupManager; use OCP\Migration\IOutput; +use OCP\Server; use OCP\Share\IShare; use PHPUnit\Framework\MockObject\MockObject; @@ -32,7 +33,7 @@ class OldGroupMembershipSharesTest extends \Test\TestCase { $this->groupManager = $this->getMockBuilder(IGroupManager::class) ->disableOriginalConstructor() ->getMock(); - $this->connection = \OCP\Server::get(IDBConnection::class); + $this->connection = Server::get(IDBConnection::class); $this->deleteAllShares(); } diff --git a/tests/lib/Repair/Owncloud/CleanPreviewsBackgroundJobTest.php b/tests/lib/Repair/Owncloud/CleanPreviewsBackgroundJobTest.php index 3c5583c49da..7a60bdd18ea 100644 --- a/tests/lib/Repair/Owncloud/CleanPreviewsBackgroundJobTest.php +++ b/tests/lib/Repair/Owncloud/CleanPreviewsBackgroundJobTest.php @@ -71,8 +71,7 @@ class CleanPreviewsBackgroundJobTest extends TestCase { $thumbnailFolder->expects($this->never()) ->method('delete'); - $this->timeFactory->method('getTime') - ->will($this->onConsecutiveCalls(100, 200)); + $this->timeFactory->method('getTime')->willReturnOnConsecutiveCalls(100, 200); $this->jobList->expects($this->once()) ->method('add') @@ -84,7 +83,7 @@ class CleanPreviewsBackgroundJobTest extends TestCase { $loggerCalls = []; $this->logger->expects($this->exactly(2)) ->method('info') - ->willReturnCallback(function () use (&$loggerCalls) { + ->willReturnCallback(function () use (&$loggerCalls): void { $loggerCalls[] = func_get_args(); }); @@ -118,8 +117,7 @@ class CleanPreviewsBackgroundJobTest extends TestCase { $thumbnailFolder->method('getDirectoryListing') ->willReturn([$previewFolder1]); - $this->timeFactory->method('getTime') - ->will($this->onConsecutiveCalls(100, 101)); + $this->timeFactory->method('getTime')->willReturnOnConsecutiveCalls(100, 101); $this->jobList->expects($this->never()) ->method('add'); @@ -127,7 +125,7 @@ class CleanPreviewsBackgroundJobTest extends TestCase { $loggerCalls = []; $this->logger->expects($this->exactly(2)) ->method('info') - ->willReturnCallback(function () use (&$loggerCalls) { + ->willReturnCallback(function () use (&$loggerCalls): void { $loggerCalls[] = func_get_args(); }); @@ -150,7 +148,7 @@ class CleanPreviewsBackgroundJobTest extends TestCase { $loggerCalls = []; $this->logger->expects($this->exactly(2)) ->method('info') - ->willReturnCallback(function () use (&$loggerCalls) { + ->willReturnCallback(function () use (&$loggerCalls): void { $loggerCalls[] = func_get_args(); }); @@ -178,7 +176,7 @@ class CleanPreviewsBackgroundJobTest extends TestCase { $loggerCalls = []; $this->logger->expects($this->exactly(2)) ->method('info') - ->willReturnCallback(function () use (&$loggerCalls) { + ->willReturnCallback(function () use (&$loggerCalls): void { $loggerCalls[] = func_get_args(); }); @@ -213,8 +211,7 @@ class CleanPreviewsBackgroundJobTest extends TestCase { $thumbnailFolder->method('getDirectoryListing') ->willReturn([$previewFolder1]); - $this->timeFactory->method('getTime') - ->will($this->onConsecutiveCalls(100, 101)); + $this->timeFactory->method('getTime')->willReturnOnConsecutiveCalls(100, 101); $this->jobList->expects($this->never()) ->method('add'); @@ -226,7 +223,7 @@ class CleanPreviewsBackgroundJobTest extends TestCase { $loggerCalls = []; $this->logger->expects($this->exactly(2)) ->method('info') - ->willReturnCallback(function () use (&$loggerCalls) { + ->willReturnCallback(function () use (&$loggerCalls): void { $loggerCalls[] = func_get_args(); }); diff --git a/tests/lib/Repair/Owncloud/CleanPreviewsTest.php b/tests/lib/Repair/Owncloud/CleanPreviewsTest.php index 3a1936076a0..c0ea6f5bc1f 100644 --- a/tests/lib/Repair/Owncloud/CleanPreviewsTest.php +++ b/tests/lib/Repair/Owncloud/CleanPreviewsTest.php @@ -52,15 +52,15 @@ class CleanPreviewsTest extends TestCase { $this->userManager->expects($this->once()) ->method('callForSeenUsers') - ->will($this->returnCallback(function (\Closure $function) use (&$user1, $user2) { + ->willReturnCallback(function (\Closure $function) use (&$user1, $user2): void { $function($user1); $function($user2); - })); + }); $jobListCalls = []; $this->jobList->expects($this->exactly(2)) ->method('add') - ->willReturnCallback(function () use (&$jobListCalls) { + ->willReturnCallback(function () use (&$jobListCalls): void { $jobListCalls[] = func_get_args(); }); diff --git a/tests/lib/Repair/Owncloud/UpdateLanguageCodesTest.php b/tests/lib/Repair/Owncloud/UpdateLanguageCodesTest.php index a7907308d93..e2967dfd601 100644 --- a/tests/lib/Repair/Owncloud/UpdateLanguageCodesTest.php +++ b/tests/lib/Repair/Owncloud/UpdateLanguageCodesTest.php @@ -11,6 +11,7 @@ use OCP\DB\QueryBuilder\IQueryBuilder; use OCP\IConfig; use OCP\IDBConnection; use OCP\Migration\IOutput; +use OCP\Server; use PHPUnit\Framework\MockObject\MockObject; use Test\TestCase; @@ -29,7 +30,7 @@ class UpdateLanguageCodesTest extends TestCase { protected function setUp(): void { parent::setUp(); - $this->connection = \OCP\Server::get(IDBConnection::class); + $this->connection = Server::get(IDBConnection::class); $this->config = $this->createMock(IConfig::class); } @@ -91,7 +92,7 @@ class UpdateLanguageCodesTest extends TestCase { $outputMock = $this->createMock(IOutput::class); $outputMock->expects($this->exactly(7)) ->method('info') - ->willReturnCallback(function () use (&$outputMessages) { + ->willReturnCallback(function () use (&$outputMessages): void { $outputMessages[] = func_get_args(); }); diff --git a/tests/lib/Repair/RepairCollationTest.php b/tests/lib/Repair/RepairCollationTest.php index 3f007fa6310..e0cf5a8bb6f 100644 --- a/tests/lib/Repair/RepairCollationTest.php +++ b/tests/lib/Repair/RepairCollationTest.php @@ -12,6 +12,7 @@ use OC\Repair\Collation; use OCP\IConfig; use OCP\IDBConnection; use OCP\Migration\IOutput; +use OCP\Server; use PHPUnit\Framework\MockObject\MockObject; use Psr\Log\LoggerInterface; use Test\TestCase; @@ -45,8 +46,8 @@ class RepairCollationTest extends TestCase { protected function setUp(): void { parent::setUp(); - $this->connection = \OCP\Server::get(ConnectionAdapter::class); - $this->config = \OCP\Server::get(IConfig::class); + $this->connection = Server::get(ConnectionAdapter::class); + $this->config = Server::get(IConfig::class); if ($this->connection->getDatabaseProvider() !== IDBConnection::PLATFORM_MYSQL) { $this->markTestSkipped('Test only relevant on MySql'); } diff --git a/tests/lib/Repair/RepairInvalidSharesTest.php b/tests/lib/Repair/RepairInvalidSharesTest.php index 7c49d74e2ef..f987d35f5c0 100644 --- a/tests/lib/Repair/RepairInvalidSharesTest.php +++ b/tests/lib/Repair/RepairInvalidSharesTest.php @@ -8,9 +8,11 @@ namespace Test\Repair; use OC\Repair\RepairInvalidShares; +use OCP\Constants; use OCP\IConfig; use OCP\IDBConnection; use OCP\Migration\IOutput; +use OCP\Server; use OCP\Share\IShare; use Test\TestCase; @@ -37,7 +39,7 @@ class RepairInvalidSharesTest extends TestCase { ->with('version') ->willReturn('12.0.0.0'); - $this->connection = \OCP\Server::get(IDBConnection::class); + $this->connection = Server::get(IDBConnection::class); $this->deleteAllShares(); $this->repair = new RepairInvalidShares($config, $this->connection); @@ -133,14 +135,14 @@ class RepairInvalidSharesTest extends TestCase { // unchanged for read-write + share [ 'file', - \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_SHARE, - \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_SHARE, + Constants::PERMISSION_READ | Constants::PERMISSION_UPDATE | Constants::PERMISSION_SHARE, + Constants::PERMISSION_READ | Constants::PERMISSION_UPDATE | Constants::PERMISSION_SHARE, ], // fixed for all perms [ 'file', - \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE | \OCP\Constants::PERMISSION_SHARE, - \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_SHARE, + Constants::PERMISSION_READ | Constants::PERMISSION_CREATE | Constants::PERMISSION_UPDATE | Constants::PERMISSION_DELETE | Constants::PERMISSION_SHARE, + Constants::PERMISSION_READ | Constants::PERMISSION_UPDATE | Constants::PERMISSION_SHARE, ], ]; } diff --git a/tests/lib/Repair/RepairMimeTypesTest.php b/tests/lib/Repair/RepairMimeTypesTest.php index 4f044c054d3..e4645b3be4c 100644 --- a/tests/lib/Repair/RepairMimeTypesTest.php +++ b/tests/lib/Repair/RepairMimeTypesTest.php @@ -14,6 +14,7 @@ use OCP\IAppConfig; use OCP\IConfig; use OCP\IDBConnection; use OCP\Migration\IOutput; +use OCP\Server; /** * Tests for the converting of legacy storages to home storages. @@ -32,8 +33,8 @@ class RepairMimeTypesTest extends \Test\TestCase { protected function setUp(): void { parent::setUp(); - $this->mimetypeLoader = \OCP\Server::get(IMimeTypeLoader::class); - $this->db = \OCP\Server::get(IDBConnection::class); + $this->mimetypeLoader = Server::get(IMimeTypeLoader::class); + $this->db = Server::get(IDBConnection::class); $config = $this->getMockBuilder(IConfig::class) ->disableOriginalConstructor() @@ -55,7 +56,7 @@ class RepairMimeTypesTest extends \Test\TestCase { $this->repair = new RepairMimeTypes( $config, $appConfig, - \OCP\Server::get(IDBConnection::class), + Server::get(IDBConnection::class), ); } diff --git a/tests/lib/RepairTest.php b/tests/lib/RepairTest.php index 97c278a1d10..f567aebf3c8 100644 --- a/tests/lib/RepairTest.php +++ b/tests/lib/RepairTest.php @@ -13,21 +13,22 @@ use OC\Repair\Events\RepairInfoEvent; use OC\Repair\Events\RepairStepEvent; use OC\Repair\Events\RepairWarningEvent; use OCP\EventDispatcher\IEventDispatcher; +use OCP\Migration\IOutput; use OCP\Migration\IRepairStep; +use OCP\Server; use Psr\Log\LoggerInterface; class TestRepairStep implements IRepairStep { - private bool $warning; - - public function __construct(bool $warning = false) { - $this->warning = $warning; + public function __construct( + private bool $warning = false, + ) { } public function getName() { return 'Test Name'; } - public function run(\OCP\Migration\IOutput $out) { + public function run(IOutput $out) { if ($this->warning) { $out->warning('Simulated warning'); } else { @@ -44,19 +45,19 @@ class RepairTest extends TestCase { protected function setUp(): void { parent::setUp(); - $dispatcher = \OC::$server->get(IEventDispatcher::class); + $dispatcher = Server::get(IEventDispatcher::class); $this->repair = new Repair($dispatcher, $this->createMock(LoggerInterface::class)); - $dispatcher->addListener(RepairWarningEvent::class, function (RepairWarningEvent $event) { + $dispatcher->addListener(RepairWarningEvent::class, function (RepairWarningEvent $event): void { $this->outputArray[] = 'warning: ' . $event->getMessage(); }); - $dispatcher->addListener(RepairInfoEvent::class, function (RepairInfoEvent $event) { + $dispatcher->addListener(RepairInfoEvent::class, function (RepairInfoEvent $event): void { $this->outputArray[] = 'info: ' . $event->getMessage(); }); - $dispatcher->addListener(RepairStepEvent::class, function (RepairStepEvent $event) { + $dispatcher->addListener(RepairStepEvent::class, function (RepairStepEvent $event): void { $this->outputArray[] = 'step: ' . $event->getStepName(); }); - $dispatcher->addListener(RepairErrorEvent::class, function (RepairErrorEvent $event) { + $dispatcher->addListener(RepairErrorEvent::class, function (RepairErrorEvent $event): void { $this->outputArray[] = 'error: ' . $event->getMessage(); }); } @@ -91,7 +92,7 @@ class RepairTest extends TestCase { $mock = $this->createMock(TestRepairStep::class); $mock->expects($this->any()) ->method('run') - ->will($this->throwException(new \Exception('Exception text'))); + ->willThrowException(new \Exception('Exception text')); $mock->expects($this->any()) ->method('getName') ->willReturn('Exception Test'); diff --git a/tests/lib/RichObjectStrings/DefinitionsTest.php b/tests/lib/RichObjectStrings/DefinitionsTest.php index cc964aff50f..5106de50ba4 100644 --- a/tests/lib/RichObjectStrings/DefinitionsTest.php +++ b/tests/lib/RichObjectStrings/DefinitionsTest.php @@ -7,6 +7,7 @@ namespace Test\RichObjectStrings; use OCP\RichObjectStrings\Definitions; +use OCP\RichObjectStrings\InvalidObjectExeption; use Test\TestCase; class DefinitionsTest extends TestCase { @@ -21,7 +22,7 @@ class DefinitionsTest extends TestCase { public function testGetDefinitionNotExisting(): void { - $this->expectException(\OCP\RichObjectStrings\InvalidObjectExeption::class); + $this->expectException(InvalidObjectExeption::class); $this->expectExceptionMessage('Object type is undefined'); $definitions = new Definitions(); diff --git a/tests/lib/Route/RouterTest.php b/tests/lib/Route/RouterTest.php index f99ebe4767f..560cd5d3aed 100644 --- a/tests/lib/Route/RouterTest.php +++ b/tests/lib/Route/RouterTest.php @@ -35,7 +35,7 @@ class RouterTest extends TestCase { $logger = $this->createMock(LoggerInterface::class); $logger->method('info') ->willReturnCallback( - function (string $message, array $data) { + function (string $message, array $data): void { $this->fail('Unexpected info log: ' . (string)($data['exception'] ?? $message)); } ); diff --git a/tests/lib/Security/CSP/ContentSecurityPolicyManagerTest.php b/tests/lib/Security/CSP/ContentSecurityPolicyManagerTest.php index 63a5565e7fa..a32a4132287 100644 --- a/tests/lib/Security/CSP/ContentSecurityPolicyManagerTest.php +++ b/tests/lib/Security/CSP/ContentSecurityPolicyManagerTest.php @@ -11,8 +11,11 @@ declare(strict_types=1); namespace Test\Security\CSP; use OC\Security\CSP\ContentSecurityPolicyManager; +use OCP\AppFramework\Http\ContentSecurityPolicy; +use OCP\AppFramework\Http\EmptyContentSecurityPolicy; use OCP\EventDispatcher\IEventDispatcher; use OCP\Security\CSP\AddContentSecurityPolicyEvent; +use OCP\Server; use Test\TestCase; class ContentSecurityPolicyManagerTest extends TestCase { @@ -24,26 +27,26 @@ class ContentSecurityPolicyManagerTest extends TestCase { protected function setUp(): void { parent::setUp(); - $this->dispatcher = \OC::$server->query(IEventDispatcher::class); + $this->dispatcher = Server::get(IEventDispatcher::class); $this->contentSecurityPolicyManager = new ContentSecurityPolicyManager($this->dispatcher); } public function testAddDefaultPolicy(): void { - $this->contentSecurityPolicyManager->addDefaultPolicy(new \OCP\AppFramework\Http\ContentSecurityPolicy()); + $this->contentSecurityPolicyManager->addDefaultPolicy(new ContentSecurityPolicy()); $this->addToAssertionCount(1); } public function testGetDefaultPolicyWithPolicies(): void { - $policy = new \OCP\AppFramework\Http\ContentSecurityPolicy(); + $policy = new ContentSecurityPolicy(); $policy->addAllowedFontDomain('mydomain.com'); $policy->addAllowedImageDomain('anotherdomain.de'); $this->contentSecurityPolicyManager->addDefaultPolicy($policy); - $policy = new \OCP\AppFramework\Http\ContentSecurityPolicy(); + $policy = new ContentSecurityPolicy(); $policy->addAllowedFontDomain('example.com'); $policy->addAllowedImageDomain('example.org'); $policy->allowEvalScript(true); $this->contentSecurityPolicyManager->addDefaultPolicy($policy); - $policy = new \OCP\AppFramework\Http\EmptyContentSecurityPolicy(); + $policy = new EmptyContentSecurityPolicy(); $policy->addAllowedChildSrcDomain('childdomain'); $policy->addAllowedFontDomain('anotherFontDomain'); $policy->addAllowedFormActionDomain('thirdDomain'); @@ -65,8 +68,8 @@ class ContentSecurityPolicyManagerTest extends TestCase { } public function testGetDefaultPolicyWithPoliciesViaEvent(): void { - $this->dispatcher->addListener(AddContentSecurityPolicyEvent::class, function (AddContentSecurityPolicyEvent $e) { - $policy = new \OCP\AppFramework\Http\ContentSecurityPolicy(); + $this->dispatcher->addListener(AddContentSecurityPolicyEvent::class, function (AddContentSecurityPolicyEvent $e): void { + $policy = new ContentSecurityPolicy(); $policy->addAllowedFontDomain('mydomain.com'); $policy->addAllowedImageDomain('anotherdomain.de'); $policy->useStrictDynamic(true); @@ -75,16 +78,16 @@ class ContentSecurityPolicyManagerTest extends TestCase { $e->addPolicy($policy); }); - $this->dispatcher->addListener(AddContentSecurityPolicyEvent::class, function (AddContentSecurityPolicyEvent $e) { - $policy = new \OCP\AppFramework\Http\ContentSecurityPolicy(); + $this->dispatcher->addListener(AddContentSecurityPolicyEvent::class, function (AddContentSecurityPolicyEvent $e): void { + $policy = new ContentSecurityPolicy(); $policy->addAllowedFontDomain('example.com'); $policy->addAllowedImageDomain('example.org'); $policy->allowEvalScript(false); $e->addPolicy($policy); }); - $this->dispatcher->addListener(AddContentSecurityPolicyEvent::class, function (AddContentSecurityPolicyEvent $e) { - $policy = new \OCP\AppFramework\Http\EmptyContentSecurityPolicy(); + $this->dispatcher->addListener(AddContentSecurityPolicyEvent::class, function (AddContentSecurityPolicyEvent $e): void { + $policy = new EmptyContentSecurityPolicy(); $policy->addAllowedChildSrcDomain('childdomain'); $policy->addAllowedFontDomain('anotherFontDomain'); $policy->addAllowedFormActionDomain('thirdDomain'); diff --git a/tests/lib/Security/CSRF/CsrfTokenGeneratorTest.php b/tests/lib/Security/CSRF/CsrfTokenGeneratorTest.php index 98eddf602ee..e40726fe56a 100644 --- a/tests/lib/Security/CSRF/CsrfTokenGeneratorTest.php +++ b/tests/lib/Security/CSRF/CsrfTokenGeneratorTest.php @@ -10,6 +10,8 @@ declare(strict_types=1); namespace Test\Security\CSRF; +use OC\Security\CSRF\CsrfTokenGenerator; + class CsrfTokenGeneratorTest extends \Test\TestCase { /** @var \OCP\Security\ISecureRandom */ private $random; @@ -20,7 +22,7 @@ class CsrfTokenGeneratorTest extends \Test\TestCase { parent::setUp(); $this->random = $this->getMockBuilder('\OCP\Security\ISecureRandom') ->disableOriginalConstructor()->getMock(); - $this->csrfTokenGenerator = new \OC\Security\CSRF\CsrfTokenGenerator($this->random); + $this->csrfTokenGenerator = new CsrfTokenGenerator($this->random); } public function testGenerateTokenWithCustomNumber(): void { diff --git a/tests/lib/Security/CSRF/CsrfTokenManagerTest.php b/tests/lib/Security/CSRF/CsrfTokenManagerTest.php index 47f873bfe13..66ee18475a4 100644 --- a/tests/lib/Security/CSRF/CsrfTokenManagerTest.php +++ b/tests/lib/Security/CSRF/CsrfTokenManagerTest.php @@ -10,6 +10,9 @@ declare(strict_types=1); namespace Test\Security\CSRF; +use OC\Security\CSRF\CsrfToken; +use OC\Security\CSRF\CsrfTokenManager; + class CsrfTokenManagerTest extends \Test\TestCase { /** @var \OC\Security\CSRF\CsrfTokenManager */ private $csrfTokenManager; @@ -25,7 +28,7 @@ class CsrfTokenManagerTest extends \Test\TestCase { $this->storageInterface = $this->getMockBuilder('\OC\Security\CSRF\TokenStorage\SessionStorage') ->disableOriginalConstructor()->getMock(); - $this->csrfTokenManager = new \OC\Security\CSRF\CsrfTokenManager( + $this->csrfTokenManager = new CsrfTokenManager( $this->tokenGenerator, $this->storageInterface ); @@ -41,7 +44,7 @@ class CsrfTokenManagerTest extends \Test\TestCase { ->method('getToken') ->willReturn('MyExistingToken'); - $expected = new \OC\Security\CSRF\CsrfToken('MyExistingToken'); + $expected = new CsrfToken('MyExistingToken'); $this->assertEquals($expected, $this->csrfTokenManager->getToken()); } @@ -55,7 +58,7 @@ class CsrfTokenManagerTest extends \Test\TestCase { ->method('getToken') ->willReturn('MyExistingToken'); - $expected = new \OC\Security\CSRF\CsrfToken('MyExistingToken'); + $expected = new CsrfToken('MyExistingToken'); $token = $this->csrfTokenManager->getToken(); $this->assertSame($token, $this->csrfTokenManager->getToken()); $this->assertSame($token, $this->csrfTokenManager->getToken()); @@ -75,7 +78,7 @@ class CsrfTokenManagerTest extends \Test\TestCase { ->method('setToken') ->with('MyNewToken'); - $expected = new \OC\Security\CSRF\CsrfToken('MyNewToken'); + $expected = new CsrfToken('MyNewToken'); $this->assertEquals($expected, $this->csrfTokenManager->getToken()); } @@ -89,7 +92,7 @@ class CsrfTokenManagerTest extends \Test\TestCase { ->method('setToken') ->with('MyNewToken'); - $expected = new \OC\Security\CSRF\CsrfToken('MyNewToken'); + $expected = new CsrfToken('MyNewToken'); $this->assertEquals($expected, $this->csrfTokenManager->refreshToken()); } @@ -106,7 +109,7 @@ class CsrfTokenManagerTest extends \Test\TestCase { ->expects($this->once()) ->method('hasToken') ->willReturn(false); - $token = new \OC\Security\CSRF\CsrfToken('Token'); + $token = new CsrfToken('Token'); $this->assertSame(false, $this->csrfTokenManager->isTokenValid($token)); } @@ -116,7 +119,7 @@ class CsrfTokenManagerTest extends \Test\TestCase { ->expects($this->once()) ->method('hasToken') ->willReturn(true); - $token = new \OC\Security\CSRF\CsrfToken('Token'); + $token = new CsrfToken('Token'); $this->storageInterface ->expects($this->once()) ->method('getToken') @@ -134,7 +137,7 @@ class CsrfTokenManagerTest extends \Test\TestCase { ->expects($this->once()) ->method('hasToken') ->willReturn(true); - $token = new \OC\Security\CSRF\CsrfToken($tokenVal); + $token = new CsrfToken($tokenVal); $this->storageInterface ->expects($this->once()) ->method('getToken') diff --git a/tests/lib/Security/CSRF/CsrfTokenTest.php b/tests/lib/Security/CSRF/CsrfTokenTest.php index 9ecbbe9f23a..5b5ba5ae54f 100644 --- a/tests/lib/Security/CSRF/CsrfTokenTest.php +++ b/tests/lib/Security/CSRF/CsrfTokenTest.php @@ -10,15 +10,17 @@ declare(strict_types=1); namespace Test\Security\CSRF; +use OC\Security\CSRF\CsrfToken; + class CsrfTokenTest extends \Test\TestCase { public function testGetEncryptedValue(): void { - $csrfToken = new \OC\Security\CSRF\CsrfToken('MyCsrfToken'); + $csrfToken = new CsrfToken('MyCsrfToken'); $this->assertSame(33, strlen($csrfToken->getEncryptedValue())); $this->assertSame(':', $csrfToken->getEncryptedValue()[16]); } public function testGetEncryptedValueStaysSameOnSecondRequest(): void { - $csrfToken = new \OC\Security\CSRF\CsrfToken('MyCsrfToken'); + $csrfToken = new CsrfToken('MyCsrfToken'); $tokenValue = $csrfToken->getEncryptedValue(); $this->assertSame($tokenValue, $csrfToken->getEncryptedValue()); $this->assertSame($tokenValue, $csrfToken->getEncryptedValue()); @@ -29,7 +31,7 @@ class CsrfTokenTest extends \Test\TestCase { $b = 'def'; $xorB64 = 'BQcF'; $tokenVal = sprintf('%s:%s', $xorB64, base64_encode($a)); - $csrfToken = new \OC\Security\CSRF\CsrfToken($tokenVal); + $csrfToken = new CsrfToken($tokenVal); $this->assertSame($b, $csrfToken->getDecryptedValue()); } } diff --git a/tests/lib/Security/CSRF/TokenStorage/SessionStorageTest.php b/tests/lib/Security/CSRF/TokenStorage/SessionStorageTest.php index fcc776ade8e..0e8a36112e2 100644 --- a/tests/lib/Security/CSRF/TokenStorage/SessionStorageTest.php +++ b/tests/lib/Security/CSRF/TokenStorage/SessionStorageTest.php @@ -10,6 +10,7 @@ declare(strict_types=1); namespace Test\Security\CSRF\TokenStorage; +use OC\Security\CSRF\TokenStorage\SessionStorage; use OCP\ISession; class SessionStorageTest extends \Test\TestCase { @@ -22,7 +23,7 @@ class SessionStorageTest extends \Test\TestCase { parent::setUp(); $this->session = $this->getMockBuilder(ISession::class) ->disableOriginalConstructor()->getMock(); - $this->sessionStorage = new \OC\Security\CSRF\TokenStorage\SessionStorage($this->session); + $this->sessionStorage = new SessionStorage($this->session); } /** diff --git a/tests/lib/Security/CertificateManagerTest.php b/tests/lib/Security/CertificateManagerTest.php index a0cb133ec3b..3657eeb2f99 100644 --- a/tests/lib/Security/CertificateManagerTest.php +++ b/tests/lib/Security/CertificateManagerTest.php @@ -10,11 +10,16 @@ declare(strict_types=1); namespace Test\Security; +use OC\Files\Filesystem; +use OC\Files\Storage\Temporary; use OC\Files\View; +use OC\Security\Certificate; use OC\Security\CertificateManager; use OCP\Files\InvalidPathException; use OCP\IConfig; +use OCP\IUserManager; use OCP\Security\ISecureRandom; +use OCP\Server; use PHPUnit\Framework\MockObject\MockObject; use Psr\Log\LoggerInterface; @@ -37,12 +42,12 @@ class CertificateManagerTest extends \Test\TestCase { $this->username = $this->getUniqueID('', 20); $this->createUser($this->username, ''); - $storage = new \OC\Files\Storage\Temporary(); + $storage = new Temporary(); $this->registerMount($this->username, $storage, '/' . $this->username . '/'); \OC_Util::tearDownFS(); \OC_User::setUserId($this->username); - \OC\Files\Filesystem::tearDown(); + Filesystem::tearDown(); \OC_Util::setupFS($this->username); $config = $this->createMock(IConfig::class); @@ -54,7 +59,7 @@ class CertificateManagerTest extends \Test\TestCase { ->willReturn('random'); $this->certificateManager = new CertificateManager( - new \OC\Files\View(), + new View(), $config, $this->createMock(LoggerInterface::class), $this->random @@ -62,7 +67,7 @@ class CertificateManagerTest extends \Test\TestCase { } protected function tearDown(): void { - $user = \OC::$server->getUserManager()->get($this->username); + $user = Server::get(IUserManager::class)->get($this->username); if ($user !== null) { $user->delete(); } @@ -83,12 +88,12 @@ class CertificateManagerTest extends \Test\TestCase { // Add some certificates $this->certificateManager->addCertificate(file_get_contents(__DIR__ . '/../../data/certificates/goodCertificate.crt'), 'GoodCertificate'); $certificateStore = []; - $certificateStore[] = new \OC\Security\Certificate(file_get_contents(__DIR__ . '/../../data/certificates/goodCertificate.crt'), 'GoodCertificate'); + $certificateStore[] = new Certificate(file_get_contents(__DIR__ . '/../../data/certificates/goodCertificate.crt'), 'GoodCertificate'); $this->assertEqualsArrays($certificateStore, $this->certificateManager->listCertificates()); // Add another certificates $this->certificateManager->addCertificate(file_get_contents(__DIR__ . '/../../data/certificates/expiredCertificate.crt'), 'ExpiredCertificate'); - $certificateStore[] = new \OC\Security\Certificate(file_get_contents(__DIR__ . '/../../data/certificates/expiredCertificate.crt'), 'ExpiredCertificate'); + $certificateStore[] = new Certificate(file_get_contents(__DIR__ . '/../../data/certificates/expiredCertificate.crt'), 'ExpiredCertificate'); $this->assertEqualsArrays($certificateStore, $this->certificateManager->listCertificates()); } diff --git a/tests/lib/Security/CryptoTest.php b/tests/lib/Security/CryptoTest.php index 64042d0c5a9..b650e3ffc09 100644 --- a/tests/lib/Security/CryptoTest.php +++ b/tests/lib/Security/CryptoTest.php @@ -11,6 +11,8 @@ declare(strict_types=1); namespace Test\Security; use OC\Security\Crypto; +use OCP\IConfig; +use OCP\Server; class CryptoTest extends \Test\TestCase { public static function defaultEncryptionProvider(): array { @@ -26,7 +28,7 @@ class CryptoTest extends \Test\TestCase { protected function setUp(): void { parent::setUp(); - $this->crypto = new Crypto(\OC::$server->getConfig()); + $this->crypto = new Crypto(Server::get(IConfig::class)); } /** diff --git a/tests/lib/Security/FeaturePolicy/FeaturePolicyManagerTest.php b/tests/lib/Security/FeaturePolicy/FeaturePolicyManagerTest.php index 7386aa023a9..01624cb92d3 100644 --- a/tests/lib/Security/FeaturePolicy/FeaturePolicyManagerTest.php +++ b/tests/lib/Security/FeaturePolicy/FeaturePolicyManagerTest.php @@ -12,6 +12,7 @@ use OC\Security\FeaturePolicy\FeaturePolicyManager; use OCP\AppFramework\Http\FeaturePolicy; use OCP\EventDispatcher\IEventDispatcher; use OCP\Security\FeaturePolicy\AddFeaturePolicyEvent; +use OCP\Server; use Test\TestCase; class FeaturePolicyManagerTest extends TestCase { @@ -23,7 +24,7 @@ class FeaturePolicyManagerTest extends TestCase { protected function setUp(): void { parent::setUp(); - $this->dispatcher = \OC::$server->query(IEventDispatcher::class); + $this->dispatcher = Server::get(IEventDispatcher::class); $this->manager = new FeaturePolicyManager($this->dispatcher); } @@ -33,7 +34,7 @@ class FeaturePolicyManagerTest extends TestCase { } public function testGetDefaultPolicyWithPoliciesViaEvent(): void { - $this->dispatcher->addListener(AddFeaturePolicyEvent::class, function (AddFeaturePolicyEvent $e) { + $this->dispatcher->addListener(AddFeaturePolicyEvent::class, function (AddFeaturePolicyEvent $e): void { $policy = new FeaturePolicy(); $policy->addAllowedMicrophoneDomain('mydomain.com'); $policy->addAllowedPaymentDomain('mypaymentdomain.com'); @@ -41,7 +42,7 @@ class FeaturePolicyManagerTest extends TestCase { $e->addPolicy($policy); }); - $this->dispatcher->addListener(AddFeaturePolicyEvent::class, function (AddFeaturePolicyEvent $e) { + $this->dispatcher->addListener(AddFeaturePolicyEvent::class, function (AddFeaturePolicyEvent $e): void { $policy = new FeaturePolicy(); $policy->addAllowedPaymentDomain('mydomainother.com'); $policy->addAllowedGeoLocationDomain('mylocation.here'); @@ -49,7 +50,7 @@ class FeaturePolicyManagerTest extends TestCase { $e->addPolicy($policy); }); - $this->dispatcher->addListener(AddFeaturePolicyEvent::class, function (AddFeaturePolicyEvent $e) { + $this->dispatcher->addListener(AddFeaturePolicyEvent::class, function (AddFeaturePolicyEvent $e): void { $policy = new FeaturePolicy(); $policy->addAllowedAutoplayDomain('youtube.com'); diff --git a/tests/lib/Security/RateLimiting/LimiterTest.php b/tests/lib/Security/RateLimiting/LimiterTest.php index 6f430e85576..b19d5c6feba 100644 --- a/tests/lib/Security/RateLimiting/LimiterTest.php +++ b/tests/lib/Security/RateLimiting/LimiterTest.php @@ -10,6 +10,7 @@ declare(strict_types=1); namespace Test\Security\RateLimiting; use OC\Security\RateLimiting\Backend\IBackend; +use OC\Security\RateLimiting\Exception\RateLimitExceededException; use OC\Security\RateLimiting\Limiter; use OCP\IUser; use OCP\Security\RateLimiting\ILimiter; @@ -37,7 +38,7 @@ class LimiterTest extends TestCase { public function testRegisterAnonRequestExceeded(): void { - $this->expectException(\OC\Security\RateLimiting\Exception\RateLimitExceededException::class); + $this->expectException(RateLimitExceededException::class); $this->expectExceptionMessage('Rate limit exceeded'); $this->backend @@ -79,7 +80,7 @@ class LimiterTest extends TestCase { public function testRegisterUserRequestExceeded(): void { - $this->expectException(\OC\Security\RateLimiting\Exception\RateLimitExceededException::class); + $this->expectException(RateLimitExceededException::class); $this->expectExceptionMessage('Rate limit exceeded'); /** @var IUser|\PHPUnit\Framework\MockObject\MockObject $user */ diff --git a/tests/lib/Security/SecureRandomTest.php b/tests/lib/Security/SecureRandomTest.php index 98eb0e45df3..490045a4c52 100644 --- a/tests/lib/Security/SecureRandomTest.php +++ b/tests/lib/Security/SecureRandomTest.php @@ -37,7 +37,7 @@ class SecureRandomTest extends \Test\TestCase { protected function setUp(): void { parent::setUp(); - $this->rng = new \OC\Security\SecureRandom(); + $this->rng = new SecureRandom(); } /** diff --git a/tests/lib/ServerTest.php b/tests/lib/ServerTest.php index 371bc572b15..58d987a102d 100644 --- a/tests/lib/ServerTest.php +++ b/tests/lib/ServerTest.php @@ -8,6 +8,8 @@ namespace Test; use OC\App\AppStore\Fetcher\AppFetcher; +use OC\Config; +use OC\Server; use OCP\Comments\ICommentsManager; /** @@ -24,8 +26,8 @@ class ServerTest extends \Test\TestCase { protected function setUp(): void { parent::setUp(); - $config = new \OC\Config(\OC::$configDir); - $this->server = new \OC\Server('', $config); + $config = new Config(\OC::$configDir); + $this->server = new Server('', $config); } public static function dataTestQuery(): array { diff --git a/tests/lib/Session/CryptoSessionDataTest.php b/tests/lib/Session/CryptoSessionDataTest.php index 6c1536f4769..85cdcfbf83b 100644 --- a/tests/lib/Session/CryptoSessionDataTest.php +++ b/tests/lib/Session/CryptoSessionDataTest.php @@ -8,6 +8,7 @@ namespace Test\Session; use OC\Session\CryptoSessionData; +use OC\Session\Memory; use OCP\Security\ICrypto; class CryptoSessionDataTest extends Session { @@ -20,7 +21,7 @@ class CryptoSessionDataTest extends Session { protected function setUp(): void { parent::setUp(); - $this->wrappedSession = new \OC\Session\Memory(); + $this->wrappedSession = new Memory(); $this->crypto = $this->createMock(ICrypto::class); $this->crypto->expects($this->any()) ->method('encrypt') diff --git a/tests/lib/Session/MemoryTest.php b/tests/lib/Session/MemoryTest.php index 24bfc06b274..40977f1f3fb 100644 --- a/tests/lib/Session/MemoryTest.php +++ b/tests/lib/Session/MemoryTest.php @@ -8,15 +8,18 @@ namespace Test\Session; +use OC\Session\Memory; +use OCP\Session\Exceptions\SessionNotAvailableException; + class MemoryTest extends Session { protected function setUp(): void { parent::setUp(); - $this->instance = new \OC\Session\Memory(); + $this->instance = new Memory(); } public function testThrowsExceptionOnGetId(): void { - $this->expectException(\OCP\Session\Exceptions\SessionNotAvailableException::class); + $this->expectException(SessionNotAvailableException::class); $this->instance->getId(); } diff --git a/tests/lib/Settings/ManagerTest.php b/tests/lib/Settings/ManagerTest.php index 38b0262bb55..e4672235711 100644 --- a/tests/lib/Settings/ManagerTest.php +++ b/tests/lib/Settings/ManagerTest.php @@ -8,6 +8,7 @@ namespace OC\Settings\Tests\AppInfo; use OC\Settings\AuthorizedGroupMapper; use OC\Settings\Manager; +use OCA\WorkflowEngine\Settings\Section; use OCP\Group\ISubAdmin; use OCP\IDBConnection; use OCP\IGroupManager; @@ -15,6 +16,7 @@ use OCP\IL10N; use OCP\IServerContainer; use OCP\IURLGenerator; use OCP\L10N\IFactory; +use OCP\Server; use OCP\Settings\ISettings; use OCP\Settings\ISubAdminSettings; use PHPUnit\Framework\MockObject\MockObject; @@ -65,11 +67,11 @@ class ManagerTest extends TestCase { } public function testGetAdminSections(): void { - $this->manager->registerSection('admin', \OCA\WorkflowEngine\Settings\Section::class); + $this->manager->registerSection('admin', Section::class); - $section = \OC::$server->query(\OCA\WorkflowEngine\Settings\Section::class); + $section = Server::get(Section::class); $this->container->method('get') - ->with(\OCA\WorkflowEngine\Settings\Section::class) + ->with(Section::class) ->willReturn($section); $this->assertEquals([ @@ -78,11 +80,11 @@ class ManagerTest extends TestCase { } public function testGetPersonalSections(): void { - $this->manager->registerSection('personal', \OCA\WorkflowEngine\Settings\Section::class); + $this->manager->registerSection('personal', Section::class); - $section = \OC::$server->query(\OCA\WorkflowEngine\Settings\Section::class); + $section = Server::get(Section::class); $this->container->method('get') - ->with(\OCA\WorkflowEngine\Settings\Section::class) + ->with(Section::class) ->willReturn($section); $this->assertEquals([ @@ -202,13 +204,13 @@ class ManagerTest extends TestCase { ->method('t') ->willReturnArgument(0); - $this->manager->registerSection('personal', \OCA\WorkflowEngine\Settings\Section::class); - $this->manager->registerSection('admin', \OCA\WorkflowEngine\Settings\Section::class); + $this->manager->registerSection('personal', Section::class); + $this->manager->registerSection('admin', Section::class); - $section = \OC::$server->query(\OCA\WorkflowEngine\Settings\Section::class); + $section = Server::get(Section::class); $this->container->method('get') - ->with(\OCA\WorkflowEngine\Settings\Section::class) + ->with(Section::class) ->willReturn($section); $this->assertEquals([ diff --git a/tests/lib/Share/Backend.php b/tests/lib/Share/Backend.php index 489f4a9bfd1..8f38d216ff5 100644 --- a/tests/lib/Share/Backend.php +++ b/tests/lib/Share/Backend.php @@ -10,8 +10,9 @@ namespace Test\Share; use OC\Share20\Manager; use OCP\Server; use OCP\Share\IShare; +use OCP\Share_Backend; -class Backend implements \OCP\Share_Backend { +class Backend implements Share_Backend { public const FORMAT_SOURCE = 0; public const FORMAT_TARGET = 1; public const FORMAT_PERMISSIONS = 2; diff --git a/tests/lib/Share/HelperTest.php b/tests/lib/Share/HelperTest.php index c56350358eb..b39720181b6 100644 --- a/tests/lib/Share/HelperTest.php +++ b/tests/lib/Share/HelperTest.php @@ -7,6 +7,8 @@ namespace Test\Share; +use OC\Share\Helper; + /** * @group DB * Class Helper @@ -37,7 +39,7 @@ class HelperTest extends \Test\TestCase { * @dataProvider expireDateProvider */ public function testCalculateExpireDate($defaultExpireSettings, $creationTime, $userExpireDate, $expected): void { - $result = \OC\Share\Helper::calculateExpireDate($defaultExpireSettings, $creationTime, $userExpireDate); + $result = Helper::calculateExpireDate($defaultExpireSettings, $creationTime, $userExpireDate); $this->assertSame($expected, $result); } @@ -50,7 +52,7 @@ class HelperTest extends \Test\TestCase { */ public function testIsSameUserOnSameServer($user1, $server1, $user2, $server2, $expected): void { $this->assertSame($expected, - \OC\Share\Helper::isSameUserOnSameServer($user1, $server1, $user2, $server2) + Helper::isSameUserOnSameServer($user1, $server1, $user2, $server2) ); } diff --git a/tests/lib/Share/ShareTest.php b/tests/lib/Share/ShareTest.php index 944d0738eb1..6814eac4e3c 100644 --- a/tests/lib/Share/ShareTest.php +++ b/tests/lib/Share/ShareTest.php @@ -8,11 +8,15 @@ namespace Test\Share; use OC\Share\Share; +use OC\SystemConfig; +use OCP\Constants; +use OCP\IConfig; use OCP\IDBConnection; use OCP\IGroup; use OCP\IGroupManager; use OCP\IUser; use OCP\IUserManager; +use OCP\Server; /** * Class Test_Share @@ -45,8 +49,8 @@ class ShareTest extends \Test\TestCase { protected function setUp(): void { parent::setUp(); - $this->groupManager = \OC::$server->getGroupManager(); - $this->userManager = \OC::$server->getUserManager(); + $this->groupManager = Server::get(IGroupManager::class); + $this->userManager = Server::get(IUserManager::class); $this->userManager->clearBackends(); $this->userManager->registerBackend(new \Test\Util\User\Dummy()); @@ -66,7 +70,7 @@ class ShareTest extends \Test\TestCase { $this->group1 = $this->groupManager->createGroup($this->getUniqueID('group1_')); $this->group2 = $this->groupManager->createGroup($this->getUniqueID('group2_')); $this->groupAndUser_group = $this->groupManager->createGroup($groupAndUserId); - $this->connection = \OC::$server->get(IDBConnection::class); + $this->connection = Server::get(IDBConnection::class); $this->group1->addUser($this->user1); $this->group1->addUser($this->user2); @@ -78,9 +82,9 @@ class ShareTest extends \Test\TestCase { Share::registerBackend('test', 'Test\Share\Backend'); \OC_Hook::clear('OCP\\Share'); - \OC::registerShareHooks(\OC::$server->getSystemConfig()); - $this->resharing = \OC::$server->getConfig()->getAppValue('core', 'shareapi_allow_resharing', 'yes'); - \OC::$server->getConfig()->setAppValue('core', 'shareapi_allow_resharing', 'yes'); + \OC::registerShareHooks(Server::get(SystemConfig::class)); + $this->resharing = Server::get(IConfig::class)->getAppValue('core', 'shareapi_allow_resharing', 'yes'); + Server::get(IConfig::class)->setAppValue('core', 'shareapi_allow_resharing', 'yes'); // 20 Minutes in the past, 20 minutes in the future. $now = time(); @@ -93,7 +97,7 @@ class ShareTest extends \Test\TestCase { $query = $this->connection->getQueryBuilder(); $query->delete('share')->andWhere($query->expr()->eq('item_type', $query->createNamedParameter('test'))); $query->executeStatement(); - \OC::$server->getConfig()->setAppValue('core', 'shareapi_allow_resharing', $this->resharing); + Server::get(IConfig::class)->setAppValue('core', 'shareapi_allow_resharing', $this->resharing); $this->user1->delete(); $this->user2->delete(); @@ -166,20 +170,20 @@ class ShareTest extends \Test\TestCase { // one array with one share [ [ // input - ['item_source' => 1, 'permissions' => \OCP\Constants::PERMISSION_ALL, 'item_target' => 't1']], + ['item_source' => 1, 'permissions' => Constants::PERMISSION_ALL, 'item_target' => 't1']], [ // expected result - ['item_source' => 1, 'permissions' => \OCP\Constants::PERMISSION_ALL, 'item_target' => 't1']]], + ['item_source' => 1, 'permissions' => Constants::PERMISSION_ALL, 'item_target' => 't1']]], // two shares both point to the same source [ [ // input - ['item_source' => 1, 'permissions' => \OCP\Constants::PERMISSION_READ, 'item_target' => 't1'], - ['item_source' => 1, 'permissions' => \OCP\Constants::PERMISSION_UPDATE, 'item_target' => 't1'], + ['item_source' => 1, 'permissions' => Constants::PERMISSION_READ, 'item_target' => 't1'], + ['item_source' => 1, 'permissions' => Constants::PERMISSION_UPDATE, 'item_target' => 't1'], ], [ // expected result - ['item_source' => 1, 'permissions' => \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_UPDATE, 'item_target' => 't1', + ['item_source' => 1, 'permissions' => Constants::PERMISSION_READ | Constants::PERMISSION_UPDATE, 'item_target' => 't1', 'grouped' => [ - ['item_source' => 1, 'permissions' => \OCP\Constants::PERMISSION_READ, 'item_target' => 't1'], - ['item_source' => 1, 'permissions' => \OCP\Constants::PERMISSION_UPDATE, 'item_target' => 't1'], + ['item_source' => 1, 'permissions' => Constants::PERMISSION_READ, 'item_target' => 't1'], + ['item_source' => 1, 'permissions' => Constants::PERMISSION_UPDATE, 'item_target' => 't1'], ] ], ] @@ -187,29 +191,29 @@ class ShareTest extends \Test\TestCase { // two shares both point to the same source but with different targets [ [ // input - ['item_source' => 1, 'permissions' => \OCP\Constants::PERMISSION_READ, 'item_target' => 't1'], - ['item_source' => 1, 'permissions' => \OCP\Constants::PERMISSION_UPDATE, 'item_target' => 't2'], + ['item_source' => 1, 'permissions' => Constants::PERMISSION_READ, 'item_target' => 't1'], + ['item_source' => 1, 'permissions' => Constants::PERMISSION_UPDATE, 'item_target' => 't2'], ], [ // expected result - ['item_source' => 1, 'permissions' => \OCP\Constants::PERMISSION_READ, 'item_target' => 't1'], - ['item_source' => 1, 'permissions' => \OCP\Constants::PERMISSION_UPDATE, 'item_target' => 't2'], + ['item_source' => 1, 'permissions' => Constants::PERMISSION_READ, 'item_target' => 't1'], + ['item_source' => 1, 'permissions' => Constants::PERMISSION_UPDATE, 'item_target' => 't2'], ] ], // three shares two point to the same source [ [ // input - ['item_source' => 1, 'permissions' => \OCP\Constants::PERMISSION_READ, 'item_target' => 't1'], - ['item_source' => 2, 'permissions' => \OCP\Constants::PERMISSION_CREATE, 'item_target' => 't2'], - ['item_source' => 1, 'permissions' => \OCP\Constants::PERMISSION_UPDATE, 'item_target' => 't1'], + ['item_source' => 1, 'permissions' => Constants::PERMISSION_READ, 'item_target' => 't1'], + ['item_source' => 2, 'permissions' => Constants::PERMISSION_CREATE, 'item_target' => 't2'], + ['item_source' => 1, 'permissions' => Constants::PERMISSION_UPDATE, 'item_target' => 't1'], ], [ // expected result - ['item_source' => 1, 'permissions' => \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_UPDATE, 'item_target' => 't1', + ['item_source' => 1, 'permissions' => Constants::PERMISSION_READ | Constants::PERMISSION_UPDATE, 'item_target' => 't1', 'grouped' => [ - ['item_source' => 1, 'permissions' => \OCP\Constants::PERMISSION_READ, 'item_target' => 't1'], - ['item_source' => 1, 'permissions' => \OCP\Constants::PERMISSION_UPDATE, 'item_target' => 't1'], + ['item_source' => 1, 'permissions' => Constants::PERMISSION_READ, 'item_target' => 't1'], + ['item_source' => 1, 'permissions' => Constants::PERMISSION_UPDATE, 'item_target' => 't1'], ] ], - ['item_source' => 2, 'permissions' => \OCP\Constants::PERMISSION_CREATE, 'item_target' => 't2'], + ['item_source' => 2, 'permissions' => Constants::PERMISSION_CREATE, 'item_target' => 't2'], ] ], ]; diff --git a/tests/lib/Share20/DefaultShareProviderTest.php b/tests/lib/Share20/DefaultShareProviderTest.php index 39560795921..1b2745882f1 100644 --- a/tests/lib/Share20/DefaultShareProviderTest.php +++ b/tests/lib/Share20/DefaultShareProviderTest.php @@ -9,8 +9,11 @@ namespace Test\Share20; use OC\Files\Node\Node; use OC\Share20\DefaultShareProvider; +use OC\Share20\Exception\ProviderException; +use OC\Share20\Share; use OC\Share20\ShareAttributes; use OCP\AppFramework\Utility\ITimeFactory; +use OCP\Constants; use OCP\DB\QueryBuilder\IQueryBuilder; use OCP\Defaults; use OCP\Files\File; @@ -25,6 +28,8 @@ use OCP\IUser; use OCP\IUserManager; use OCP\L10N\IFactory; use OCP\Mail\IMailer; +use OCP\Server; +use OCP\Share\Exceptions\ShareNotFound; use OCP\Share\IManager as IShareManager; use OCP\Share\IShare; use PHPUnit\Framework\MockObject\MockObject; @@ -76,7 +81,7 @@ class DefaultShareProviderTest extends \Test\TestCase { protected IShareManager&MockObject $shareManager; protected function setUp(): void { - $this->dbConn = \OC::$server->getDatabaseConnection(); + $this->dbConn = Server::get(IDBConnection::class); $this->userManager = $this->createMock(IUserManager::class); $this->groupManager = $this->createMock(IGroupManager::class); $this->rootFolder = $this->createMock(IRootFolder::class); @@ -177,7 +182,7 @@ class DefaultShareProviderTest extends \Test\TestCase { public function testGetShareByIdNotExist(): void { - $this->expectException(\OCP\Share\Exceptions\ShareNotFound::class); + $this->expectException(ShareNotFound::class); $this->provider->getShareById(1); } @@ -674,7 +679,7 @@ class DefaultShareProviderTest extends \Test\TestCase { } public function testCreateUserShare(): void { - $share = new \OC\Share20\Share($this->rootFolder, $this->userManager); + $share = new Share($this->rootFolder, $this->userManager); $shareOwner = $this->createMock(IUser::class); $shareOwner->method('getUID')->willReturn('shareOwner'); @@ -746,7 +751,7 @@ class DefaultShareProviderTest extends \Test\TestCase { } public function testCreateGroupShare(): void { - $share = new \OC\Share20\Share($this->rootFolder, $this->userManager); + $share = new Share($this->rootFolder, $this->userManager); $shareOwner = $this->createMock(IUser::class); $shareOwner->method('getUID')->willReturn('shareOwner'); @@ -816,7 +821,7 @@ class DefaultShareProviderTest extends \Test\TestCase { } public function testCreateLinkShare(): void { - $share = new \OC\Share20\Share($this->rootFolder, $this->userManager); + $share = new Share($this->rootFolder, $this->userManager); $shareOwner = $this->createMock(IUser::class); $shareOwner->method('getUID')->willReturn('shareOwner'); @@ -940,7 +945,7 @@ class DefaultShareProviderTest extends \Test\TestCase { } public function testGetShareByTokenNotFound(): void { - $this->expectException(\OCP\Share\Exceptions\ShareNotFound::class); + $this->expectException(ShareNotFound::class); $this->provider->getShareByToken('invalidtoken'); } @@ -1679,7 +1684,7 @@ class DefaultShareProviderTest extends \Test\TestCase { public function testDeleteFromSelfGroupDoesNotExist(): void { - $this->expectException(\OC\Share20\Exception\ProviderException::class); + $this->expectException(ProviderException::class); $this->expectExceptionMessage('Group "group" does not exist'); $qb = $this->dbConn->getQueryBuilder(); @@ -1770,7 +1775,7 @@ class DefaultShareProviderTest extends \Test\TestCase { public function testDeleteFromSelfUserNotRecipient(): void { - $this->expectException(\OC\Share20\Exception\ProviderException::class); + $this->expectException(ProviderException::class); $this->expectExceptionMessage('Recipient does not match'); $qb = $this->dbConn->getQueryBuilder(); @@ -1813,7 +1818,7 @@ class DefaultShareProviderTest extends \Test\TestCase { public function testDeleteFromSelfLink(): void { - $this->expectException(\OC\Share20\Exception\ProviderException::class); + $this->expectException(ProviderException::class); $this->expectExceptionMessage('Invalid shareType'); $qb = $this->dbConn->getQueryBuilder(); @@ -2556,9 +2561,9 @@ class DefaultShareProviderTest extends \Test\TestCase { } public function testGetSharesInFolder(): void { - $userManager = \OC::$server->getUserManager(); - $groupManager = \OC::$server->getGroupManager(); - $rootFolder = \OC::$server->get(IRootFolder::class); + $userManager = Server::get(IUserManager::class); + $groupManager = Server::get(IGroupManager::class); + $rootFolder = Server::get(IRootFolder::class); $provider = new DefaultShareProvider( $this->dbConn, @@ -2587,14 +2592,14 @@ class DefaultShareProviderTest extends \Test\TestCase { $file1 = $folder1->newFile('bar'); $folder2 = $folder1->newFolder('baz'); - $shareManager = \OC::$server->get(IShareManager::class); + $shareManager = Server::get(IShareManager::class); $share1 = $shareManager->newShare(); $share1->setNode($folder1) ->setSharedBy($u1->getUID()) ->setSharedWith($u2->getUID()) ->setShareOwner($u1->getUID()) ->setShareType(IShare::TYPE_USER) - ->setPermissions(\OCP\Constants::PERMISSION_ALL); + ->setPermissions(Constants::PERMISSION_ALL); $share1 = $this->provider->create($share1); $share2 = $shareManager->newShare(); @@ -2603,7 +2608,7 @@ class DefaultShareProviderTest extends \Test\TestCase { ->setSharedWith($u3->getUID()) ->setShareOwner($u1->getUID()) ->setShareType(IShare::TYPE_USER) - ->setPermissions(\OCP\Constants::PERMISSION_READ); + ->setPermissions(Constants::PERMISSION_READ); $share2 = $this->provider->create($share2); $share3 = $shareManager->newShare(); @@ -2611,7 +2616,7 @@ class DefaultShareProviderTest extends \Test\TestCase { ->setSharedBy($u2->getUID()) ->setShareOwner($u1->getUID()) ->setShareType(IShare::TYPE_LINK) - ->setPermissions(\OCP\Constants::PERMISSION_READ); + ->setPermissions(Constants::PERMISSION_READ); $share3 = $this->provider->create($share3); $share4 = $shareManager->newShare(); @@ -2620,7 +2625,7 @@ class DefaultShareProviderTest extends \Test\TestCase { ->setSharedWith($g1->getGID()) ->setShareOwner($u1->getUID()) ->setShareType(IShare::TYPE_GROUP) - ->setPermissions(\OCP\Constants::PERMISSION_READ); + ->setPermissions(Constants::PERMISSION_READ); $share4 = $this->provider->create($share4); $result = $provider->getSharesInFolder($u1->getUID(), $folder1, false); @@ -2656,9 +2661,9 @@ class DefaultShareProviderTest extends \Test\TestCase { } public function testGetAccessListNoCurrentAccessRequired(): void { - $userManager = \OC::$server->getUserManager(); - $groupManager = \OC::$server->getGroupManager(); - $rootFolder = \OC::$server->get(IRootFolder::class); + $userManager = Server::get(IUserManager::class); + $groupManager = Server::get(IGroupManager::class); + $rootFolder = Server::get(IRootFolder::class); $provider = new DefaultShareProvider( $this->dbConn, @@ -2693,14 +2698,14 @@ class DefaultShareProviderTest extends \Test\TestCase { $this->assertCount(0, $result['users']); $this->assertFalse($result['public']); - $shareManager = \OC::$server->get(IShareManager::class); + $shareManager = Server::get(IShareManager::class); $share1 = $shareManager->newShare(); $share1->setNode($folder1) ->setSharedBy($u1->getUID()) ->setSharedWith($u2->getUID()) ->setShareOwner($u1->getUID()) ->setShareType(IShare::TYPE_USER) - ->setPermissions(\OCP\Constants::PERMISSION_ALL); + ->setPermissions(Constants::PERMISSION_ALL); $share1 = $this->provider->create($share1); $share1 = $provider->acceptShare($share1, $u2->getUid()); @@ -2710,7 +2715,7 @@ class DefaultShareProviderTest extends \Test\TestCase { ->setSharedWith($g1->getGID()) ->setShareOwner($u1->getUID()) ->setShareType(IShare::TYPE_GROUP) - ->setPermissions(\OCP\Constants::PERMISSION_ALL); + ->setPermissions(Constants::PERMISSION_ALL); $share2 = $this->provider->create($share2); $shareManager->deleteFromSelf($share2, $u4->getUID()); @@ -2723,7 +2728,7 @@ class DefaultShareProviderTest extends \Test\TestCase { ->setSharedBy($u3->getUID()) ->setShareOwner($u1->getUID()) ->setShareType(IShare::TYPE_LINK) - ->setPermissions(\OCP\Constants::PERMISSION_READ); + ->setPermissions(Constants::PERMISSION_READ); $share3 = $this->provider->create($share3); $share4 = $shareManager->newShare(); @@ -2732,7 +2737,7 @@ class DefaultShareProviderTest extends \Test\TestCase { ->setSharedWith($u5->getUID()) ->setShareOwner($u1->getUID()) ->setShareType(IShare::TYPE_USER) - ->setPermissions(\OCP\Constants::PERMISSION_READ); + ->setPermissions(Constants::PERMISSION_READ); $share4 = $this->provider->create($share4); $share4 = $provider->acceptShare($share4, $u5->getUid()); @@ -2759,9 +2764,9 @@ class DefaultShareProviderTest extends \Test\TestCase { } public function testGetAccessListCurrentAccessRequired(): void { - $userManager = \OC::$server->getUserManager(); - $groupManager = \OC::$server->getGroupManager(); - $rootFolder = \OC::$server->get(IRootFolder::class); + $userManager = Server::get(IUserManager::class); + $groupManager = Server::get(IGroupManager::class); + $rootFolder = Server::get(IRootFolder::class); $provider = new DefaultShareProvider( $this->dbConn, @@ -2796,14 +2801,14 @@ class DefaultShareProviderTest extends \Test\TestCase { $this->assertCount(0, $result['users']); $this->assertFalse($result['public']); - $shareManager = \OC::$server->get(IShareManager::class); + $shareManager = Server::get(IShareManager::class); $share1 = $shareManager->newShare(); $share1->setNode($folder1) ->setSharedBy($u1->getUID()) ->setSharedWith($u2->getUID()) ->setShareOwner($u1->getUID()) ->setShareType(IShare::TYPE_USER) - ->setPermissions(\OCP\Constants::PERMISSION_ALL); + ->setPermissions(Constants::PERMISSION_ALL); $share1 = $this->provider->create($share1); $share1 = $provider->acceptShare($share1, $u2->getUid()); @@ -2813,7 +2818,7 @@ class DefaultShareProviderTest extends \Test\TestCase { ->setSharedWith($g1->getGID()) ->setShareOwner($u1->getUID()) ->setShareType(IShare::TYPE_GROUP) - ->setPermissions(\OCP\Constants::PERMISSION_ALL); + ->setPermissions(Constants::PERMISSION_ALL); $share2 = $this->provider->create($share2); $share2 = $provider->acceptShare($share2, $u3->getUid()); $share2 = $provider->acceptShare($share2, $u4->getUid()); @@ -2825,7 +2830,7 @@ class DefaultShareProviderTest extends \Test\TestCase { ->setSharedBy($u3->getUID()) ->setShareOwner($u1->getUID()) ->setShareType(IShare::TYPE_LINK) - ->setPermissions(\OCP\Constants::PERMISSION_READ); + ->setPermissions(Constants::PERMISSION_READ); $share3 = $this->provider->create($share3); $share4 = $shareManager->newShare(); @@ -2834,7 +2839,7 @@ class DefaultShareProviderTest extends \Test\TestCase { ->setSharedWith($u5->getUID()) ->setShareOwner($u1->getUID()) ->setShareType(IShare::TYPE_USER) - ->setPermissions(\OCP\Constants::PERMISSION_READ); + ->setPermissions(Constants::PERMISSION_READ); $share4 = $this->provider->create($share4); $share4 = $provider->acceptShare($share4, $u5->getUid()); diff --git a/tests/lib/Share20/LegacyHooksTest.php b/tests/lib/Share20/LegacyHooksTest.php index 4a3d3a4310b..f7e9d77bf03 100644 --- a/tests/lib/Share20/LegacyHooksTest.php +++ b/tests/lib/Share20/LegacyHooksTest.php @@ -6,6 +6,7 @@ namespace Test\Share20; +use OC\EventDispatcher\EventDispatcher; use OC\Share20\LegacyHooks; use OC\Share20\Manager; use OCP\Constants; @@ -13,6 +14,7 @@ use OCP\EventDispatcher\IEventDispatcher; use OCP\Files\Cache\ICacheEntry; use OCP\Files\File; use OCP\IServerContainer; +use OCP\Server; use OCP\Share\Events\BeforeShareCreatedEvent; use OCP\Share\Events\BeforeShareDeletedEvent; use OCP\Share\Events\ShareCreatedEvent; @@ -20,6 +22,7 @@ use OCP\Share\Events\ShareDeletedEvent; use OCP\Share\Events\ShareDeletedFromSelfEvent; use OCP\Share\IManager as IShareManager; use OCP\Share\IShare; +use OCP\Util; use Psr\Log\LoggerInterface; use Test\TestCase; @@ -51,9 +54,9 @@ class LegacyHooksTest extends TestCase { $symfonyDispatcher = new \Symfony\Component\EventDispatcher\EventDispatcher(); $logger = $this->createMock(LoggerInterface::class); - $this->eventDispatcher = new \OC\EventDispatcher\EventDispatcher($symfonyDispatcher, \OC::$server->get(IServerContainer::class), $logger); + $this->eventDispatcher = new EventDispatcher($symfonyDispatcher, Server::get(IServerContainer::class), $logger); $this->hooks = new LegacyHooks($this->eventDispatcher); - $this->manager = \OC::$server->get(IShareManager::class); + $this->manager = Server::get(IShareManager::class); } public function testPreUnshare(): void { @@ -74,7 +77,7 @@ class LegacyHooksTest extends TestCase { ->setNodeCacheEntry($info); $hookListner = $this->getMockBuilder(Dummy::class)->onlyMethods(['pre'])->getMock(); - \OCP\Util::connectHook('OCP\Share', 'pre_unshare', $hookListner, 'pre'); + Util::connectHook('OCP\Share', 'pre_unshare', $hookListner, 'pre'); $hookListnerExpectsPre = [ 'id' => 42, @@ -115,7 +118,7 @@ class LegacyHooksTest extends TestCase { ->setNodeCacheEntry($info); $hookListner = $this->getMockBuilder(Dummy::class)->onlyMethods(['post'])->getMock(); - \OCP\Util::connectHook('OCP\Share', 'post_unshare', $hookListner, 'post'); + Util::connectHook('OCP\Share', 'post_unshare', $hookListner, 'post'); $hookListnerExpectsPost = [ 'id' => 42, @@ -169,7 +172,7 @@ class LegacyHooksTest extends TestCase { ->setNodeCacheEntry($info); $hookListner = $this->getMockBuilder(Dummy::class)->onlyMethods(['postFromSelf'])->getMock(); - \OCP\Util::connectHook('OCP\Share', 'post_unshareFromSelf', $hookListner, 'postFromSelf'); + Util::connectHook('OCP\Share', 'post_unshareFromSelf', $hookListner, 'postFromSelf'); $hookListnerExpectsPostFromSelf = [ 'id' => 42, @@ -226,7 +229,7 @@ class LegacyHooksTest extends TestCase { $hookListner = $this->getMockBuilder(Dummy::class)->onlyMethods(['preShare'])->getMock(); - \OCP\Util::connectHook('OCP\Share', 'pre_shared', $hookListner, 'preShare'); + Util::connectHook('OCP\Share', 'pre_shared', $hookListner, 'preShare'); $run = true; $error = ''; @@ -274,7 +277,7 @@ class LegacyHooksTest extends TestCase { $hookListner = $this->getMockBuilder(Dummy::class)->onlyMethods(['preShare'])->getMock(); - \OCP\Util::connectHook('OCP\Share', 'pre_shared', $hookListner, 'preShare'); + Util::connectHook('OCP\Share', 'pre_shared', $hookListner, 'preShare'); $run = true; $error = ''; @@ -298,7 +301,7 @@ class LegacyHooksTest extends TestCase { ->expects($this->exactly(1)) ->method('preShare') ->with($expected) - ->willReturnCallback(function ($data) { + ->willReturnCallback(function ($data): void { $data['run'] = false; $data['error'] = 'I error'; }); @@ -330,7 +333,7 @@ class LegacyHooksTest extends TestCase { $hookListner = $this->getMockBuilder(Dummy::class)->onlyMethods(['postShare'])->getMock(); - \OCP\Util::connectHook('OCP\Share', 'post_shared', $hookListner, 'postShare'); + Util::connectHook('OCP\Share', 'post_shared', $hookListner, 'postShare'); $expected = [ 'id' => 42, diff --git a/tests/lib/Share20/ManagerTest.php b/tests/lib/Share20/ManagerTest.php index 357ae9ee678..346e6a49206 100644 --- a/tests/lib/Share20/ManagerTest.php +++ b/tests/lib/Share20/ManagerTest.php @@ -12,10 +12,11 @@ use OC\Files\Mount\MoveableMount; use OC\Files\Utils\PathHelper; use OC\KnownUser\KnownUserService; use OC\Share20\DefaultShareProvider; -use OC\Share20\Exception; +use OC\Share20\Exception\ProviderException; use OC\Share20\Manager; use OC\Share20\Share; use OC\Share20\ShareDisableChecker; +use OCP\Constants; use OCP\EventDispatcher\Event; use OCP\EventDispatcher\IEventDispatcher; use OCP\Files\File; @@ -56,6 +57,7 @@ use OCP\Share\IProviderFactory; use OCP\Share\IShare; use OCP\Share\IShareProvider; use OCP\Share\IShareProviderSupportsAllSharesInFolder; +use OCP\Util; use PHPUnit\Framework\MockObject\MockBuilder; use PHPUnit\Framework\MockObject\MockObject; use Psr\Log\LoggerInterface; @@ -278,7 +280,7 @@ class ManagerTest extends \Test\TestCase { ]; $this->dispatcher->expects($this->exactly(2)) ->method('dispatchTyped') - ->willReturnCallback(function ($event) use (&$calls, $share) { + ->willReturnCallback(function ($event) use (&$calls, $share): void { $expected = array_shift($calls); $this->assertInstanceOf($expected, $event); $this->assertEquals($share, $event->getShare()); @@ -321,7 +323,7 @@ class ManagerTest extends \Test\TestCase { ]; $this->dispatcher->expects($this->exactly(2)) ->method('dispatchTyped') - ->willReturnCallback(function ($event) use (&$calls, $share) { + ->willReturnCallback(function ($event) use (&$calls, $share): void { $expected = array_shift($calls); $this->assertInstanceOf($expected, $event); $this->assertEquals($share, $event->getShare()); @@ -381,7 +383,7 @@ class ManagerTest extends \Test\TestCase { ]; $this->defaultProvider->expects($this->exactly(3)) ->method('delete') - ->willReturnCallback(function ($share) use (&$deleteCalls) { + ->willReturnCallback(function ($share) use (&$deleteCalls): void { $expected = array_shift($deleteCalls); $this->assertEquals($expected, $share); }); @@ -396,7 +398,7 @@ class ManagerTest extends \Test\TestCase { ]; $this->dispatcher->expects($this->exactly(6)) ->method('dispatchTyped') - ->willReturnCallback(function ($event) use (&$dispatchCalls) { + ->willReturnCallback(function ($event) use (&$dispatchCalls): void { $expected = array_shift($dispatchCalls); $this->assertInstanceOf($expected[0], $event); $this->assertEquals($expected[1]->getId(), $event->getShare()->getId()); @@ -476,7 +478,7 @@ class ManagerTest extends \Test\TestCase { ]; $this->defaultProvider->expects($this->exactly(3)) ->method('delete') - ->willReturnCallback(function ($share) use (&$calls) { + ->willReturnCallback(function ($share) use (&$calls): void { $expected = array_shift($calls); $this->assertEquals($expected, $share); }); @@ -573,7 +575,7 @@ class ManagerTest extends \Test\TestCase { ]; $manager->expects($this->exactly(2)) ->method('updateShare') - ->willReturnCallback(function ($share) use (&$calls) { + ->willReturnCallback(function ($share) use (&$calls): void { $expected = array_shift($calls); $this->assertEquals($expected, $share); }); @@ -667,7 +669,7 @@ class ManagerTest extends \Test\TestCase { ]; $manager->expects($this->exactly(2)) ->method('updateShare') - ->willReturnCallback(function ($share) use (&$calls) { + ->willReturnCallback(function ($share) use (&$calls): void { $expected = array_shift($calls); $this->assertEquals($expected, $share); }); @@ -689,7 +691,7 @@ class ManagerTest extends \Test\TestCase { public function testGetExpiredShareById(): void { - $this->expectException(\OCP\Share\Exceptions\ShareNotFound::class); + $this->expectException(ShareNotFound::class); $manager = $this->createManagerMock() ->onlyMethods(['deleteShare']) @@ -774,7 +776,7 @@ class ManagerTest extends \Test\TestCase { ]); $this->dispatcher->expects($this->once())->method('dispatchTyped') - ->willReturnCallback(function (Event $event) { + ->willReturnCallback(function (Event $event): void { $this->assertInstanceOf(ValidatePasswordPolicyEvent::class, $event); /** @var ValidatePasswordPolicyEvent $event */ $this->assertSame('password', $event->getPassword()); @@ -796,7 +798,7 @@ class ManagerTest extends \Test\TestCase { ]); $this->dispatcher->expects($this->once())->method('dispatchTyped') - ->willReturnCallback(function (Event $event) { + ->willReturnCallback(function (Event $event): void { $this->assertInstanceOf(ValidatePasswordPolicyEvent::class, $event); /** @var ValidatePasswordPolicyEvent $event */ $this->assertSame('password', $event->getPassword()); @@ -891,7 +893,7 @@ class ManagerTest extends \Test\TestCase { $limitedPermssions = $this->createMock(File::class); $limitedPermssions->method('isShareable')->willReturn(true); - $limitedPermssions->method('getPermissions')->willReturn(\OCP\Constants::PERMISSION_READ); + $limitedPermssions->method('getPermissions')->willReturn(Constants::PERMISSION_READ); $limitedPermssions->method('getId')->willReturn(108); $limitedPermssions->method('getPath')->willReturn('path'); $limitedPermssions->method('getName')->willReturn('name'); @@ -915,10 +917,10 @@ class ManagerTest extends \Test\TestCase { $nonMovableStorage->method('instanceOfStorage') ->with('\OCA\Files_Sharing\External\Storage') ->willReturn(false); - $nonMovableStorage->method('getPermissions')->willReturn(\OCP\Constants::PERMISSION_ALL); + $nonMovableStorage->method('getPermissions')->willReturn(Constants::PERMISSION_ALL); $nonMoveableMountPermssions = $this->createMock(Folder::class); $nonMoveableMountPermssions->method('isShareable')->willReturn(true); - $nonMoveableMountPermssions->method('getPermissions')->willReturn(\OCP\Constants::PERMISSION_READ); + $nonMoveableMountPermssions->method('getPermissions')->willReturn(Constants::PERMISSION_READ); $nonMoveableMountPermssions->method('getId')->willReturn(108); $nonMoveableMountPermssions->method('getPath')->willReturn('path'); $nonMoveableMountPermssions->method('getName')->willReturn('name'); @@ -933,7 +935,7 @@ class ManagerTest extends \Test\TestCase { $rootFolder = $this->createMock(Folder::class); $rootFolder->method('isShareable')->willReturn(true); - $rootFolder->method('getPermissions')->willReturn(\OCP\Constants::PERMISSION_ALL); + $rootFolder->method('getPermissions')->willReturn(Constants::PERMISSION_ALL); $rootFolder->method('getId')->willReturn(42); $data[] = [$this->createShare(null, IShare::TYPE_USER, $rootFolder, $user2, $user0, $user0, 30, null, null), 'You cannot share your root folder', true]; @@ -942,7 +944,7 @@ class ManagerTest extends \Test\TestCase { $allPermssionsFiles = $this->createMock(File::class); $allPermssionsFiles->method('isShareable')->willReturn(true); - $allPermssionsFiles->method('getPermissions')->willReturn(\OCP\Constants::PERMISSION_ALL); + $allPermssionsFiles->method('getPermissions')->willReturn(Constants::PERMISSION_ALL); $allPermssionsFiles->method('getId')->willReturn(187); $allPermssionsFiles->method('getOwner') ->willReturn($owner); @@ -950,13 +952,13 @@ class ManagerTest extends \Test\TestCase { ->willReturn($storage); // test invalid CREATE or DELETE permissions - $data[] = [$this->createShare(null, IShare::TYPE_USER, $allPermssionsFiles, $user2, $user0, $user0, \OCP\Constants::PERMISSION_ALL, null, null), 'File shares cannot have create or delete permissions', true]; - $data[] = [$this->createShare(null, IShare::TYPE_GROUP, $allPermssionsFiles, $group0, $user0, $user0, \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_CREATE, null, null), 'File shares cannot have create or delete permissions', true]; - $data[] = [$this->createShare(null, IShare::TYPE_LINK, $allPermssionsFiles, null, $user0, $user0, \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_DELETE, null, null), 'File shares cannot have create or delete permissions', true]; + $data[] = [$this->createShare(null, IShare::TYPE_USER, $allPermssionsFiles, $user2, $user0, $user0, Constants::PERMISSION_ALL, null, null), 'File shares cannot have create or delete permissions', true]; + $data[] = [$this->createShare(null, IShare::TYPE_GROUP, $allPermssionsFiles, $group0, $user0, $user0, Constants::PERMISSION_READ | Constants::PERMISSION_CREATE, null, null), 'File shares cannot have create or delete permissions', true]; + $data[] = [$this->createShare(null, IShare::TYPE_LINK, $allPermssionsFiles, null, $user0, $user0, Constants::PERMISSION_READ | Constants::PERMISSION_DELETE, null, null), 'File shares cannot have create or delete permissions', true]; $allPermssions = $this->createMock(Folder::class); $allPermssions->method('isShareable')->willReturn(true); - $allPermssions->method('getPermissions')->willReturn(\OCP\Constants::PERMISSION_ALL); + $allPermssions->method('getPermissions')->willReturn(Constants::PERMISSION_ALL); $allPermssions->method('getId')->willReturn(108); $allPermssions->method('getOwner') ->willReturn($owner); @@ -983,7 +985,7 @@ class ManagerTest extends \Test\TestCase { ->willReturn(true); $remoteFile = $this->createMock(Folder::class); $remoteFile->method('isShareable')->willReturn(true); - $remoteFile->method('getPermissions')->willReturn(\OCP\Constants::PERMISSION_READ ^ \OCP\Constants::PERMISSION_UPDATE); + $remoteFile->method('getPermissions')->willReturn(Constants::PERMISSION_READ ^ Constants::PERMISSION_UPDATE); $remoteFile->method('getId')->willReturn(108); $remoteFile->method('getOwner') ->willReturn($owner); @@ -1032,7 +1034,7 @@ class ManagerTest extends \Test\TestCase { try { self::invokePrivate($this->manager, 'generalCreateChecks', [$share]); $thrown = false; - } catch (\OCP\Share\Exceptions\GenericShareException $e) { + } catch (GenericShareException $e) { $this->assertEquals($exceptionMessage, $e->getHint()); $thrown = true; } catch (\InvalidArgumentException $e) { @@ -1077,7 +1079,7 @@ class ManagerTest extends \Test\TestCase { * @dataProvider validateExpirationDateInternalProvider */ public function testValidateExpirationDateInternalInPast($shareType): void { - $this->expectException(\OCP\Share\Exceptions\GenericShareException::class); + $this->expectException(GenericShareException::class); $this->expectExceptionMessage('Expiration date is in the past'); // Expire date in the past @@ -1217,7 +1219,7 @@ class ManagerTest extends \Test\TestCase { * @dataProvider validateExpirationDateInternalProvider */ public function testValidateExpirationDateInternalEnforceTooFarIntoFuture($shareType): void { - $this->expectException(\OCP\Share\Exceptions\GenericShareException::class); + $this->expectException(GenericShareException::class); $this->expectExceptionMessage('Cannot set expiration date more than 3 days in the future'); $future = new \DateTime(); @@ -1278,7 +1280,7 @@ class ManagerTest extends \Test\TestCase { } $hookListener = $this->createMock(DummyShareManagerListener::class); - \OCP\Util::connectHook('\OC\Share', 'verifyExpirationDate', $hookListener, 'listener'); + Util::connectHook('\OC\Share', 'verifyExpirationDate', $hookListener, 'listener'); $hookListener->expects($this->once())->method('listener')->with($this->callback(function ($data) use ($future) { return $data['expirationDate'] == $future; })); @@ -1304,7 +1306,7 @@ class ManagerTest extends \Test\TestCase { $share->setExpirationDate($date); $hookListener = $this->createMock(DummyShareManagerListener::class); - \OCP\Util::connectHook('\OC\Share', 'verifyExpirationDate', $hookListener, 'listener'); + Util::connectHook('\OC\Share', 'verifyExpirationDate', $hookListener, 'listener'); $hookListener->expects($this->once())->method('listener')->with($this->callback(function ($data) use ($expected) { return $data['expirationDate'] == $expected && $data['passwordSet'] === false; })); @@ -1319,7 +1321,7 @@ class ManagerTest extends \Test\TestCase { */ public function testValidateExpirationDateInternalNoDateNoDefault($shareType): void { $hookListener = $this->createMock(DummyShareManagerListener::class); - \OCP\Util::connectHook('\OC\Share', 'verifyExpirationDate', $hookListener, 'listener'); + Util::connectHook('\OC\Share', 'verifyExpirationDate', $hookListener, 'listener'); $hookListener->expects($this->once())->method('listener')->with($this->callback(function ($data) { return $data['expirationDate'] === null && $data['passwordSet'] === true; })); @@ -1362,7 +1364,7 @@ class ManagerTest extends \Test\TestCase { } $hookListener = $this->createMock(DummyShareManagerListener::class); - \OCP\Util::connectHook('\OC\Share', 'verifyExpirationDate', $hookListener, 'listener'); + Util::connectHook('\OC\Share', 'verifyExpirationDate', $hookListener, 'listener'); $hookListener->expects($this->once())->method('listener')->with($this->callback(function ($data) use ($expected) { return $data['expirationDate'] == $expected; })); @@ -1404,7 +1406,7 @@ class ManagerTest extends \Test\TestCase { } $hookListener = $this->createMock(DummyShareManagerListener::class); - \OCP\Util::connectHook('\OC\Share', 'verifyExpirationDate', $hookListener, 'listener'); + Util::connectHook('\OC\Share', 'verifyExpirationDate', $hookListener, 'listener'); $hookListener->expects($this->once())->method('listener')->with($this->callback(function ($data) use ($expected) { return $data['expirationDate'] == $expected; })); @@ -1425,8 +1427,8 @@ class ManagerTest extends \Test\TestCase { $save = clone $nextWeek; $hookListener = $this->createMock(DummyShareManagerListener::class); - \OCP\Util::connectHook('\OC\Share', 'verifyExpirationDate', $hookListener, 'listener'); - $hookListener->expects($this->once())->method('listener')->willReturnCallback(function ($data) { + Util::connectHook('\OC\Share', 'verifyExpirationDate', $hookListener, 'listener'); + $hookListener->expects($this->once())->method('listener')->willReturnCallback(function ($data): void { $data['expirationDate']->sub(new \DateInterval('P2D')); }); @@ -1456,8 +1458,8 @@ class ManagerTest extends \Test\TestCase { $share->setExpirationDate($nextWeek); $hookListener = $this->createMock(DummyShareManagerListener::class); - \OCP\Util::connectHook('\OC\Share', 'verifyExpirationDate', $hookListener, 'listener'); - $hookListener->expects($this->once())->method('listener')->willReturnCallback(function ($data) { + Util::connectHook('\OC\Share', 'verifyExpirationDate', $hookListener, 'listener'); + $hookListener->expects($this->once())->method('listener')->willReturnCallback(function ($data): void { $data['accepted'] = false; $data['message'] = 'Invalid date!'; }); @@ -1493,7 +1495,7 @@ class ManagerTest extends \Test\TestCase { } public function testValidateExpirationDateInPast(): void { - $this->expectException(\OCP\Share\Exceptions\GenericShareException::class); + $this->expectException(GenericShareException::class); $this->expectExceptionMessage('Expiration date is in the past'); // Expire date in the past @@ -1579,7 +1581,7 @@ class ManagerTest extends \Test\TestCase { } public function testValidateExpirationDateEnforceTooFarIntoFuture(): void { - $this->expectException(\OCP\Share\Exceptions\GenericShareException::class); + $this->expectException(GenericShareException::class); $this->expectExceptionMessage('Cannot set expiration date more than 3 days in the future'); $future = new \DateTime(); @@ -1617,7 +1619,7 @@ class ManagerTest extends \Test\TestCase { ]); $hookListener = $this->createMock(DummyShareManagerListener::class); - \OCP\Util::connectHook('\OC\Share', 'verifyExpirationDate', $hookListener, 'listener'); + Util::connectHook('\OC\Share', 'verifyExpirationDate', $hookListener, 'listener'); $hookListener->expects($this->once())->method('listener')->with($this->callback(function ($data) use ($future) { return $data['expirationDate'] == $future; })); @@ -1640,7 +1642,7 @@ class ManagerTest extends \Test\TestCase { $share->setExpirationDate($date); $hookListener = $this->createMock(DummyShareManagerListener::class); - \OCP\Util::connectHook('\OC\Share', 'verifyExpirationDate', $hookListener, 'listener'); + Util::connectHook('\OC\Share', 'verifyExpirationDate', $hookListener, 'listener'); $hookListener->expects($this->once())->method('listener')->with($this->callback(function ($data) use ($expected) { return $data['expirationDate'] == $expected && $data['passwordSet'] === false; })); @@ -1652,7 +1654,7 @@ class ManagerTest extends \Test\TestCase { public function testValidateExpirationDateNoDateNoDefault(): void { $hookListener = $this->createMock(DummyShareManagerListener::class); - \OCP\Util::connectHook('\OC\Share', 'verifyExpirationDate', $hookListener, 'listener'); + Util::connectHook('\OC\Share', 'verifyExpirationDate', $hookListener, 'listener'); $hookListener->expects($this->once())->method('listener')->with($this->callback(function ($data) { return $data['expirationDate'] === null && $data['passwordSet'] === true; })); @@ -1681,7 +1683,7 @@ class ManagerTest extends \Test\TestCase { ]); $hookListener = $this->createMock(DummyShareManagerListener::class); - \OCP\Util::connectHook('\OC\Share', 'verifyExpirationDate', $hookListener, 'listener'); + Util::connectHook('\OC\Share', 'verifyExpirationDate', $hookListener, 'listener'); $hookListener->expects($this->once())->method('listener')->with($this->callback(function ($data) use ($expected) { return $data['expirationDate'] == $expected; })); @@ -1711,7 +1713,7 @@ class ManagerTest extends \Test\TestCase { ]); $hookListener = $this->createMock(DummyShareManagerListener::class); - \OCP\Util::connectHook('\OC\Share', 'verifyExpirationDate', $hookListener, 'listener'); + Util::connectHook('\OC\Share', 'verifyExpirationDate', $hookListener, 'listener'); $hookListener->expects($this->once())->method('listener')->with($this->callback(function ($data) use ($expected) { return $data['expirationDate'] == $expected; })); @@ -1742,7 +1744,7 @@ class ManagerTest extends \Test\TestCase { ]); $hookListener = $this->createMock(DummyShareManagerListener::class); - \OCP\Util::connectHook('\OC\Share', 'verifyExpirationDate', $hookListener, 'listener'); + Util::connectHook('\OC\Share', 'verifyExpirationDate', $hookListener, 'listener'); $hookListener->expects($this->once())->method('listener')->with($this->callback(function ($data) use ($expected) { return $data['expirationDate'] == $expected; })); @@ -1762,8 +1764,8 @@ class ManagerTest extends \Test\TestCase { $save->setTimezone(new \DateTimeZone(date_default_timezone_get())); $hookListener = $this->createMock(DummyShareManagerListener::class); - \OCP\Util::connectHook('\OC\Share', 'verifyExpirationDate', $hookListener, 'listener'); - $hookListener->expects($this->once())->method('listener')->willReturnCallback(function ($data) { + Util::connectHook('\OC\Share', 'verifyExpirationDate', $hookListener, 'listener'); + $hookListener->expects($this->once())->method('listener')->willReturnCallback(function ($data): void { $data['expirationDate']->sub(new \DateInterval('P2D')); }); @@ -1787,8 +1789,8 @@ class ManagerTest extends \Test\TestCase { $share->setExpirationDate($nextWeek); $hookListener = $this->createMock(DummyShareManagerListener::class); - \OCP\Util::connectHook('\OC\Share', 'verifyExpirationDate', $hookListener, 'listener'); - $hookListener->expects($this->once())->method('listener')->willReturnCallback(function ($data) { + Util::connectHook('\OC\Share', 'verifyExpirationDate', $hookListener, 'listener'); + $hookListener->expects($this->once())->method('listener')->willReturnCallback(function ($data): void { $data['accepted'] = false; $data['message'] = 'Invalid date!'; }); @@ -2204,7 +2206,7 @@ class ManagerTest extends \Test\TestCase { public function testFileLinkCreateChecksNoPublicUpload(): void { $share = $this->manager->newShare(); - $share->setPermissions(\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE); + $share->setPermissions(Constants::PERMISSION_CREATE | Constants::PERMISSION_UPDATE); $share->setNodeType('file'); $this->config @@ -2224,7 +2226,7 @@ class ManagerTest extends \Test\TestCase { $share = $this->manager->newShare(); - $share->setPermissions(\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE); + $share->setPermissions(Constants::PERMISSION_CREATE | Constants::PERMISSION_UPDATE); $share->setNodeType('folder'); $this->config @@ -2240,7 +2242,7 @@ class ManagerTest extends \Test\TestCase { public function testLinkCreateChecksPublicUpload(): void { $share = $this->manager->newShare(); - $share->setPermissions(\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE); + $share->setPermissions(Constants::PERMISSION_CREATE | Constants::PERMISSION_UPDATE); $share->setSharedWith('sharedWith'); $folder = $this->createMock(\OC\Files\Node\Folder::class); $share->setNode($folder); @@ -2259,7 +2261,7 @@ class ManagerTest extends \Test\TestCase { public function testLinkCreateChecksReadOnly(): void { $share = $this->manager->newShare(); - $share->setPermissions(\OCP\Constants::PERMISSION_READ); + $share->setPermissions(Constants::PERMISSION_READ); $share->setSharedWith('sharedWith'); $folder = $this->createMock(\OC\Files\Node\Folder::class); $share->setNode($folder); @@ -2460,7 +2462,7 @@ class ManagerTest extends \Test\TestCase { 'sharedWith', 'sharedBy', null, - \OCP\Constants::PERMISSION_ALL); + Constants::PERMISSION_ALL); $manager->expects($this->once()) ->method('canShare') @@ -2515,7 +2517,7 @@ class ManagerTest extends \Test\TestCase { 'sharedWith', 'sharedBy', null, - \OCP\Constants::PERMISSION_ALL); + Constants::PERMISSION_ALL); $manager->expects($this->once()) ->method('canShare') @@ -2578,7 +2580,7 @@ class ManagerTest extends \Test\TestCase { $share->setShareType(IShare::TYPE_LINK) ->setNode($path) ->setSharedBy('sharedBy') - ->setPermissions(\OCP\Constants::PERMISSION_ALL) + ->setPermissions(Constants::PERMISSION_ALL) ->setExpirationDate($date) ->setPassword('password'); @@ -2630,7 +2632,7 @@ class ManagerTest extends \Test\TestCase { ]; $this->dispatcher->expects($this->exactly(2)) ->method('dispatchTyped') - ->willReturnCallback(function ($event) use (&$calls, $date, $path) { + ->willReturnCallback(function ($event) use (&$calls, $date, $path): void { $expected = array_shift($calls); $this->assertInstanceOf($expected, $event); $share = $event->getShare(); @@ -2638,7 +2640,7 @@ class ManagerTest extends \Test\TestCase { $this->assertEquals(IShare::TYPE_LINK, $share->getShareType(), 'getShareType'); $this->assertEquals($path, $share->getNode(), 'getNode'); $this->assertEquals('sharedBy', $share->getSharedBy(), 'getSharedBy'); - $this->assertEquals(\OCP\Constants::PERMISSION_ALL, $share->getPermissions(), 'getPermissions'); + $this->assertEquals(Constants::PERMISSION_ALL, $share->getPermissions(), 'getPermissions'); $this->assertEquals($date, $share->getExpirationDate(), 'getExpirationDate'); $this->assertEquals('hashed', $share->getPassword(), 'getPassword'); $this->assertEquals('token', $share->getToken(), 'getToken'); @@ -2686,7 +2688,7 @@ class ManagerTest extends \Test\TestCase { $share->setShareType(IShare::TYPE_EMAIL) ->setNode($path) ->setSharedBy('sharedBy') - ->setPermissions(\OCP\Constants::PERMISSION_ALL); + ->setPermissions(Constants::PERMISSION_ALL); $manager->expects($this->once()) ->method('canShare') @@ -2727,7 +2729,7 @@ class ManagerTest extends \Test\TestCase { ]; $this->dispatcher->expects($this->exactly(2)) ->method('dispatchTyped') - ->willReturnCallback(function ($event) use (&$calls, $path) { + ->willReturnCallback(function ($event) use (&$calls, $path): void { $expected = array_shift($calls); $this->assertInstanceOf($expected, $event); $share = $event->getShare(); @@ -2735,7 +2737,7 @@ class ManagerTest extends \Test\TestCase { $this->assertEquals(IShare::TYPE_EMAIL, $share->getShareType(), 'getShareType'); $this->assertEquals($path, $share->getNode(), 'getNode'); $this->assertEquals('sharedBy', $share->getSharedBy(), 'getSharedBy'); - $this->assertEquals(\OCP\Constants::PERMISSION_ALL, $share->getPermissions(), 'getPermissions'); + $this->assertEquals(Constants::PERMISSION_ALL, $share->getPermissions(), 'getPermissions'); $this->assertNull($share->getExpirationDate(), 'getExpirationDate'); $this->assertNull($share->getPassword(), 'getPassword'); $this->assertEquals('token', $share->getToken(), 'getToken'); @@ -2784,7 +2786,7 @@ class ManagerTest extends \Test\TestCase { 'sharedWith', 'sharedBy', null, - \OCP\Constants::PERMISSION_ALL); + Constants::PERMISSION_ALL); $manager->expects($this->once()) ->method('canShare') @@ -2814,7 +2816,7 @@ class ManagerTest extends \Test\TestCase { ->method('dispatchTyped') ->with( $this->isInstanceOf(BeforeShareCreatedEvent::class) - )->willReturnCallback(function (BeforeShareCreatedEvent $e) { + )->willReturnCallback(function (BeforeShareCreatedEvent $e): void { $e->setError('I won\'t let you share!'); $e->stopPropagation(); } @@ -2863,7 +2865,7 @@ class ManagerTest extends \Test\TestCase { 'sharedWith', 'sharedBy', null, - \OCP\Constants::PERMISSION_ALL); + Constants::PERMISSION_ALL); $manager->expects($this->once()) ->method('canShare') @@ -3001,7 +3003,7 @@ class ManagerTest extends \Test\TestCase { * Simulate the deleteShare call. */ $manager->method('deleteShare') - ->willReturnCallback(function ($share) use (&$shares2) { + ->willReturnCallback(function ($share) use (&$shares2): void { for ($i = 0; $i < count($shares2); $i++) { if ($shares2[$i]->getId() === $share->getId()) { array_splice($shares2, $i, 1); @@ -3075,7 +3077,7 @@ class ManagerTest extends \Test\TestCase { ->method('getProviderForType') ->willReturnCallback(function ($shareType) use ($roomShareProvider) { if ($shareType !== IShare::TYPE_ROOM) { - throw new Exception\ProviderException(); + throw new ProviderException(); } return $roomShareProvider; @@ -3131,7 +3133,7 @@ class ManagerTest extends \Test\TestCase { public function testGetShareByTokenHideDisabledUser(): void { - $this->expectException(\OCP\Share\Exceptions\ShareNotFound::class); + $this->expectException(ShareNotFound::class); $this->expectExceptionMessage('The requested share comes from a disabled user'); $this->config @@ -3186,7 +3188,7 @@ class ManagerTest extends \Test\TestCase { public function testGetShareByTokenExpired(): void { - $this->expectException(\OCP\Share\Exceptions\ShareNotFound::class); + $this->expectException(ShareNotFound::class); $this->expectExceptionMessage('The requested share does not exist anymore'); $this->config @@ -3247,7 +3249,7 @@ class ManagerTest extends \Test\TestCase { public function testGetShareByTokenWithPublicLinksDisabled(): void { - $this->expectException(\OCP\Share\Exceptions\ShareNotFound::class); + $this->expectException(ShareNotFound::class); $this->config ->expects($this->once()) @@ -3269,7 +3271,7 @@ class ManagerTest extends \Test\TestCase { $share = $this->manager->newShare(); $share->setShareType(IShare::TYPE_LINK) - ->setPermissions(\OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE); + ->setPermissions(Constants::PERMISSION_READ | Constants::PERMISSION_CREATE | Constants::PERMISSION_UPDATE); $share->setSharedWith('sharedWith'); $folder = $this->createMock(\OC\Files\Node\Folder::class); $share->setNode($folder); @@ -3281,7 +3283,7 @@ class ManagerTest extends \Test\TestCase { $res = $this->manager->getShareByToken('validToken'); - $this->assertSame(\OCP\Constants::PERMISSION_READ, $res->getPermissions()); + $this->assertSame(Constants::PERMISSION_READ, $res->getPermissions()); } public function testCheckPasswordNoLinkShare(): void { @@ -3333,7 +3335,7 @@ class ManagerTest extends \Test\TestCase { $this->defaultProvider->expects($this->once()) ->method('update') - ->with($this->callback(function (\OCP\Share\IShare $share) { + ->with($this->callback(function (IShare $share) { return $share->getPassword() === 'newHash'; })); @@ -3469,14 +3471,14 @@ class ManagerTest extends \Test\TestCase { ->willReturn($share); $hookListener = $this->createMock(DummyShareManagerListener::class); - \OCP\Util::connectHook('OCP\Share', 'post_set_expiration_date', $hookListener, 'post'); + Util::connectHook('OCP\Share', 'post_set_expiration_date', $hookListener, 'post'); $hookListener->expects($this->never())->method('post'); $this->rootFolder->method('getUserFolder')->with('newUser')->willReturnSelf(); $this->rootFolder->method('getRelativePath')->with('/newUser/files/myPath')->willReturn('/myPath'); $hookListener2 = $this->createMock(DummyShareManagerListener::class); - \OCP\Util::connectHook('OCP\Share', 'post_update_permissions', $hookListener2, 'post'); + Util::connectHook('OCP\Share', 'post_update_permissions', $hookListener2, 'post'); $hookListener2->expects($this->once())->method('post')->with([ 'itemType' => 'file', 'itemSource' => 100, @@ -3527,11 +3529,11 @@ class ManagerTest extends \Test\TestCase { ->willReturn($share); $hookListener = $this->createMock(DummyShareManagerListener::class); - \OCP\Util::connectHook('OCP\Share', 'post_set_expiration_date', $hookListener, 'post'); + Util::connectHook('OCP\Share', 'post_set_expiration_date', $hookListener, 'post'); $hookListener->expects($this->never())->method('post'); $hookListener2 = $this->createMock(DummyShareManagerListener::class); - \OCP\Util::connectHook('OCP\Share', 'post_update_permissions', $hookListener2, 'post'); + Util::connectHook('OCP\Share', 'post_update_permissions', $hookListener2, 'post'); $hookListener2->expects($this->never())->method('post'); $manager->updateShare($share); @@ -3589,7 +3591,7 @@ class ManagerTest extends \Test\TestCase { ->willReturn($share); $hookListener = $this->createMock(DummyShareManagerListener::class); - \OCP\Util::connectHook('OCP\Share', 'post_set_expiration_date', $hookListener, 'post'); + Util::connectHook('OCP\Share', 'post_set_expiration_date', $hookListener, 'post'); $hookListener->expects($this->once())->method('post')->with([ 'itemType' => 'file', 'itemSource' => 100, @@ -3598,7 +3600,7 @@ class ManagerTest extends \Test\TestCase { ]); $hookListener2 = $this->createMock(DummyShareManagerListener::class); - \OCP\Util::connectHook('OCP\Share', 'post_update_password', $hookListener2, 'post'); + Util::connectHook('OCP\Share', 'post_update_password', $hookListener2, 'post'); $hookListener2->expects($this->once())->method('post')->with([ 'itemType' => 'file', 'itemSource' => 100, @@ -3608,7 +3610,7 @@ class ManagerTest extends \Test\TestCase { ]); $hookListener3 = $this->createMock(DummyShareManagerListener::class); - \OCP\Util::connectHook('OCP\Share', 'post_update_permissions', $hookListener3, 'post'); + Util::connectHook('OCP\Share', 'post_update_permissions', $hookListener3, 'post'); $hookListener3->expects($this->never())->method('post'); @@ -3670,15 +3672,15 @@ class ManagerTest extends \Test\TestCase { ->method('update'); $hookListener = $this->createMock(DummyShareManagerListener::class); - \OCP\Util::connectHook('OCP\Share', 'post_set_expiration_date', $hookListener, 'post'); + Util::connectHook('OCP\Share', 'post_set_expiration_date', $hookListener, 'post'); $hookListener->expects($this->never())->method('post'); $hookListener2 = $this->createMock(DummyShareManagerListener::class); - \OCP\Util::connectHook('OCP\Share', 'post_update_password', $hookListener2, 'post'); + Util::connectHook('OCP\Share', 'post_update_password', $hookListener2, 'post'); $hookListener2->expects($this->never())->method('post'); $hookListener3 = $this->createMock(DummyShareManagerListener::class); - \OCP\Util::connectHook('OCP\Share', 'post_update_permissions', $hookListener3, 'post'); + Util::connectHook('OCP\Share', 'post_update_permissions', $hookListener3, 'post'); $hookListener3->expects($this->never())->method('post'); $manager->updateShare($share); @@ -3699,7 +3701,7 @@ class ManagerTest extends \Test\TestCase { $originalShare = $this->manager->newShare(); $originalShare->setShareType(IShare::TYPE_EMAIL) - ->setPermissions(\OCP\Constants::PERMISSION_ALL); + ->setPermissions(Constants::PERMISSION_ALL); $tomorrow = new \DateTime(); $tomorrow->setTime(0, 0, 0); @@ -3718,7 +3720,7 @@ class ManagerTest extends \Test\TestCase { ->setPassword('password') ->setExpirationDate($tomorrow) ->setNode($file) - ->setPermissions(\OCP\Constants::PERMISSION_ALL); + ->setPermissions(Constants::PERMISSION_ALL); $manager->expects($this->once())->method('canShare')->willReturn(true); $manager->expects($this->once())->method('getShareById')->with('foo:42')->willReturn($originalShare); @@ -3739,7 +3741,7 @@ class ManagerTest extends \Test\TestCase { ->willReturn($share); $hookListener = $this->createMock(DummyShareManagerListener::class); - \OCP\Util::connectHook('OCP\Share', 'post_set_expiration_date', $hookListener, 'post'); + Util::connectHook('OCP\Share', 'post_set_expiration_date', $hookListener, 'post'); $hookListener->expects($this->once())->method('post')->with([ 'itemType' => 'file', 'itemSource' => 100, @@ -3748,7 +3750,7 @@ class ManagerTest extends \Test\TestCase { ]); $hookListener2 = $this->createMock(DummyShareManagerListener::class); - \OCP\Util::connectHook('OCP\Share', 'post_update_password', $hookListener2, 'post'); + Util::connectHook('OCP\Share', 'post_update_password', $hookListener2, 'post'); $hookListener2->expects($this->once())->method('post')->with([ 'itemType' => 'file', 'itemSource' => 100, @@ -3758,7 +3760,7 @@ class ManagerTest extends \Test\TestCase { ]); $hookListener3 = $this->createMock(DummyShareManagerListener::class); - \OCP\Util::connectHook('OCP\Share', 'post_update_permissions', $hookListener3, 'post'); + Util::connectHook('OCP\Share', 'post_update_permissions', $hookListener3, 'post'); $hookListener3->expects($this->never())->method('post'); $manager->updateShare($share); @@ -3779,7 +3781,7 @@ class ManagerTest extends \Test\TestCase { $originalShare = $this->manager->newShare(); $originalShare->setShareType(IShare::TYPE_EMAIL) - ->setPermissions(\OCP\Constants::PERMISSION_ALL) + ->setPermissions(Constants::PERMISSION_ALL) ->setPassword(null) ->setSendPasswordByTalk(false); @@ -3801,7 +3803,7 @@ class ManagerTest extends \Test\TestCase { ->setSendPasswordByTalk(true) ->setExpirationDate($tomorrow) ->setNode($file) - ->setPermissions(\OCP\Constants::PERMISSION_ALL); + ->setPermissions(Constants::PERMISSION_ALL); $manager->expects($this->once())->method('canShare')->willReturn(true); $manager->expects($this->once())->method('getShareById')->with('foo:42')->willReturn($originalShare); @@ -3822,7 +3824,7 @@ class ManagerTest extends \Test\TestCase { ->willReturn($share); $hookListener = $this->createMock(DummyShareManagerListener::class); - \OCP\Util::connectHook('OCP\Share', 'post_set_expiration_date', $hookListener, 'post'); + Util::connectHook('OCP\Share', 'post_set_expiration_date', $hookListener, 'post'); $hookListener->expects($this->once())->method('post')->with([ 'itemType' => 'file', 'itemSource' => 100, @@ -3831,7 +3833,7 @@ class ManagerTest extends \Test\TestCase { ]); $hookListener2 = $this->createMock(DummyShareManagerListener::class); - \OCP\Util::connectHook('OCP\Share', 'post_update_password', $hookListener2, 'post'); + Util::connectHook('OCP\Share', 'post_update_password', $hookListener2, 'post'); $hookListener2->expects($this->once())->method('post')->with([ 'itemType' => 'file', 'itemSource' => 100, @@ -3841,7 +3843,7 @@ class ManagerTest extends \Test\TestCase { ]); $hookListener3 = $this->createMock(DummyShareManagerListener::class); - \OCP\Util::connectHook('OCP\Share', 'post_update_permissions', $hookListener3, 'post'); + Util::connectHook('OCP\Share', 'post_update_permissions', $hookListener3, 'post'); $hookListener3->expects($this->never())->method('post'); $manager->updateShare($share); @@ -3862,7 +3864,7 @@ class ManagerTest extends \Test\TestCase { $originalShare = $this->manager->newShare(); $originalShare->setShareType(IShare::TYPE_EMAIL) - ->setPermissions(\OCP\Constants::PERMISSION_ALL) + ->setPermissions(Constants::PERMISSION_ALL) ->setPassword('anotherPasswordHash') ->setSendPasswordByTalk(false); @@ -3884,7 +3886,7 @@ class ManagerTest extends \Test\TestCase { ->setSendPasswordByTalk(true) ->setExpirationDate($tomorrow) ->setNode($file) - ->setPermissions(\OCP\Constants::PERMISSION_ALL); + ->setPermissions(Constants::PERMISSION_ALL); $manager->expects($this->once())->method('canShare')->willReturn(true); $manager->expects($this->once())->method('getShareById')->with('foo:42')->willReturn($originalShare); @@ -3910,7 +3912,7 @@ class ManagerTest extends \Test\TestCase { ->willReturn($share); $hookListener = $this->createMock(DummyShareManagerListener::class); - \OCP\Util::connectHook('OCP\Share', 'post_set_expiration_date', $hookListener, 'post'); + Util::connectHook('OCP\Share', 'post_set_expiration_date', $hookListener, 'post'); $hookListener->expects($this->once())->method('post')->with([ 'itemType' => 'file', 'itemSource' => 100, @@ -3919,7 +3921,7 @@ class ManagerTest extends \Test\TestCase { ]); $hookListener2 = $this->createMock(DummyShareManagerListener::class); - \OCP\Util::connectHook('OCP\Share', 'post_update_password', $hookListener2, 'post'); + Util::connectHook('OCP\Share', 'post_update_password', $hookListener2, 'post'); $hookListener2->expects($this->once())->method('post')->with([ 'itemType' => 'file', 'itemSource' => 100, @@ -3929,7 +3931,7 @@ class ManagerTest extends \Test\TestCase { ]); $hookListener3 = $this->createMock(DummyShareManagerListener::class); - \OCP\Util::connectHook('OCP\Share', 'post_update_permissions', $hookListener3, 'post'); + Util::connectHook('OCP\Share', 'post_update_permissions', $hookListener3, 'post'); $hookListener3->expects($this->never())->method('post'); $manager->updateShare($share); @@ -3953,7 +3955,7 @@ class ManagerTest extends \Test\TestCase { $originalShare = $this->manager->newShare(); $originalShare->setShareType(IShare::TYPE_EMAIL) - ->setPermissions(\OCP\Constants::PERMISSION_ALL) + ->setPermissions(Constants::PERMISSION_ALL) ->setPassword(null) ->setSendPasswordByTalk(false); @@ -3975,7 +3977,7 @@ class ManagerTest extends \Test\TestCase { ->setSendPasswordByTalk(true) ->setExpirationDate($tomorrow) ->setNode($file) - ->setPermissions(\OCP\Constants::PERMISSION_ALL); + ->setPermissions(Constants::PERMISSION_ALL); $manager->expects($this->once())->method('canShare')->willReturn(true); $manager->expects($this->once())->method('getShareById')->with('foo:42')->willReturn($originalShare); @@ -3993,15 +3995,15 @@ class ManagerTest extends \Test\TestCase { ->method('update'); $hookListener = $this->createMock(DummyShareManagerListener::class); - \OCP\Util::connectHook('OCP\Share', 'post_set_expiration_date', $hookListener, 'post'); + Util::connectHook('OCP\Share', 'post_set_expiration_date', $hookListener, 'post'); $hookListener->expects($this->never())->method('post'); $hookListener2 = $this->createMock(DummyShareManagerListener::class); - \OCP\Util::connectHook('OCP\Share', 'post_update_password', $hookListener2, 'post'); + Util::connectHook('OCP\Share', 'post_update_password', $hookListener2, 'post'); $hookListener2->expects($this->never())->method('post'); $hookListener3 = $this->createMock(DummyShareManagerListener::class); - \OCP\Util::connectHook('OCP\Share', 'post_update_permissions', $hookListener3, 'post'); + Util::connectHook('OCP\Share', 'post_update_permissions', $hookListener3, 'post'); $hookListener3->expects($this->never())->method('post'); $manager->updateShare($share); @@ -4026,7 +4028,7 @@ class ManagerTest extends \Test\TestCase { $originalShare = $this->manager->newShare(); $originalShare->setShareType(IShare::TYPE_EMAIL) - ->setPermissions(\OCP\Constants::PERMISSION_ALL) + ->setPermissions(Constants::PERMISSION_ALL) ->setPassword('passwordHash') ->setSendPasswordByTalk(false); @@ -4048,7 +4050,7 @@ class ManagerTest extends \Test\TestCase { ->setSendPasswordByTalk(true) ->setExpirationDate($tomorrow) ->setNode($file) - ->setPermissions(\OCP\Constants::PERMISSION_ALL); + ->setPermissions(Constants::PERMISSION_ALL); $manager->expects($this->once())->method('canShare')->willReturn(true); $manager->expects($this->once())->method('getShareById')->with('foo:42')->willReturn($originalShare); @@ -4066,15 +4068,15 @@ class ManagerTest extends \Test\TestCase { ->method('update'); $hookListener = $this->createMock(DummyShareManagerListener::class); - \OCP\Util::connectHook('OCP\Share', 'post_set_expiration_date', $hookListener, 'post'); + Util::connectHook('OCP\Share', 'post_set_expiration_date', $hookListener, 'post'); $hookListener->expects($this->never())->method('post'); $hookListener2 = $this->createMock(DummyShareManagerListener::class); - \OCP\Util::connectHook('OCP\Share', 'post_update_password', $hookListener2, 'post'); + Util::connectHook('OCP\Share', 'post_update_password', $hookListener2, 'post'); $hookListener2->expects($this->never())->method('post'); $hookListener3 = $this->createMock(DummyShareManagerListener::class); - \OCP\Util::connectHook('OCP\Share', 'post_update_permissions', $hookListener3, 'post'); + Util::connectHook('OCP\Share', 'post_update_permissions', $hookListener3, 'post'); $hookListener3->expects($this->never())->method('post'); $manager->updateShare($share); @@ -4099,7 +4101,7 @@ class ManagerTest extends \Test\TestCase { $originalShare = $this->manager->newShare(); $originalShare->setShareType(IShare::TYPE_EMAIL) - ->setPermissions(\OCP\Constants::PERMISSION_ALL) + ->setPermissions(Constants::PERMISSION_ALL) ->setPassword('passwordHash') ->setSendPasswordByTalk(false); @@ -4121,7 +4123,7 @@ class ManagerTest extends \Test\TestCase { ->setSendPasswordByTalk(true) ->setExpirationDate($tomorrow) ->setNode($file) - ->setPermissions(\OCP\Constants::PERMISSION_ALL); + ->setPermissions(Constants::PERMISSION_ALL); $manager->expects($this->once())->method('canShare')->willReturn(true); $manager->expects($this->once())->method('getShareById')->with('foo:42')->willReturn($originalShare); @@ -4139,15 +4141,15 @@ class ManagerTest extends \Test\TestCase { ->method('update'); $hookListener = $this->createMock(DummyShareManagerListener::class); - \OCP\Util::connectHook('OCP\Share', 'post_set_expiration_date', $hookListener, 'post'); + Util::connectHook('OCP\Share', 'post_set_expiration_date', $hookListener, 'post'); $hookListener->expects($this->never())->method('post'); $hookListener2 = $this->createMock(DummyShareManagerListener::class); - \OCP\Util::connectHook('OCP\Share', 'post_update_password', $hookListener2, 'post'); + Util::connectHook('OCP\Share', 'post_update_password', $hookListener2, 'post'); $hookListener2->expects($this->never())->method('post'); $hookListener3 = $this->createMock(DummyShareManagerListener::class); - \OCP\Util::connectHook('OCP\Share', 'post_update_permissions', $hookListener3, 'post'); + Util::connectHook('OCP\Share', 'post_update_permissions', $hookListener3, 'post'); $hookListener3->expects($this->never())->method('post'); $manager->updateShare($share); @@ -4172,7 +4174,7 @@ class ManagerTest extends \Test\TestCase { $originalShare = $this->manager->newShare(); $originalShare->setShareType(IShare::TYPE_EMAIL) - ->setPermissions(\OCP\Constants::PERMISSION_ALL) + ->setPermissions(Constants::PERMISSION_ALL) ->setPassword('password') ->setSendPasswordByTalk(false); @@ -4194,7 +4196,7 @@ class ManagerTest extends \Test\TestCase { ->setSendPasswordByTalk(true) ->setExpirationDate($tomorrow) ->setNode($file) - ->setPermissions(\OCP\Constants::PERMISSION_ALL); + ->setPermissions(Constants::PERMISSION_ALL); $manager->expects($this->once())->method('canShare')->willReturn(true); $manager->expects($this->once())->method('getShareById')->with('foo:42')->willReturn($originalShare); @@ -4214,15 +4216,15 @@ class ManagerTest extends \Test\TestCase { ->method('update'); $hookListener = $this->createMock(DummyShareManagerListener::class); - \OCP\Util::connectHook('OCP\Share', 'post_set_expiration_date', $hookListener, 'post'); + Util::connectHook('OCP\Share', 'post_set_expiration_date', $hookListener, 'post'); $hookListener->expects($this->never())->method('post'); $hookListener2 = $this->createMock(DummyShareManagerListener::class); - \OCP\Util::connectHook('OCP\Share', 'post_update_password', $hookListener2, 'post'); + Util::connectHook('OCP\Share', 'post_update_password', $hookListener2, 'post'); $hookListener2->expects($this->never())->method('post'); $hookListener3 = $this->createMock(DummyShareManagerListener::class); - \OCP\Util::connectHook('OCP\Share', 'post_update_permissions', $hookListener3, 'post'); + Util::connectHook('OCP\Share', 'post_update_permissions', $hookListener3, 'post'); $hookListener3->expects($this->never())->method('post'); $manager->updateShare($share); @@ -4246,7 +4248,7 @@ class ManagerTest extends \Test\TestCase { $originalShare = $this->manager->newShare(); $originalShare->setShareType(IShare::TYPE_EMAIL) - ->setPermissions(\OCP\Constants::PERMISSION_ALL) + ->setPermissions(Constants::PERMISSION_ALL) ->setPassword('passwordHash') ->setSendPasswordByTalk(true); @@ -4268,7 +4270,7 @@ class ManagerTest extends \Test\TestCase { ->setSendPasswordByTalk(false) ->setExpirationDate($tomorrow) ->setNode($file) - ->setPermissions(\OCP\Constants::PERMISSION_ALL); + ->setPermissions(Constants::PERMISSION_ALL); $manager->expects($this->once())->method('canShare')->willReturn(true); $manager->expects($this->once())->method('getShareById')->with('foo:42')->willReturn($originalShare); @@ -4288,15 +4290,15 @@ class ManagerTest extends \Test\TestCase { ->method('update'); $hookListener = $this->createMock(DummyShareManagerListener::class); - \OCP\Util::connectHook('OCP\Share', 'post_set_expiration_date', $hookListener, 'post'); + Util::connectHook('OCP\Share', 'post_set_expiration_date', $hookListener, 'post'); $hookListener->expects($this->never())->method('post'); $hookListener2 = $this->createMock(DummyShareManagerListener::class); - \OCP\Util::connectHook('OCP\Share', 'post_update_password', $hookListener2, 'post'); + Util::connectHook('OCP\Share', 'post_update_password', $hookListener2, 'post'); $hookListener2->expects($this->never())->method('post'); $hookListener3 = $this->createMock(DummyShareManagerListener::class); - \OCP\Util::connectHook('OCP\Share', 'post_update_permissions', $hookListener3, 'post'); + Util::connectHook('OCP\Share', 'post_update_permissions', $hookListener3, 'post'); $hookListener3->expects($this->never())->method('post'); $manager->updateShare($share); @@ -4320,7 +4322,7 @@ class ManagerTest extends \Test\TestCase { $originalShare = $this->manager->newShare(); $originalShare->setShareType(IShare::TYPE_EMAIL) - ->setPermissions(\OCP\Constants::PERMISSION_ALL) + ->setPermissions(Constants::PERMISSION_ALL) ->setPassword('passwordHash') ->setSendPasswordByTalk(true); @@ -4342,7 +4344,7 @@ class ManagerTest extends \Test\TestCase { ->setSendPasswordByTalk(false) ->setExpirationDate($tomorrow) ->setNode($file) - ->setPermissions(\OCP\Constants::PERMISSION_ALL); + ->setPermissions(Constants::PERMISSION_ALL); $manager->expects($this->once())->method('canShare')->willReturn(true); $manager->expects($this->once())->method('getShareById')->with('foo:42')->willReturn($originalShare); @@ -4362,15 +4364,15 @@ class ManagerTest extends \Test\TestCase { ->method('update'); $hookListener = $this->createMock(DummyShareManagerListener::class); - \OCP\Util::connectHook('OCP\Share', 'post_set_expiration_date', $hookListener, 'post'); + Util::connectHook('OCP\Share', 'post_set_expiration_date', $hookListener, 'post'); $hookListener->expects($this->never())->method('post'); $hookListener2 = $this->createMock(DummyShareManagerListener::class); - \OCP\Util::connectHook('OCP\Share', 'post_update_password', $hookListener2, 'post'); + Util::connectHook('OCP\Share', 'post_update_password', $hookListener2, 'post'); $hookListener2->expects($this->never())->method('post'); $hookListener3 = $this->createMock(DummyShareManagerListener::class); - \OCP\Util::connectHook('OCP\Share', 'post_update_permissions', $hookListener3, 'post'); + Util::connectHook('OCP\Share', 'post_update_permissions', $hookListener3, 'post'); $hookListener3->expects($this->never())->method('post'); $manager->updateShare($share); @@ -4483,7 +4485,7 @@ class ManagerTest extends \Test\TestCase { if ($id === IShare::TYPE_USER) { return true; } - throw new Exception\ProviderException(); + throw new ProviderException(); }); $manager = $this->createManager($factory); @@ -4905,7 +4907,7 @@ class DummyFactory implements IProviderFactory { /** @var IShareProvider */ protected $provider; - public function __construct(\OCP\IServerContainer $serverContainer) { + public function __construct(IServerContainer $serverContainer) { } /** diff --git a/tests/lib/Share20/ShareByMailProviderTest.php b/tests/lib/Share20/ShareByMailProviderTest.php index bc8e9e53df0..de4dc1a820c 100644 --- a/tests/lib/Share20/ShareByMailProviderTest.php +++ b/tests/lib/Share20/ShareByMailProviderTest.php @@ -24,6 +24,7 @@ use OCP\IUserManager; use OCP\Mail\IMailer; use OCP\Security\IHasher; use OCP\Security\ISecureRandom; +use OCP\Server; use OCP\Share\IShare; use PHPUnit\Framework\MockObject\MockObject; use Psr\Log\LoggerInterface; @@ -85,7 +86,7 @@ class ShareByMailProviderTest extends TestCase { private $settingsManager; protected function setUp(): void { - $this->dbConn = \OC::$server->getDatabaseConnection(); + $this->dbConn = Server::get(IDBConnection::class); $this->userManager = $this->createMock(IUserManager::class); $this->rootFolder = $this->createMock(IRootFolder::class); $this->mailer = $this->createMock(IMailer::class); diff --git a/tests/lib/Share20/ShareTest.php b/tests/lib/Share20/ShareTest.php index 72f3b46190c..e95112f9abc 100644 --- a/tests/lib/Share20/ShareTest.php +++ b/tests/lib/Share20/ShareTest.php @@ -7,8 +7,10 @@ namespace Test\Share20; +use OC\Share20\Share; use OCP\Files\IRootFolder; use OCP\IUserManager; +use OCP\Share\Exceptions\IllegalIDChangeException; use PHPUnit\Framework\MockObject\MockObject; /** @@ -27,7 +29,7 @@ class ShareTest extends \Test\TestCase { protected function setUp(): void { $this->rootFolder = $this->createMock(IRootFolder::class); $this->userManager = $this->createMock(IUserManager::class); - $this->share = new \OC\Share20\Share($this->rootFolder, $this->userManager); + $this->share = new Share($this->rootFolder, $this->userManager); } @@ -51,7 +53,7 @@ class ShareTest extends \Test\TestCase { public function testSetIdOnce(): void { - $this->expectException(\OCP\Share\Exceptions\IllegalIDChangeException::class); + $this->expectException(IllegalIDChangeException::class); $this->expectExceptionMessage('Not allowed to assign a new internal id to a share'); $this->share->setId('foo'); @@ -75,7 +77,7 @@ class ShareTest extends \Test\TestCase { public function testSetProviderIdOnce(): void { - $this->expectException(\OCP\Share\Exceptions\IllegalIDChangeException::class); + $this->expectException(IllegalIDChangeException::class); $this->expectExceptionMessage('Not allowed to assign a new provider id to a share'); $this->share->setProviderId('foo'); diff --git a/tests/lib/SubAdminTest.php b/tests/lib/SubAdminTest.php index 4cda08a2945..ce5410e9b88 100644 --- a/tests/lib/SubAdminTest.php +++ b/tests/lib/SubAdminTest.php @@ -7,9 +7,14 @@ namespace Test; +use OC\SubAdmin; use OCP\EventDispatcher\IEventDispatcher; use OCP\Group\Events\SubAdminAddedEvent; use OCP\Group\Events\SubAdminRemovedEvent; +use OCP\IDBConnection; +use OCP\IGroupManager; +use OCP\IUserManager; +use OCP\Server; /** * @group DB @@ -39,10 +44,10 @@ class SubAdminTest extends \Test\TestCase { $this->users = []; $this->groups = []; - $this->userManager = \OC::$server->getUserManager(); - $this->groupManager = \OC::$server->getGroupManager(); - $this->dbConn = \OC::$server->getDatabaseConnection(); - $this->eventDispatcher = \OC::$server->get(IEventDispatcher::class); + $this->userManager = Server::get(IUserManager::class); + $this->groupManager = Server::get(IGroupManager::class); + $this->dbConn = Server::get(IDBConnection::class); + $this->eventDispatcher = Server::get(IEventDispatcher::class); // Create 3 users and 3 groups for ($i = 0; $i < 3; $i++) { @@ -95,7 +100,7 @@ class SubAdminTest extends \Test\TestCase { } public function testCreateSubAdmin(): void { - $subAdmin = new \OC\SubAdmin($this->userManager, $this->groupManager, $this->dbConn, $this->eventDispatcher); + $subAdmin = new SubAdmin($this->userManager, $this->groupManager, $this->dbConn, $this->eventDispatcher); $subAdmin->createSubAdmin($this->users[0], $this->groups[0]); // Look for subadmin in the database @@ -120,7 +125,7 @@ class SubAdminTest extends \Test\TestCase { } public function testDeleteSubAdmin(): void { - $subAdmin = new \OC\SubAdmin($this->userManager, $this->groupManager, $this->dbConn, $this->eventDispatcher); + $subAdmin = new SubAdmin($this->userManager, $this->groupManager, $this->dbConn, $this->eventDispatcher); $subAdmin->createSubAdmin($this->users[0], $this->groups[0]); $subAdmin->deleteSubAdmin($this->users[0], $this->groups[0]); @@ -136,7 +141,7 @@ class SubAdminTest extends \Test\TestCase { } public function testGetSubAdminsGroups(): void { - $subAdmin = new \OC\SubAdmin($this->userManager, $this->groupManager, $this->dbConn, $this->eventDispatcher); + $subAdmin = new SubAdmin($this->userManager, $this->groupManager, $this->dbConn, $this->eventDispatcher); $subAdmin->createSubAdmin($this->users[0], $this->groups[0]); $subAdmin->createSubAdmin($this->users[0], $this->groups[1]); @@ -152,7 +157,7 @@ class SubAdminTest extends \Test\TestCase { } public function testGetGroupsSubAdmins(): void { - $subAdmin = new \OC\SubAdmin($this->userManager, $this->groupManager, $this->dbConn, $this->eventDispatcher); + $subAdmin = new SubAdmin($this->userManager, $this->groupManager, $this->dbConn, $this->eventDispatcher); $subAdmin->createSubAdmin($this->users[0], $this->groups[0]); $subAdmin->createSubAdmin($this->users[1], $this->groups[0]); @@ -168,7 +173,7 @@ class SubAdminTest extends \Test\TestCase { } public function testGetAllSubAdmin(): void { - $subAdmin = new \OC\SubAdmin($this->userManager, $this->groupManager, $this->dbConn, $this->eventDispatcher); + $subAdmin = new SubAdmin($this->userManager, $this->groupManager, $this->dbConn, $this->eventDispatcher); $subAdmin->createSubAdmin($this->users[0], $this->groups[0]); $subAdmin->createSubAdmin($this->users[1], $this->groups[1]); @@ -183,7 +188,7 @@ class SubAdminTest extends \Test\TestCase { } public function testIsSubAdminofGroup(): void { - $subAdmin = new \OC\SubAdmin($this->userManager, $this->groupManager, $this->dbConn, $this->eventDispatcher); + $subAdmin = new SubAdmin($this->userManager, $this->groupManager, $this->dbConn, $this->eventDispatcher); $subAdmin->createSubAdmin($this->users[0], $this->groups[0]); $this->assertTrue($subAdmin->isSubAdminOfGroup($this->users[0], $this->groups[0])); @@ -194,7 +199,7 @@ class SubAdminTest extends \Test\TestCase { } public function testIsSubAdmin(): void { - $subAdmin = new \OC\SubAdmin($this->userManager, $this->groupManager, $this->dbConn, $this->eventDispatcher); + $subAdmin = new SubAdmin($this->userManager, $this->groupManager, $this->dbConn, $this->eventDispatcher); $subAdmin->createSubAdmin($this->users[0], $this->groups[0]); $this->assertTrue($subAdmin->isSubAdmin($this->users[0])); @@ -204,14 +209,14 @@ class SubAdminTest extends \Test\TestCase { } public function testIsSubAdminAsAdmin(): void { - $subAdmin = new \OC\SubAdmin($this->userManager, $this->groupManager, $this->dbConn, $this->eventDispatcher); + $subAdmin = new SubAdmin($this->userManager, $this->groupManager, $this->dbConn, $this->eventDispatcher); $this->groupManager->get('admin')->addUser($this->users[0]); $this->assertTrue($subAdmin->isSubAdmin($this->users[0])); } public function testIsUserAccessible(): void { - $subAdmin = new \OC\SubAdmin($this->userManager, $this->groupManager, $this->dbConn, $this->eventDispatcher); + $subAdmin = new SubAdmin($this->userManager, $this->groupManager, $this->dbConn, $this->eventDispatcher); $this->groups[0]->addUser($this->users[1]); $this->groups[1]->addUser($this->users[1]); $this->groups[1]->addUser($this->users[2]); @@ -227,12 +232,12 @@ class SubAdminTest extends \Test\TestCase { } public function testIsUserAccessibleAsUser(): void { - $subAdmin = new \OC\SubAdmin($this->userManager, $this->groupManager, $this->dbConn, $this->eventDispatcher); + $subAdmin = new SubAdmin($this->userManager, $this->groupManager, $this->dbConn, $this->eventDispatcher); $this->assertFalse($subAdmin->isUserAccessible($this->users[0], $this->users[1])); } public function testIsUserAccessibleAdmin(): void { - $subAdmin = new \OC\SubAdmin($this->userManager, $this->groupManager, $this->dbConn, $this->eventDispatcher); + $subAdmin = new SubAdmin($this->userManager, $this->groupManager, $this->dbConn, $this->eventDispatcher); $subAdmin->createSubAdmin($this->users[0], $this->groups[0]); $this->groupManager->get('admin')->addUser($this->users[1]); @@ -240,7 +245,7 @@ class SubAdminTest extends \Test\TestCase { } public function testPostDeleteUser(): void { - $subAdmin = new \OC\SubAdmin($this->userManager, $this->groupManager, $this->dbConn, $this->eventDispatcher); + $subAdmin = new SubAdmin($this->userManager, $this->groupManager, $this->dbConn, $this->eventDispatcher); $user = array_shift($this->users); foreach ($this->groups as $group) { @@ -252,7 +257,7 @@ class SubAdminTest extends \Test\TestCase { } public function testPostDeleteGroup(): void { - $subAdmin = new \OC\SubAdmin($this->userManager, $this->groupManager, $this->dbConn, $this->eventDispatcher); + $subAdmin = new SubAdmin($this->userManager, $this->groupManager, $this->dbConn, $this->eventDispatcher); $group = array_shift($this->groups); foreach ($this->users as $user) { @@ -264,20 +269,20 @@ class SubAdminTest extends \Test\TestCase { } public function testHooks(): void { - $subAdmin = new \OC\SubAdmin($this->userManager, $this->groupManager, $this->dbConn, $this->eventDispatcher); + $subAdmin = new SubAdmin($this->userManager, $this->groupManager, $this->dbConn, $this->eventDispatcher); $test = $this; $u = $this->users[0]; $g = $this->groups[0]; $count = 0; - $this->eventDispatcher->addListener(SubAdminAddedEvent::class, function (SubAdminAddedEvent $event) use ($test, $u, $g, &$count) { + $this->eventDispatcher->addListener(SubAdminAddedEvent::class, function (SubAdminAddedEvent $event) use ($test, $u, $g, &$count): void { $test->assertEquals($u->getUID(), $event->getUser()->getUID()); $test->assertEquals($g->getGID(), $event->getGroup()->getGID()); $count++; }); - $this->eventDispatcher->addListener(SubAdminRemovedEvent::class, function ($event) use ($test, $u, $g, &$count) { + $this->eventDispatcher->addListener(SubAdminRemovedEvent::class, function ($event) use ($test, $u, $g, &$count): void { $test->assertEquals($u->getUID(), $event->getUser()->getUID()); $test->assertEquals($g->getGID(), $event->getGroup()->getGID()); $count++; diff --git a/tests/lib/Support/Subscription/DummySubscription.php b/tests/lib/Support/Subscription/DummySubscription.php index ca1644c91f5..4513bf278f6 100644 --- a/tests/lib/Support/Subscription/DummySubscription.php +++ b/tests/lib/Support/Subscription/DummySubscription.php @@ -9,24 +9,20 @@ declare(strict_types=1); namespace Test\Support\Subscription; -class DummySubscription implements \OCP\Support\Subscription\ISubscription { - /** @var bool */ - private $hasValidSubscription; - /** @var bool */ - private $hasExtendedSupport; - /** @var bool */ - private $isHardUserLimitReached; +use OCP\Support\Subscription\ISubscription; +class DummySubscription implements ISubscription { /** * DummySubscription constructor. * * @param bool $hasValidSubscription * @param bool $hasExtendedSupport */ - public function __construct(bool $hasValidSubscription, bool $hasExtendedSupport, bool $isHardUserLimitReached) { - $this->hasValidSubscription = $hasValidSubscription; - $this->hasExtendedSupport = $hasExtendedSupport; - $this->isHardUserLimitReached = $isHardUserLimitReached; + public function __construct( + private bool $hasValidSubscription, + private bool $hasExtendedSupport, + private bool $isHardUserLimitReached, + ) { } /** diff --git a/tests/lib/Support/Subscription/RegistryTest.php b/tests/lib/Support/Subscription/RegistryTest.php index 08a216294d6..3f2b9f5032f 100644 --- a/tests/lib/Support/Subscription/RegistryTest.php +++ b/tests/lib/Support/Subscription/RegistryTest.php @@ -14,6 +14,7 @@ use OCP\IGroupManager; use OCP\IServerContainer; use OCP\IUserManager; use OCP\Notification\IManager; +use OCP\Support\Subscription\Exception\AlreadyRegisteredException; use OCP\Support\Subscription\ISubscription; use OCP\Support\Subscription\ISupportedApps; use PHPUnit\Framework\MockObject\MockObject; @@ -58,7 +59,7 @@ class RegistryTest extends TestCase { public function testDoubleRegistration(): void { - $this->expectException(\OCP\Support\Subscription\Exception\AlreadyRegisteredException::class); + $this->expectException(AlreadyRegisteredException::class); /* @var ISubscription $subscription1 */ $subscription1 = $this->createMock(ISubscription::class); diff --git a/tests/lib/SystemTag/SystemTagManagerTest.php b/tests/lib/SystemTag/SystemTagManagerTest.php index 4627ebbf546..806c3fea240 100644 --- a/tests/lib/SystemTag/SystemTagManagerTest.php +++ b/tests/lib/SystemTag/SystemTagManagerTest.php @@ -16,8 +16,11 @@ use OCP\IDBConnection; use OCP\IGroupManager; use OCP\IUser; use OCP\IUserSession; +use OCP\Server; use OCP\SystemTag\ISystemTag; use OCP\SystemTag\ISystemTagManager; +use OCP\SystemTag\TagAlreadyExistsException; +use OCP\SystemTag\TagNotFoundException; use Test\TestCase; /** @@ -37,7 +40,7 @@ class SystemTagManagerTest extends TestCase { protected function setUp(): void { parent::setUp(); - $this->connection = \OC::$server->getDatabaseConnection(); + $this->connection = Server::get(IDBConnection::class); $this->dispatcher = $this->createMock(IEventDispatcher::class); $this->groupManager = $this->createMock(IGroupManager::class); @@ -239,7 +242,7 @@ class SystemTagManagerTest extends TestCase { * @dataProvider oneTagMultipleFlagsProvider */ public function testCreateDuplicate($name, $userVisible, $userAssignable): void { - $this->expectException(\OCP\SystemTag\TagAlreadyExistsException::class); + $this->expectException(TagAlreadyExistsException::class); try { $this->tagManager->createTag($name, $userVisible, $userAssignable); @@ -278,14 +281,14 @@ class SystemTagManagerTest extends TestCase { public function testGetNonExistingTag(): void { - $this->expectException(\OCP\SystemTag\TagNotFoundException::class); + $this->expectException(TagNotFoundException::class); $this->tagManager->getTag('nonexist', false, false); } public function testGetNonExistingTagsById(): void { - $this->expectException(\OCP\SystemTag\TagNotFoundException::class); + $this->expectException(TagNotFoundException::class); $tag1 = $this->tagManager->createTag('one', true, false); $this->tagManager->getTagsByIds([$tag1->getId(), 100, 101]); @@ -360,7 +363,7 @@ class SystemTagManagerTest extends TestCase { * @dataProvider updateTagProvider */ public function testUpdateTagDuplicate($tagCreate, $tagUpdated): void { - $this->expectException(\OCP\SystemTag\TagAlreadyExistsException::class); + $this->expectException(TagAlreadyExistsException::class); $this->tagManager->createTag( $tagCreate[0], @@ -396,7 +399,7 @@ class SystemTagManagerTest extends TestCase { public function testDeleteNonExistingTag(): void { - $this->expectException(\OCP\SystemTag\TagNotFoundException::class); + $this->expectException(TagNotFoundException::class); $this->tagManager->deleteTags([100]); } diff --git a/tests/lib/SystemTag/SystemTagObjectMapperTest.php b/tests/lib/SystemTag/SystemTagObjectMapperTest.php index 3569c98b5bc..a43bda3b659 100644 --- a/tests/lib/SystemTag/SystemTagObjectMapperTest.php +++ b/tests/lib/SystemTag/SystemTagObjectMapperTest.php @@ -13,6 +13,7 @@ use OC\SystemTag\SystemTagManager; use OC\SystemTag\SystemTagObjectMapper; use OCP\EventDispatcher\IEventDispatcher; use OCP\IDBConnection; +use OCP\Server; use OCP\SystemTag\ISystemTag; use OCP\SystemTag\ISystemTagManager; use OCP\SystemTag\ISystemTagObjectMapper; @@ -64,7 +65,7 @@ class SystemTagObjectMapperTest extends TestCase { protected function setUp(): void { parent::setUp(); - $this->connection = \OC::$server->getDatabaseConnection(); + $this->connection = Server::get(IDBConnection::class); $this->pruneTagsTables(); $this->tagManager = $this->createMock(ISystemTagManager::class); @@ -198,7 +199,7 @@ class SystemTagObjectMapperTest extends TestCase { public function testGetObjectsForNonExistingTag(): void { - $this->expectException(\OCP\SystemTag\TagNotFoundException::class); + $this->expectException(TagNotFoundException::class); $this->tagMapper->getObjectIdsForTags( [100], @@ -236,7 +237,7 @@ class SystemTagObjectMapperTest extends TestCase { public function testAssignNonExistingTags(): void { - $this->expectException(\OCP\SystemTag\TagNotFoundException::class); + $this->expectException(TagNotFoundException::class); $this->tagMapper->assignTags('1', 'testtype', [100]); } @@ -263,7 +264,7 @@ class SystemTagObjectMapperTest extends TestCase { public function testUnassignNonExistingTags(): void { - $this->expectException(\OCP\SystemTag\TagNotFoundException::class); + $this->expectException(TagNotFoundException::class); $this->tagMapper->unassignTags('1', 'testtype', [100]); } @@ -394,7 +395,7 @@ class SystemTagObjectMapperTest extends TestCase { public function testHaveTagNonExisting(): void { - $this->expectException(\OCP\SystemTag\TagNotFoundException::class); + $this->expectException(TagNotFoundException::class); $this->tagMapper->haveTag( ['1'], diff --git a/tests/lib/TagsTest.php b/tests/lib/TagsTest.php index feb6bd2a1ad..92e6f7c7dc7 100644 --- a/tests/lib/TagsTest.php +++ b/tests/lib/TagsTest.php @@ -7,6 +7,8 @@ namespace Test; +use OC\Tagging\TagMapper; +use OC\TagManager; use OCP\EventDispatcher\IEventDispatcher; use OCP\IDBConnection; use OCP\IUser; @@ -50,12 +52,12 @@ class TagsTest extends \Test\TestCase { ->willReturn($this->user); $this->objectType = $this->getUniqueID('type_'); - $this->tagMapper = new \OC\Tagging\TagMapper(\OC::$server->get(IDBConnection::class)); - $this->tagMgr = new \OC\TagManager($this->tagMapper, $this->userSession, \OC::$server->get(IDBConnection::class), \OC::$server->get(LoggerInterface::class), \OC::$server->get(IEventDispatcher::class)); + $this->tagMapper = new TagMapper(Server::get(IDBConnection::class)); + $this->tagMgr = new TagManager($this->tagMapper, $this->userSession, Server::get(IDBConnection::class), Server::get(LoggerInterface::class), Server::get(IEventDispatcher::class)); } protected function tearDown(): void { - $conn = \OC::$server->getDatabaseConnection(); + $conn = Server::get(IDBConnection::class); $conn->executeQuery('DELETE FROM `*PREFIX*vcategory_to_object`'); $conn->executeQuery('DELETE FROM `*PREFIX*vcategory`'); @@ -68,7 +70,7 @@ class TagsTest extends \Test\TestCase { ->expects($this->any()) ->method('getUser') ->willReturn(null); - $this->tagMgr = new \OC\TagManager($this->tagMapper, $this->userSession, \OC::$server->getDatabaseConnection(), \OC::$server->get(LoggerInterface::class), \OC::$server->get(IEventDispatcher::class)); + $this->tagMgr = new TagManager($this->tagMapper, $this->userSession, Server::get(IDBConnection::class), Server::get(LoggerInterface::class), Server::get(IEventDispatcher::class)); $this->assertNull($this->tagMgr->load($this->objectType)); } @@ -194,7 +196,7 @@ class TagsTest extends \Test\TestCase { $tagId = $tagData[0]['id']; $tagType = $tagData[0]['type']; - $conn = \OC::$server->getDatabaseConnection(); + $conn = Server::get(IDBConnection::class); $statement = $conn->prepare( 'INSERT INTO `*PREFIX*vcategory_to_object` ' . '(`objid`, `categoryid`, `type`) VALUES ' . diff --git a/tests/lib/TaskProcessing/TaskProcessingTest.php b/tests/lib/TaskProcessing/TaskProcessingTest.php index 73f67b07266..1995b6919ab 100644 --- a/tests/lib/TaskProcessing/TaskProcessingTest.php +++ b/tests/lib/TaskProcessing/TaskProcessingTest.php @@ -12,6 +12,7 @@ use OC\EventDispatcher\EventDispatcher; use OC\TaskProcessing\Db\TaskMapper; use OC\TaskProcessing\Manager; use OC\TaskProcessing\RemoveOldTasksBackgroundJob; +use OC\TaskProcessing\SynchronousBackgroundJob; use OCP\App\IAppManager; use OCP\AppFramework\Utility\ITimeFactory; use OCP\BackgroundJob\IJobList; @@ -19,6 +20,7 @@ use OCP\EventDispatcher\IEventDispatcher; use OCP\Files\AppData\IAppDataFactory; use OCP\Files\Config\ICachedMountInfo; use OCP\Files\Config\IUserMountCache; +use OCP\Files\File; use OCP\Files\IRootFolder; use OCP\Http\Client\IClientService; use OCP\ICacheFactory; @@ -27,11 +29,13 @@ use OCP\IDBConnection; use OCP\IServerContainer; use OCP\IUser; use OCP\IUserManager; +use OCP\Server; use OCP\TaskProcessing\EShapeType; use OCP\TaskProcessing\Events\GetTaskProcessingProvidersEvent; use OCP\TaskProcessing\Events\TaskFailedEvent; use OCP\TaskProcessing\Events\TaskSuccessfulEvent; use OCP\TaskProcessing\Exception\NotFoundException; +use OCP\TaskProcessing\Exception\PreConditionNotMetException; use OCP\TaskProcessing\Exception\ProcessingException; use OCP\TaskProcessing\Exception\UnauthorizedException; use OCP\TaskProcessing\Exception\ValidationException; @@ -551,7 +555,7 @@ class TaskProcessingTest extends \Test\TestCase { ConflictingExternalTaskType::class => new ConflictingExternalTaskType(), ]; - $userManager = \OCP\Server::get(IUserManager::class); + $userManager = Server::get(IUserManager::class); if (!$userManager->userExists(self::TEST_USER)) { $userManager->createUser(self::TEST_USER, 'test'); } @@ -564,19 +568,19 @@ class TaskProcessingTest extends \Test\TestCase { $this->eventDispatcher = new EventDispatcher( new \Symfony\Component\EventDispatcher\EventDispatcher(), $this->serverContainer, - \OC::$server->get(LoggerInterface::class), + Server::get(LoggerInterface::class), ); $this->registrationContext = $this->createMock(RegistrationContext::class); $this->coordinator = $this->createMock(Coordinator::class); $this->coordinator->expects($this->any())->method('getRegistrationContext')->willReturn($this->registrationContext); - $this->rootFolder = \OCP\Server::get(IRootFolder::class); + $this->rootFolder = Server::get(IRootFolder::class); - $this->taskMapper = \OCP\Server::get(TaskMapper::class); + $this->taskMapper = Server::get(TaskMapper::class); $this->jobList = $this->createPartialMock(DummyJobList::class, ['add']); - $this->jobList->expects($this->any())->method('add')->willReturnCallback(function () { + $this->jobList->expects($this->any())->method('add')->willReturnCallback(function (): void { }); $this->eventDispatcher = $this->createMock(IEventDispatcher::class); @@ -585,34 +589,34 @@ class TaskProcessingTest extends \Test\TestCase { $text2imageManager = new \OC\TextToImage\Manager( $this->serverContainer, $this->coordinator, - \OC::$server->get(LoggerInterface::class), + Server::get(LoggerInterface::class), $this->jobList, - \OC::$server->get(\OC\TextToImage\Db\TaskMapper::class), - \OC::$server->get(IConfig::class), - \OC::$server->get(IAppDataFactory::class), + Server::get(\OC\TextToImage\Db\TaskMapper::class), + Server::get(IConfig::class), + Server::get(IAppDataFactory::class), ); $this->userMountCache = $this->createMock(IUserMountCache::class); - $this->config = \OC::$server->get(IConfig::class); + $this->config = Server::get(IConfig::class); $this->manager = new Manager( $this->config, $this->coordinator, $this->serverContainer, - \OC::$server->get(LoggerInterface::class), + Server::get(LoggerInterface::class), $this->taskMapper, $this->jobList, $this->eventDispatcher, - \OC::$server->get(IAppDataFactory::class), - \OC::$server->get(IRootFolder::class), + Server::get(IAppDataFactory::class), + Server::get(IRootFolder::class), $text2imageManager, $this->userMountCache, - \OC::$server->get(IClientService::class), - \OC::$server->get(IAppManager::class), - \OC::$server->get(ICacheFactory::class), + Server::get(IClientService::class), + Server::get(IAppManager::class), + Server::get(ICacheFactory::class), ); } - private function getFile(string $name, string $content): \OCP\Files\File { + private function getFile(string $name, string $content): File { $folder = $this->rootFolder->getUserFolder(self::TEST_USER); $file = $folder->newFile($name, $content); return $file; @@ -622,7 +626,7 @@ class TaskProcessingTest extends \Test\TestCase { $this->registrationContext->expects($this->any())->method('getTaskProcessingProviders')->willReturn([]); self::assertCount(0, $this->manager->getAvailableTaskTypes()); self::assertFalse($this->manager->hasProviders()); - self::expectException(\OCP\TaskProcessing\Exception\PreConditionNotMetException::class); + self::expectException(PreConditionNotMetException::class); $this->manager->scheduleTask(new Task(TextToText::ID, ['input' => 'Hello'], 'test', null)); } @@ -637,7 +641,7 @@ class TaskProcessingTest extends \Test\TestCase { self::assertCount(0, $this->manager->getAvailableTaskTypes()); self::assertCount(1, $this->manager->getAvailableTaskTypes(true)); self::assertTrue($this->manager->hasProviders()); - self::expectException(\OCP\TaskProcessing\Exception\PreConditionNotMetException::class); + self::expectException(PreConditionNotMetException::class); $this->manager->scheduleTask(new Task(TextToText::ID, ['input' => 'Hello'], 'test', null)); } @@ -694,11 +698,11 @@ class TaskProcessingTest extends \Test\TestCase { $this->eventDispatcher->expects($this->once())->method('dispatchTyped')->with(new IsInstanceOf(TaskFailedEvent::class)); - $backgroundJob = new \OC\TaskProcessing\SynchronousBackgroundJob( - \OCP\Server::get(ITimeFactory::class), + $backgroundJob = new SynchronousBackgroundJob( + Server::get(ITimeFactory::class), $this->manager, $this->jobList, - \OCP\Server::get(LoggerInterface::class), + Server::get(LoggerInterface::class), ); $backgroundJob->start($this->jobList); @@ -722,11 +726,11 @@ class TaskProcessingTest extends \Test\TestCase { $this->eventDispatcher->expects($this->once())->method('dispatchTyped')->with(new IsInstanceOf(TaskFailedEvent::class)); - $backgroundJob = new \OC\TaskProcessing\SynchronousBackgroundJob( - \OCP\Server::get(ITimeFactory::class), + $backgroundJob = new SynchronousBackgroundJob( + Server::get(ITimeFactory::class), $this->manager, $this->jobList, - \OCP\Server::get(LoggerInterface::class), + Server::get(LoggerInterface::class), ); $backgroundJob->start($this->jobList); @@ -767,11 +771,11 @@ class TaskProcessingTest extends \Test\TestCase { $this->eventDispatcher->expects($this->once())->method('dispatchTyped')->with(new IsInstanceOf(TaskSuccessfulEvent::class)); - $backgroundJob = new \OC\TaskProcessing\SynchronousBackgroundJob( - \OCP\Server::get(ITimeFactory::class), + $backgroundJob = new SynchronousBackgroundJob( + Server::get(ITimeFactory::class), $this->manager, $this->jobList, - \OCP\Server::get(LoggerInterface::class), + Server::get(LoggerInterface::class), ); $backgroundJob->start($this->jobList); @@ -803,11 +807,11 @@ class TaskProcessingTest extends \Test\TestCase { $this->eventDispatcher->expects($this->once())->method('dispatchTyped')->with(new IsInstanceOf(TaskSuccessfulEvent::class)); - $backgroundJob = new \OC\TaskProcessing\SynchronousBackgroundJob( - \OCP\Server::get(ITimeFactory::class), + $backgroundJob = new SynchronousBackgroundJob( + Server::get(ITimeFactory::class), $this->manager, $this->jobList, - \OCP\Server::get(LoggerInterface::class), + Server::get(LoggerInterface::class), ); $backgroundJob->start($this->jobList); @@ -854,7 +858,7 @@ class TaskProcessingTest extends \Test\TestCase { $this->manager->setTaskProgress($task2->getId(), 0.1); $input = $this->manager->prepareInputData($task2); self::assertTrue(isset($input['audio'])); - self::assertInstanceOf(\OCP\Files\File::class, $input['audio']); + self::assertInstanceOf(File::class, $input['audio']); self::assertEquals($audioId, $input['audio']->getId()); $this->manager->setTaskResult($task2->getId(), null, ['spectrogram' => 'World']); @@ -865,7 +869,7 @@ class TaskProcessingTest extends \Test\TestCase { self::assertTrue(isset($task->getOutput()['spectrogram'])); $node = $this->rootFolder->getFirstNodeByIdInPath($task->getOutput()['spectrogram'], '/' . $this->rootFolder->getAppDataDirectoryName() . '/'); self::assertNotNull($node); - self::assertInstanceOf(\OCP\Files\File::class, $node); + self::assertInstanceOf(File::class, $node); self::assertEquals('World', $node->getContent()); } @@ -904,7 +908,7 @@ class TaskProcessingTest extends \Test\TestCase { $this->manager->setTaskProgress($task2->getId(), 0.1); $input = $this->manager->prepareInputData($task2); self::assertTrue(isset($input['audio'])); - self::assertInstanceOf(\OCP\Files\File::class, $input['audio']); + self::assertInstanceOf(File::class, $input['audio']); self::assertEquals($audioId, $input['audio']->getId()); $outputFileId = $this->getFile('audioOutput', 'World')->getId(); @@ -917,12 +921,12 @@ class TaskProcessingTest extends \Test\TestCase { self::assertTrue(isset($task->getOutput()['spectrogram'])); $node = $this->rootFolder->getFirstNodeById($task->getOutput()['spectrogram']); self::assertNotNull($node, 'fileId:' . $task->getOutput()['spectrogram']); - self::assertInstanceOf(\OCP\Files\File::class, $node); + self::assertInstanceOf(File::class, $node); self::assertEquals('World', $node->getContent()); } public function testNonexistentTask(): void { - $this->expectException(\OCP\TaskProcessing\Exception\NotFoundException::class); + $this->expectException(NotFoundException::class); $this->manager->getTask(2147483646); } @@ -933,7 +937,7 @@ class TaskProcessingTest extends \Test\TestCase { $timeFactory->expects($this->any())->method('getTime')->willReturnCallback(fn () => $currentTime->getTimestamp()); $this->taskMapper = new TaskMapper( - \OCP\Server::get(IDBConnection::class), + Server::get(IDBConnection::class), $timeFactory, ); @@ -947,11 +951,11 @@ class TaskProcessingTest extends \Test\TestCase { $this->eventDispatcher->expects($this->once())->method('dispatchTyped')->with(new IsInstanceOf(TaskSuccessfulEvent::class)); - $backgroundJob = new \OC\TaskProcessing\SynchronousBackgroundJob( - \OCP\Server::get(ITimeFactory::class), + $backgroundJob = new SynchronousBackgroundJob( + Server::get(ITimeFactory::class), $this->manager, $this->jobList, - \OCP\Server::get(LoggerInterface::class), + Server::get(LoggerInterface::class), ); $backgroundJob->start($this->jobList); @@ -962,8 +966,8 @@ class TaskProcessingTest extends \Test\TestCase { $bgJob = new RemoveOldTasksBackgroundJob( $timeFactory, $this->taskMapper, - \OC::$server->get(LoggerInterface::class), - \OCP\Server::get(IAppDataFactory::class), + Server::get(LoggerInterface::class), + Server::get(IAppDataFactory::class), ); $bgJob->setArgument([]); $bgJob->start($this->jobList); @@ -987,11 +991,11 @@ class TaskProcessingTest extends \Test\TestCase { $this->eventDispatcher->expects($this->once())->method('dispatchTyped')->with(new IsInstanceOf(TaskSuccessfulEvent::class)); - $backgroundJob = new \OC\TaskProcessing\SynchronousBackgroundJob( - \OCP\Server::get(ITimeFactory::class), + $backgroundJob = new SynchronousBackgroundJob( + Server::get(ITimeFactory::class), $this->manager, $this->jobList, - \OCP\Server::get(LoggerInterface::class), + Server::get(LoggerInterface::class), ); $backgroundJob->start($this->jobList); @@ -1018,11 +1022,11 @@ class TaskProcessingTest extends \Test\TestCase { $this->eventDispatcher->expects($this->once())->method('dispatchTyped')->with(new IsInstanceOf(TaskFailedEvent::class)); - $backgroundJob = new \OC\TaskProcessing\SynchronousBackgroundJob( - \OCP\Server::get(ITimeFactory::class), + $backgroundJob = new SynchronousBackgroundJob( + Server::get(ITimeFactory::class), $this->manager, $this->jobList, - \OCP\Server::get(LoggerInterface::class), + Server::get(LoggerInterface::class), ); $backgroundJob->start($this->jobList); @@ -1048,11 +1052,11 @@ class TaskProcessingTest extends \Test\TestCase { $this->eventDispatcher->expects($this->once())->method('dispatchTyped')->with(new IsInstanceOf(TaskSuccessfulEvent::class)); - $backgroundJob = new \OC\TaskProcessing\SynchronousBackgroundJob( - \OCP\Server::get(ITimeFactory::class), + $backgroundJob = new SynchronousBackgroundJob( + Server::get(ITimeFactory::class), $this->manager, $this->jobList, - \OCP\Server::get(LoggerInterface::class), + Server::get(LoggerInterface::class), ); $backgroundJob->start($this->jobList); @@ -1065,7 +1069,7 @@ class TaskProcessingTest extends \Test\TestCase { self::assertTrue($this->providers[SuccessfulTextToImageProvider::class]->ran); $node = $this->rootFolder->getFirstNodeByIdInPath($task->getOutput()['images'][0], '/' . $this->rootFolder->getAppDataDirectoryName() . '/'); self::assertNotNull($node); - self::assertInstanceOf(\OCP\Files\File::class, $node); + self::assertInstanceOf(File::class, $node); self::assertEquals('test', $node->getContent()); } @@ -1084,11 +1088,11 @@ class TaskProcessingTest extends \Test\TestCase { $this->eventDispatcher->expects($this->once())->method('dispatchTyped')->with(new IsInstanceOf(TaskFailedEvent::class)); - $backgroundJob = new \OC\TaskProcessing\SynchronousBackgroundJob( - \OCP\Server::get(ITimeFactory::class), + $backgroundJob = new SynchronousBackgroundJob( + Server::get(ITimeFactory::class), $this->manager, $this->jobList, - \OCP\Server::get(LoggerInterface::class), + Server::get(LoggerInterface::class), ); $backgroundJob->start($this->jobList); @@ -1237,28 +1241,28 @@ class TaskProcessingTest extends \Test\TestCase { $text2imageManager = new \OC\TextToImage\Manager( $this->serverContainer, $this->coordinator, - \OC::$server->get(LoggerInterface::class), + Server::get(LoggerInterface::class), $this->jobList, - \OC::$server->get(\OC\TextToImage\Db\TaskMapper::class), + Server::get(\OC\TextToImage\Db\TaskMapper::class), $this->config, // Use the shared config mock - \OC::$server->get(IAppDataFactory::class), + Server::get(IAppDataFactory::class), ); return new Manager( $this->config, $this->coordinator, $this->serverContainer, - \OC::$server->get(LoggerInterface::class), + Server::get(LoggerInterface::class), $this->taskMapper, $this->jobList, $this->eventDispatcher, // Use the potentially reconfigured mock - \OC::$server->get(IAppDataFactory::class), + Server::get(IAppDataFactory::class), $this->rootFolder, $text2imageManager, $this->userMountCache, - \OC::$server->get(IClientService::class), - \OC::$server->get(IAppManager::class), - \OC::$server->get(ICacheFactory::class), + Server::get(IClientService::class), + Server::get(IAppManager::class), + Server::get(ICacheFactory::class), ); } @@ -1271,7 +1275,7 @@ class TaskProcessingTest extends \Test\TestCase { $this->eventDispatcher->expects($dispatchExpectation) ->method('dispatchTyped') - ->willReturnCallback(function (object $event) use ($providersToAdd, $taskTypesToAdd) { + ->willReturnCallback(function (object $event) use ($providersToAdd, $taskTypesToAdd): void { if ($event instanceof GetTaskProcessingProvidersEvent) { foreach ($providersToAdd as $providerInstance) { $event->addProvider($providerInstance); diff --git a/tests/lib/TempManagerTest.php b/tests/lib/TempManagerTest.php index b607772f5c3..ee7778c7e88 100644 --- a/tests/lib/TempManagerTest.php +++ b/tests/lib/TempManagerTest.php @@ -9,6 +9,7 @@ namespace Test; use bantu\IniGetWrapper\IniGetWrapper; +use OC\TempManager; use OCP\Files; use OCP\IConfig; use Psr\Log\LoggerInterface; @@ -49,7 +50,7 @@ class TempManagerTest extends \Test\TestCase { ->willReturn('/tmp'); } $iniGetWrapper = $this->createMock(IniGetWrapper::class); - $manager = new \OC\TempManager($logger, $config, $iniGetWrapper); + $manager = new TempManager($logger, $config, $iniGetWrapper); if ($this->baseDir) { $manager->overrideTempBaseDir($this->baseDir); } diff --git a/tests/lib/Template/JSCombinerTest.php b/tests/lib/Template/JSCombinerTest.php index e4e6594c05c..4881a31a52b 100644 --- a/tests/lib/Template/JSCombinerTest.php +++ b/tests/lib/Template/JSCombinerTest.php @@ -15,7 +15,9 @@ use OCP\Files\SimpleFS\ISimpleFile; use OCP\Files\SimpleFS\ISimpleFolder; use OCP\ICache; use OCP\ICacheFactory; +use OCP\ITempManager; use OCP\IURLGenerator; +use OCP\Server; use Psr\Log\LoggerInterface; class JSCombinerTest extends \Test\TestCase { @@ -488,7 +490,7 @@ var b = \'world\'; public function testGetContent(): void { // Create temporary file with some content - $tmpFile = \OC::$server->getTempManager()->getTemporaryFile('JSCombinerTest'); + $tmpFile = Server::get(ITempManager::class)->getTemporaryFile('JSCombinerTest'); $pathInfo = pathinfo($tmpFile); file_put_contents($tmpFile, json_encode(['/foo/bar/test', $pathInfo['dirname'] . '/js/mytest.js'])); $tmpFilePathArray = explode('/', $pathInfo['basename']); @@ -503,7 +505,7 @@ var b = \'world\'; public function testGetContentInvalidJson(): void { // Create temporary file with some content - $tmpFile = \OC::$server->getTempManager()->getTemporaryFile('JSCombinerTest'); + $tmpFile = Server::get(ITempManager::class)->getTemporaryFile('JSCombinerTest'); $pathInfo = pathinfo($tmpFile); file_put_contents($tmpFile, 'CertainlyNotJson'); $expected = []; diff --git a/tests/lib/Template/ResourceLocatorTest.php b/tests/lib/Template/ResourceLocatorTest.php index 65d4c7938f9..311cf317129 100644 --- a/tests/lib/Template/ResourceLocatorTest.php +++ b/tests/lib/Template/ResourceLocatorTest.php @@ -60,11 +60,11 @@ class ResourceLocatorTest extends \Test\TestCase { $locator->expects($this->once()) ->method('doFind') ->with('foo') - ->will($this->throwException(new ResourceNotFoundException('foo', 'map'))); + ->willThrowException(new ResourceNotFoundException('foo', 'map')); $locator->expects($this->once()) ->method('doFindTheme') ->with('foo') - ->will($this->throwException(new ResourceNotFoundException('foo', 'map'))); + ->willThrowException(new ResourceNotFoundException('foo', 'map')); $this->logger->expects($this->exactly(2)) ->method('debug') ->with($this->stringContains('map/foo')); diff --git a/tests/lib/TestCase.php b/tests/lib/TestCase.php index 9ca2606ce72..da1313d3697 100644 --- a/tests/lib/TestCase.php +++ b/tests/lib/TestCase.php @@ -10,6 +10,7 @@ namespace Test; use DOMDocument; use DOMNode; use OC\Command\QueueBus; +use OC\Files\Cache\Storage; use OC\Files\Config\MountProviderCollection; use OC\Files\Filesystem; use OC\Files\Mount\CacheMountProvider; @@ -24,8 +25,12 @@ use OCP\Defaults; use OCP\IConfig; use OCP\IDBConnection; use OCP\IL10N; +use OCP\IUserManager; +use OCP\IUserSession; use OCP\Lock\ILockingProvider; +use OCP\Lock\LockedException; use OCP\Security\ISecureRandom; +use OCP\Server; if (version_compare(\PHPUnit\Runner\Version::id(), 10, '>=')) { trait OnNotSuccessfulTestTrait { @@ -84,7 +89,7 @@ abstract class TestCase extends \PHPUnit\Framework\TestCase { return false; } - $this->services[$name] = \OC::$server->query($name); + $this->services[$name] = Server::get($name); $container = \OC::$server->getAppContainerForService($name); $container = $container ?? \OC::$server; @@ -154,9 +159,9 @@ abstract class TestCase extends \PHPUnit\Framework\TestCase { if (!$this->IsDatabaseAccessAllowed()) { self::$wasDatabaseAllowed = false; if (is_null(self::$realDatabase)) { - self::$realDatabase = \OC::$server->getDatabaseConnection(); + self::$realDatabase = Server::get(IDBConnection::class); } - \OC::$server->registerService(IDBConnection::class, function () { + \OC::$server->registerService(IDBConnection::class, function (): void { $this->fail('Your test case is not allowed to access the database.'); }); } @@ -183,7 +188,7 @@ abstract class TestCase extends \PHPUnit\Framework\TestCase { // further cleanup $hookExceptions = \OC_Hook::$thrownExceptions; \OC_Hook::$thrownExceptions = []; - \OC::$server->get(ILockingProvider::class)->releaseAll(); + Server::get(ILockingProvider::class)->releaseAll(); if (!empty($hookExceptions)) { throw $hookExceptions[0]; } @@ -196,7 +201,7 @@ abstract class TestCase extends \PHPUnit\Framework\TestCase { } if ($this->IsDatabaseAccessAllowed()) { - \OC\Files\Cache\Storage::getGlobalCache()->clearCache(); + Storage::getGlobalCache()->clearCache(); } // tearDown the traits @@ -264,7 +269,7 @@ abstract class TestCase extends \PHPUnit\Framework\TestCase { * @return string */ protected static function getUniqueID($prefix = '', $length = 13) { - return $prefix . \OC::$server->get(ISecureRandom::class)->generate( + return $prefix . Server::get(ISecureRandom::class)->generate( $length, // Do not use dots and slashes as we use the value for file names ISecureRandom::CHAR_DIGITS . ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_UPPER @@ -303,9 +308,9 @@ abstract class TestCase extends \PHPUnit\Framework\TestCase { return self::$realDatabase; }); } - $dataDir = \OC::$server->getConfig()->getSystemValueString('datadirectory', \OC::$SERVERROOT . '/data-autotest'); - if (self::$wasDatabaseAllowed && \OC::$server->getDatabaseConnection()) { - $db = \OC::$server->getDatabaseConnection(); + $dataDir = Server::get(IConfig::class)->getSystemValueString('datadirectory', \OC::$SERVERROOT . '/data-autotest'); + if (self::$wasDatabaseAllowed && Server::get(IDBConnection::class)) { + $db = Server::get(IDBConnection::class); 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.'); @@ -321,18 +326,18 @@ abstract class TestCase extends \PHPUnit\Framework\TestCase { self::tearDownAfterClassCleanStrayLocks(); /** @var SetupManager $setupManager */ - $setupManager = \OC::$server->get(SetupManager::class); + $setupManager = Server::get(SetupManager::class); $setupManager->tearDown(); /** @var MountProviderCollection $mountProviderCollection */ - $mountProviderCollection = \OC::$server->get(MountProviderCollection::class); + $mountProviderCollection = Server::get(MountProviderCollection::class); $mountProviderCollection->clearProviders(); /** @var IConfig $config */ - $config = \OC::$server->get(IConfig::class); + $config = Server::get(IConfig::class); $mountProviderCollection->registerProvider(new CacheMountProvider($config)); $mountProviderCollection->registerHomeProvider(new LocalHomeMountProvider()); - $objectStoreConfig = \OC::$server->get(PrimaryObjectStoreConfig::class); + $objectStoreConfig = Server::get(PrimaryObjectStoreConfig::class); $mountProviderCollection->registerRootProvider(new RootMountProvider($objectStoreConfig, $config)); $setupManager->setupRoot(); @@ -404,7 +409,7 @@ abstract class TestCase extends \PHPUnit\Framework\TestCase { protected static function tearDownAfterClassCleanStrayDataUnlinkDir($dir) { if ($dh = @opendir($dir)) { while (($file = readdir($dh)) !== false) { - if (\OC\Files\Filesystem::isIgnoredDir($file)) { + if (Filesystem::isIgnoredDir($file)) { continue; } $path = $dir . '/' . $file; @@ -430,7 +435,7 @@ abstract class TestCase extends \PHPUnit\Framework\TestCase { * Clean up the list of locks */ protected static function tearDownAfterClassCleanStrayLocks() { - \OC::$server->get(ILockingProvider::class)->releaseAll(); + Server::get(ILockingProvider::class)->releaseAll(); } /** @@ -441,14 +446,14 @@ abstract class TestCase extends \PHPUnit\Framework\TestCase { */ protected static function loginAsUser($user = '') { self::logout(); - \OC\Files\Filesystem::tearDown(); + Filesystem::tearDown(); \OC_User::setUserId($user); - $userObject = \OC::$server->getUserManager()->get($user); + $userObject = Server::get(IUserManager::class)->get($user); if (!is_null($userObject)) { $userObject->updateLastLoginTimestamp(); } \OC_Util::setupFS($user); - if (\OC::$server->getUserManager()->userExists($user)) { + if (Server::get(IUserManager::class)->userExists($user)) { \OC::$server->getUserFolder($user); } } @@ -460,7 +465,7 @@ abstract class TestCase extends \PHPUnit\Framework\TestCase { \OC_Util::tearDownFS(); \OC_User::setUserId(''); // needed for fully logout - \OC::$server->getUserSession()->setUser(null); + Server::get(IUserSession::class)->setUser(null); } /** @@ -501,12 +506,12 @@ abstract class TestCase extends \PHPUnit\Framework\TestCase { // the format of the lock key depends on the storage implementation // (in our case mostly md5) - if ($type === \OCP\Lock\ILockingProvider::LOCK_SHARED) { + if ($type === ILockingProvider::LOCK_SHARED) { // to check if the file has a shared lock, try acquiring an exclusive lock - $checkType = \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE; + $checkType = ILockingProvider::LOCK_EXCLUSIVE; } else { // a shared lock cannot be set if exclusive lock is in place - $checkType = \OCP\Lock\ILockingProvider::LOCK_SHARED; + $checkType = ILockingProvider::LOCK_SHARED; } try { $view->lockFile($path, $checkType, $onMountPoint); @@ -514,7 +519,7 @@ abstract class TestCase extends \PHPUnit\Framework\TestCase { // clean up $view->unlockFile($path, $checkType, $onMountPoint); return false; - } catch (\OCP\Lock\LockedException $e) { + } catch (LockedException $e) { // we could not acquire the counter-lock, which means // the lock of $type was in place return true; diff --git a/tests/lib/TestMoveableMountPoint.php b/tests/lib/TestMoveableMountPoint.php index 4f3feccdbe2..33a5741f6ef 100644 --- a/tests/lib/TestMoveableMountPoint.php +++ b/tests/lib/TestMoveableMountPoint.php @@ -8,11 +8,13 @@ namespace Test; use OC\Files\Mount; +use OC\Files\Mount\MountPoint; +use OC\Files\Mount\MoveableMount; /** * Test moveable mount for mocking */ -class TestMoveableMountPoint extends Mount\MountPoint implements Mount\MoveableMount { +class TestMoveableMountPoint extends MountPoint implements MoveableMount { /** * Move the mount point to $target * diff --git a/tests/lib/TextProcessing/TextProcessingTest.php b/tests/lib/TextProcessing/TextProcessingTest.php index 1bbb9cf527e..7761e064834 100644 --- a/tests/lib/TextProcessing/TextProcessingTest.php +++ b/tests/lib/TextProcessing/TextProcessingTest.php @@ -23,6 +23,7 @@ use OCP\EventDispatcher\IEventDispatcher; use OCP\IConfig; use OCP\IServerContainer; use OCP\PreConditionNotMetException; +use OCP\Server; use OCP\TextProcessing\Events\TaskFailedEvent; use OCP\TextProcessing\Events\TaskSuccessfulEvent; use OCP\TextProcessing\FreePromptTaskType; @@ -118,7 +119,7 @@ class TextProcessingTest extends \Test\TestCase { $this->eventDispatcher = new EventDispatcher( new \Symfony\Component\EventDispatcher\EventDispatcher(), $this->serverContainer, - \OCP\Server::get(LoggerInterface::class), + Server::get(LoggerInterface::class), ); $this->registrationContext = $this->createMock(RegistrationContext::class); @@ -158,14 +159,14 @@ class TextProcessingTest extends \Test\TestCase { $this->taskMapper ->expects($this->any()) ->method('deleteOlderThan') - ->willReturnCallback(function (int $timeout) { + ->willReturnCallback(function (int $timeout): void { $this->tasksDb = array_filter($this->tasksDb, function (array $task) use ($timeout) { return $task['last_updated'] >= $this->currentTime->getTimestamp() - $timeout; }); }); $this->jobList = $this->createPartialMock(DummyJobList::class, ['add']); - $this->jobList->expects($this->any())->method('add')->willReturnCallback(function () { + $this->jobList->expects($this->any())->method('add')->willReturnCallback(function (): void { }); $config = $this->createMock(IConfig::class); @@ -176,7 +177,7 @@ class TextProcessingTest extends \Test\TestCase { $this->manager = new Manager( $this->serverContainer, $this->coordinator, - \OCP\Server::get(LoggerInterface::class), + Server::get(LoggerInterface::class), $this->jobList, $this->taskMapper, $config, @@ -239,7 +240,7 @@ class TextProcessingTest extends \Test\TestCase { // run background job $bgJob = new TaskBackgroundJob( - \OCP\Server::get(ITimeFactory::class), + Server::get(ITimeFactory::class), $this->manager, $this->eventDispatcher, ); @@ -314,7 +315,7 @@ class TextProcessingTest extends \Test\TestCase { // run background job $bgJob = new TaskBackgroundJob( - \OCP\Server::get(ITimeFactory::class), + Server::get(ITimeFactory::class), $this->manager, $this->eventDispatcher, ); @@ -343,9 +344,9 @@ class TextProcessingTest extends \Test\TestCase { $this->currentTime = $this->currentTime->add(new \DateInterval('P1Y')); // run background job $bgJob = new RemoveOldTasksBackgroundJob( - \OCP\Server::get(ITimeFactory::class), + Server::get(ITimeFactory::class), $this->taskMapper, - \OCP\Server::get(LoggerInterface::class), + Server::get(LoggerInterface::class), ); $bgJob->setArgument([]); $bgJob->start($this->jobList); diff --git a/tests/lib/Traits/EncryptionTrait.php b/tests/lib/Traits/EncryptionTrait.php index e435a286685..fa0aa1541c3 100644 --- a/tests/lib/Traits/EncryptionTrait.php +++ b/tests/lib/Traits/EncryptionTrait.php @@ -11,10 +11,14 @@ use OC\Encryption\EncryptionWrapper; use OC\Files\SetupManager; use OC\Memcache\ArrayCache; use OCA\Encryption\AppInfo\Application; +use OCA\Encryption\Crypto\Encryption; use OCA\Encryption\KeyManager; use OCA\Encryption\Users\Setup; use OCP\Encryption\IManager; +use OCP\IConfig; use OCP\IUserManager; +use OCP\IUserSession; +use OCP\Server; use Psr\Log\LoggerInterface; /** @@ -51,7 +55,7 @@ trait EncryptionTrait { \OC_Util::tearDownFS(); \OC_User::setUserId(''); // needed for fully logout - \OC::$server->getUserSession()->setUser(null); + Server::get(IUserSession::class)->setUser(null); $this->setupManager->tearDown(); @@ -81,32 +85,32 @@ trait EncryptionTrait { protected function postLogin() { $encryptionWrapper = new EncryptionWrapper( new ArrayCache(), - \OC::$server->getEncryptionManager(), - \OC::$server->get(LoggerInterface::class) + Server::get(\OCP\Encryption\IManager::class), + Server::get(LoggerInterface::class) ); $this->registerStorageWrapper('oc_encryption', [$encryptionWrapper, 'wrapStorage']); } protected function setUpEncryptionTrait() { - $isReady = \OC::$server->getEncryptionManager()->isReady(); + $isReady = Server::get(\OCP\Encryption\IManager::class)->isReady(); if (!$isReady) { $this->markTestSkipped('Encryption not ready'); } - $this->userManager = \OC::$server->get(IUserManager::class); - $this->setupManager = \OC::$server->get(SetupManager::class); + $this->userManager = Server::get(IUserManager::class); + $this->setupManager = Server::get(SetupManager::class); \OC_App::loadApp('encryption'); $this->encryptionApp = new Application([], $isReady); - $this->config = \OC::$server->getConfig(); + $this->config = Server::get(IConfig::class); $this->encryptionWasEnabled = $this->config->getAppValue('core', 'encryption_enabled', 'no'); $this->originalEncryptionModule = $this->config->getAppValue('core', 'default_encryption_module'); - $this->config->setAppValue('core', 'default_encryption_module', \OCA\Encryption\Crypto\Encryption::ID); + $this->config->setAppValue('core', 'default_encryption_module', Encryption::ID); $this->config->setAppValue('core', 'encryption_enabled', 'yes'); - $this->assertTrue(\OC::$server->getEncryptionManager()->isEnabled()); + $this->assertTrue(Server::get(\OCP\Encryption\IManager::class)->isEnabled()); } protected function tearDownEncryptionTrait() { diff --git a/tests/lib/Traits/MountProviderTrait.php b/tests/lib/Traits/MountProviderTrait.php index 3bb92f48e20..479e702e2f1 100644 --- a/tests/lib/Traits/MountProviderTrait.php +++ b/tests/lib/Traits/MountProviderTrait.php @@ -9,7 +9,9 @@ namespace Test\Traits; use OC\Files\Mount\MountPoint; use OC\Files\Storage\StorageFactory; +use OCP\Files\Config\IMountProviderCollection; use OCP\IUser; +use OCP\Server; /** * Allow setting mounts for users @@ -49,7 +51,7 @@ trait MountProviderTrait { $this->mountProvider = $this->getMockBuilder('\OCP\Files\Config\IMountProvider')->getMock(); $this->mountProvider->expects($this->any()) ->method('getMountsForUser') - ->will($this->returnCallback(function (IUser $user) { + ->willReturnCallback(function (IUser $user) { if (isset($this->mounts[$user->getUID()])) { return array_map(function ($config) { return new MountPoint($config['storage'], $config['mountPoint'], $config['arguments'], $this->storageFactory); @@ -57,7 +59,7 @@ trait MountProviderTrait { } else { return []; } - })); - \OCP\Server::get(\OCP\Files\Config\IMountProviderCollection::class)->registerProvider($this->mountProvider); + }); + Server::get(IMountProviderCollection::class)->registerProvider($this->mountProvider); } } diff --git a/tests/lib/Traits/UserTrait.php b/tests/lib/Traits/UserTrait.php index 05fb0caa8ca..137ca986911 100644 --- a/tests/lib/Traits/UserTrait.php +++ b/tests/lib/Traits/UserTrait.php @@ -10,14 +10,14 @@ namespace Test\Traits; use OC\User\User; use OCP\EventDispatcher\IEventDispatcher; use OCP\IUser; +use OCP\IUserManager; use OCP\Server; class DummyUser extends User { - private string $uid; - - public function __construct(string $uid) { - $this->uid = $uid; - parent::__construct($uid, null, Server::get(IEventDispatcher::class)); + public function __construct( + private string $uid, + ) { + parent::__construct($this->uid, null, Server::get(IEventDispatcher::class)); } public function getUID(): string { @@ -41,10 +41,10 @@ trait UserTrait { protected function setUpUserTrait() { $this->userBackend = new \Test\Util\User\Dummy(); - \OC::$server->getUserManager()->registerBackend($this->userBackend); + Server::get(IUserManager::class)->registerBackend($this->userBackend); } protected function tearDownUserTrait() { - \OC::$server->getUserManager()->removeBackend($this->userBackend); + Server::get(IUserManager::class)->removeBackend($this->userBackend); } } diff --git a/tests/lib/Updater/ChangesCheckTest.php b/tests/lib/Updater/ChangesCheckTest.php index 4b0c54b0881..6b5b306d8f7 100644 --- a/tests/lib/Updater/ChangesCheckTest.php +++ b/tests/lib/Updater/ChangesCheckTest.php @@ -333,10 +333,10 @@ class ChangesCheckTest extends TestCase { public static function changeDataProvider():array { $testDataFound = $testDataNotFound = self::versionProvider(); - array_walk($testDataFound, static function (&$params) { + array_walk($testDataFound, static function (&$params): void { $params[] = true; }); - array_walk($testDataNotFound, static function (&$params) { + array_walk($testDataNotFound, static function (&$params): void { $params[] = false; }); return array_merge($testDataFound, $testDataNotFound); diff --git a/tests/lib/Updater/VersionCheckTest.php b/tests/lib/Updater/VersionCheckTest.php index 4ee75c767a2..0afbed08ab6 100644 --- a/tests/lib/Updater/VersionCheckTest.php +++ b/tests/lib/Updater/VersionCheckTest.php @@ -12,6 +12,7 @@ use OCP\Http\Client\IClientService; use OCP\IAppConfig; use OCP\IConfig; use OCP\IUserManager; +use OCP\Server; use OCP\ServerVersion; use OCP\Support\Subscription\IRegistry; use Psr\Log\LoggerInterface; @@ -63,7 +64,7 @@ class VersionCheckTest extends \Test\TestCase { * @return string */ private function buildUpdateUrl($baseUrl) { - $serverVersion = \OCP\Server::get(ServerVersion::class); + $serverVersion = Server::get(ServerVersion::class); return $baseUrl . '?version=' . implode('x', $serverVersion->getVersion()) . 'xinstalledatx' . time() . 'x' . $serverVersion->getChannel() . 'xxx' . PHP_MAJOR_VERSION . 'x' . PHP_MINOR_VERSION . 'x' . PHP_RELEASE_VERSION . 'x0x0'; } diff --git a/tests/lib/UrlGeneratorTest.php b/tests/lib/UrlGeneratorTest.php index 7006c3948f6..21a0286348a 100644 --- a/tests/lib/UrlGeneratorTest.php +++ b/tests/lib/UrlGeneratorTest.php @@ -8,6 +8,7 @@ namespace Test; use OC\Route\Router; +use OC\URLGenerator; use OCP\ICacheFactory; use OCP\IConfig; use OCP\IRequest; @@ -42,7 +43,7 @@ class UrlGeneratorTest extends \Test\TestCase { $this->cacheFactory = $this->createMock(ICacheFactory::class); $this->request = $this->createMock(IRequest::class); $this->router = $this->createMock(Router::class); - $this->urlGenerator = new \OC\URLGenerator( + $this->urlGenerator = new URLGenerator( $this->config, $this->userSession, $this->cacheFactory, diff --git a/tests/lib/User/DatabaseTest.php b/tests/lib/User/DatabaseTest.php index 900f0ddd3fa..225a0f75edb 100644 --- a/tests/lib/User/DatabaseTest.php +++ b/tests/lib/User/DatabaseTest.php @@ -7,6 +7,7 @@ namespace Test\User; +use OC\User\Database; use OC\User\User; use OCP\EventDispatcher\Event; use OCP\EventDispatcher\IEventDispatcher; @@ -39,7 +40,7 @@ class DatabaseTest extends Backend { $this->eventDispatcher = $this->createMock(IEventDispatcher::class); - $this->backend = new \OC\User\Database($this->eventDispatcher); + $this->backend = new Database($this->eventDispatcher); } protected function tearDown(): void { @@ -58,7 +59,7 @@ class DatabaseTest extends Backend { $this->eventDispatcher->expects($this->once())->method('dispatchTyped') ->willReturnCallback( - function (Event $event) { + function (Event $event): void { $this->assertInstanceOf(ValidatePasswordPolicyEvent::class, $event); /** @var ValidatePasswordPolicyEvent $event */ $this->assertSame('newpass', $event->getPassword()); @@ -71,7 +72,7 @@ class DatabaseTest extends Backend { public function testVerifyPasswordEventFail(): void { - $this->expectException(\OCP\HintException::class); + $this->expectException(HintException::class); $this->expectExceptionMessage('password change failed'); $user = $this->getUser(); @@ -79,7 +80,7 @@ class DatabaseTest extends Backend { $this->eventDispatcher->expects($this->once())->method('dispatchTyped') ->willReturnCallback( - function (Event $event) { + function (Event $event): void { $this->assertInstanceOf(ValidatePasswordPolicyEvent::class, $event); /** @var ValidatePasswordPolicyEvent $event */ $this->assertSame('newpass', $event->getPassword()); diff --git a/tests/lib/User/ManagerTest.php b/tests/lib/User/ManagerTest.php index 5d3966cf4d8..57041c0ef22 100644 --- a/tests/lib/User/ManagerTest.php +++ b/tests/lib/User/ManagerTest.php @@ -9,14 +9,17 @@ namespace Test\User; use OC\AllConfig; +use OC\USER\BACKEND; use OC\User\Database; use OC\User\Manager; +use OC\User\User; use OCP\EventDispatcher\IEventDispatcher; use OCP\ICache; use OCP\ICacheFactory; use OCP\IConfig; use OCP\IUser; use OCP\IUserManager; +use OCP\Server; use Psr\Log\LoggerInterface; use Test\TestCase; @@ -178,7 +181,7 @@ class ManagerTest extends TestCase { $backend->expects($this->any()) ->method('implementsActions') ->willReturnCallback(function ($actions) { - if ($actions === \OC\USER\BACKEND::CHECK_PASSWORD) { + if ($actions === BACKEND::CHECK_PASSWORD) { return true; } else { return false; @@ -189,7 +192,7 @@ class ManagerTest extends TestCase { $manager->registerBackend($backend); $user = $manager->checkPassword('foo', 'bar'); - $this->assertTrue($user instanceof \OC\User\User); + $this->assertTrue($user instanceof User); } public function testCheckPasswordNotSupported(): void { @@ -545,7 +548,7 @@ class ManagerTest extends TestCase { $backend->expects($this->once()) ->method('implementsActions') - ->with(\OC\USER\BACKEND::COUNT_USERS) + ->with(BACKEND::COUNT_USERS) ->willReturn(true); $backend->expects($this->once()) @@ -574,7 +577,7 @@ class ManagerTest extends TestCase { $backend1->expects($this->once()) ->method('implementsActions') - ->with(\OC\USER\BACKEND::COUNT_USERS) + ->with(BACKEND::COUNT_USERS) ->willReturn(true); $backend1->expects($this->once()) ->method('getBackendName') @@ -587,7 +590,7 @@ class ManagerTest extends TestCase { $backend2->expects($this->once()) ->method('implementsActions') - ->with(\OC\USER\BACKEND::COUNT_USERS) + ->with(BACKEND::COUNT_USERS) ->willReturn(true); $backend2->expects($this->once()) ->method('getBackendName') @@ -609,7 +612,7 @@ class ManagerTest extends TestCase { } public function testCountUsersOnlyDisabled(): void { - $manager = \OCP\Server::get(IUserManager::class); + $manager = Server::get(IUserManager::class); // count other users in the db before adding our own $countBefore = $manager->countDisabledUsers(); @@ -634,7 +637,7 @@ class ManagerTest extends TestCase { } public function testCountUsersOnlySeen(): void { - $manager = \OCP\Server::get(IUserManager::class); + $manager = Server::get(IUserManager::class); // count other users in the db before adding our own $countBefore = $manager->countSeenUsers(); @@ -660,10 +663,10 @@ class ManagerTest extends TestCase { } public function testCallForSeenUsers(): void { - $manager = \OCP\Server::get(IUserManager::class); + $manager = Server::get(IUserManager::class); // count other users in the db before adding our own $count = 0; - $function = function (IUser $user) use (&$count) { + $function = function (IUser $user) use (&$count): void { $count++; }; $manager->callForAllUsers($function, '', true); @@ -698,8 +701,8 @@ class ManagerTest extends TestCase { * @preserveGlobalState disabled */ public function testRecentlyActive(): void { - $config = \OCP\Server::get(IConfig::class); - $manager = \OCP\Server::get(IUserManager::class); + $config = Server::get(IConfig::class); + $manager = Server::get(IUserManager::class); // Create some users $now = (string)time(); diff --git a/tests/lib/User/SessionTest.php b/tests/lib/User/SessionTest.php index a10a0e87b81..685b7c13d44 100644 --- a/tests/lib/User/SessionTest.php +++ b/tests/lib/User/SessionTest.php @@ -158,7 +158,7 @@ class SessionTest extends \Test\TestCase { $this->tokenProvider->expects($this->once()) ->method('getToken') ->with('bar') - ->will($this->throwException(new InvalidTokenException())); + ->willThrowException(new InvalidTokenException()); $session->expects($this->exactly(2)) ->method('set') ->with($this->callback(function ($key) { @@ -238,7 +238,7 @@ class SessionTest extends \Test\TestCase { $this->tokenProvider->expects($this->once()) ->method('getToken') ->with('bar') - ->will($this->throwException(new InvalidTokenException())); + ->willThrowException(new InvalidTokenException()); $managerMethods = get_class_methods(Manager::class); //keep following methods intact in order to ensure hooks are working @@ -298,7 +298,7 @@ class SessionTest extends \Test\TestCase { $this->tokenProvider->expects($this->once()) ->method('getToken') ->with('bar') - ->will($this->throwException(new InvalidTokenException())); + ->willThrowException(new InvalidTokenException()); $user->expects($this->never()) ->method('isEnabled'); @@ -404,7 +404,7 @@ class SessionTest extends \Test\TestCase { $this->tokenProvider->expects($this->once()) ->method('getToken') ->with('bar') - ->will($this->throwException(new InvalidTokenException())); + ->willThrowException(new InvalidTokenException()); $manager->expects($this->once()) ->method('checkPasswordNoLogging') @@ -430,7 +430,7 @@ class SessionTest extends \Test\TestCase { $this->tokenProvider->expects($this->once()) ->method('getToken') ->with('doe') - ->will($this->throwException(new InvalidTokenException())); + ->willThrowException(new InvalidTokenException()); $this->config->expects($this->once()) ->method('getSystemValueBool') ->with('token_auth_enforced', false) @@ -466,7 +466,7 @@ class SessionTest extends \Test\TestCase { $this->tokenProvider->expects($this->once()) ->method('getToken') ->with('doe') - ->will($this->throwException(new InvalidTokenException())); + ->willThrowException(new InvalidTokenException()); $this->config->expects($this->once()) ->method('getSystemValueBool') ->with('token_auth_enforced', false) @@ -534,7 +534,7 @@ class SessionTest extends \Test\TestCase { $this->tokenProvider->expects($this->once()) ->method('getToken') ->with('doe') - ->will($this->throwException(new InvalidTokenException())); + ->willThrowException(new InvalidTokenException()); $this->config->expects($this->once()) ->method('getSystemValueBool') ->with('token_auth_enforced', false) @@ -635,7 +635,7 @@ class SessionTest extends \Test\TestCase { ->with('abcde12345') ->willReturn($dbToken); $this->session->method('set') - ->willReturnCallback(function ($key, $value) { + ->willReturnCallback(function ($key, $value): void { if ($key === 'app_password') { throw new ExpectationFailedException('app_password should not be set in session'); } @@ -725,7 +725,7 @@ class SessionTest extends \Test\TestCase { $setUID = false; $session ->method('set') - ->willReturnCallback(function ($k, $v) use (&$setUID) { + ->willReturnCallback(function ($k, $v) use (&$setUID): void { if ($k === 'user_id' && $v === 'foo') { $setUID = true; } @@ -788,7 +788,7 @@ class SessionTest extends \Test\TestCase { $this->tokenProvider->expects($this->once()) ->method('renewSessionToken') ->with($oldSessionId, $sessionId) - ->will($this->throwException(new InvalidTokenException())); + ->willThrowException(new InvalidTokenException()); $user->expects($this->never()) ->method('getUID') @@ -972,7 +972,7 @@ class SessionTest extends \Test\TestCase { $this->tokenProvider->expects($this->once()) ->method('getToken') ->with($password) - ->will($this->throwException(new InvalidTokenException())); + ->willThrowException(new InvalidTokenException()); $this->tokenProvider->expects($this->once()) ->method('generateToken') @@ -1013,7 +1013,7 @@ class SessionTest extends \Test\TestCase { $this->tokenProvider->expects($this->once()) ->method('getToken') ->with($password) - ->will($this->throwException(new InvalidTokenException())); + ->willThrowException(new InvalidTokenException()); $this->tokenProvider->expects($this->once()) ->method('generateToken') @@ -1130,7 +1130,7 @@ class SessionTest extends \Test\TestCase { $this->session ->method('set') - ->willReturnCallback(function ($k, $v) use (&$davAuthenticatedSet, &$lastPasswordConfirmSet) { + ->willReturnCallback(function ($k, $v) use (&$davAuthenticatedSet, &$lastPasswordConfirmSet): void { switch ($k) { case Auth::DAV_AUTHENTICATED: $davAuthenticatedSet = $v; diff --git a/tests/lib/User/UserTest.php b/tests/lib/User/UserTest.php index 8f9560d6486..e386d0c2c10 100644 --- a/tests/lib/User/UserTest.php +++ b/tests/lib/User/UserTest.php @@ -11,6 +11,7 @@ namespace Test\User; use OC\AllConfig; use OC\Files\Mount\ObjectHomeMountProvider; use OC\Hooks\PublicEmitter; +use OC\User\Database; use OC\User\User; use OCP\Comments\ICommentsManager; use OCP\EventDispatcher\IEventDispatcher; @@ -218,7 +219,7 @@ class UserTest extends TestCase { public function testDeleteWithDifferentHome(): void { /** @var ObjectHomeMountProvider $homeProvider */ - $homeProvider = \OC::$server->get(ObjectHomeMountProvider::class); + $homeProvider = Server::get(ObjectHomeMountProvider::class); $user = $this->createMock(IUser::class); $user->method('getUID') ->willReturn('foo'); @@ -284,7 +285,7 @@ class UserTest extends TestCase { public function testGetBackendClassName(): void { $user = new User('foo', new \Test\Util\User\Dummy(), $this->dispatcher); $this->assertEquals('Dummy', $user->getBackendClassName()); - $user = new User('foo', new \OC\User\Database(), $this->dispatcher); + $user = new User('foo', new Database(), $this->dispatcher); $this->assertEquals('Database', $user->getBackendClassName()); } @@ -392,7 +393,7 @@ class UserTest extends TestCase { /** * @var Backend | MockObject $backend */ - $backend = $this->createMock(\OC\User\Database::class); + $backend = $this->createMock(Database::class); $backend->expects($this->any()) ->method('implementsActions') @@ -421,7 +422,7 @@ class UserTest extends TestCase { /** * @var Backend | MockObject $backend */ - $backend = $this->createMock(\OC\User\Database::class); + $backend = $this->createMock(Database::class); $backend->expects($this->any()) ->method('implementsActions') @@ -442,7 +443,7 @@ class UserTest extends TestCase { /** * @var Backend | MockObject $backend */ - $backend = $this->createMock(\OC\User\Database::class); + $backend = $this->createMock(Database::class); $backend->expects($this->any()) ->method('implementsActions') @@ -471,7 +472,7 @@ class UserTest extends TestCase { * @param User $user * @param string $password */ - $hook = function ($user, $password) use ($test, &$hooksCalled) { + $hook = function ($user, $password) use ($test, &$hooksCalled): void { $hooksCalled++; $test->assertEquals('foo', $user->getUID()); $test->assertEquals('bar', $password); @@ -537,7 +538,7 @@ class UserTest extends TestCase { /** * @param User $user */ - $hook = function ($user) use ($test, &$hooksCalled) { + $hook = function ($user) use ($test, &$hooksCalled): void { $hooksCalled++; $test->assertEquals('foo', $user->getUID()); }; @@ -586,14 +587,14 @@ class UserTest extends TestCase { ->method('markProcessed'); } - $this->overwriteService(\OCP\Notification\IManager::class, $notificationManager); - $this->overwriteService(\OCP\Comments\ICommentsManager::class, $commentsManager); + $this->overwriteService(INotificationManager::class, $notificationManager); + $this->overwriteService(ICommentsManager::class, $commentsManager); $this->assertSame($result, $user->delete()); $this->restoreService(AllConfig::class); - $this->restoreService(\OCP\Comments\ICommentsManager::class); - $this->restoreService(\OCP\Notification\IManager::class); + $this->restoreService(ICommentsManager::class); + $this->restoreService(INotificationManager::class); $this->assertEquals($expectedHooks, $hooksCalled); } @@ -617,7 +618,7 @@ class UserTest extends TestCase { $userConfig = []; $config->expects(self::atLeast(2)) ->method('setUserValue') - ->willReturnCallback(function () { + ->willReturnCallback(function (): void { $userConfig[] = func_get_args(); }); @@ -626,7 +627,7 @@ class UserTest extends TestCase { ->method('deleteReferencesOfActor') ->willThrowException(new \Error('Test exception')); - $this->overwriteService(\OCP\Comments\ICommentsManager::class, $commentsManager); + $this->overwriteService(ICommentsManager::class, $commentsManager); $this->expectException(\Error::class); $user = $this->getMockBuilder(User::class) @@ -648,7 +649,7 @@ class UserTest extends TestCase { $userConfig, ); - $this->restoreService(\OCP\Comments\ICommentsManager::class); + $this->restoreService(ICommentsManager::class); } public static function dataGetCloudId(): array { @@ -686,7 +687,7 @@ class UserTest extends TestCase { * @param string $feature * @param string $value */ - $hook = function (IUser $user, $feature, $value) use ($test, &$hooksCalled) { + $hook = function (IUser $user, $feature, $value) use ($test, &$hooksCalled): void { $hooksCalled++; $test->assertEquals('eMailAddress', $feature); $test->assertEquals('', $value); @@ -722,7 +723,7 @@ class UserTest extends TestCase { * @param string $feature * @param string $value */ - $hook = function (IUser $user, $feature, $value) use ($test, &$hooksCalled) { + $hook = function (IUser $user, $feature, $value) use ($test, &$hooksCalled): void { $hooksCalled++; $test->assertEquals('eMailAddress', $feature); $test->assertEquals('foo@bar.com', $value); @@ -785,7 +786,7 @@ class UserTest extends TestCase { * @param string $feature * @param string $value */ - $hook = function (IUser $user, $feature, $value) use ($test, &$hooksCalled) { + $hook = function (IUser $user, $feature, $value) use ($test, &$hooksCalled): void { $hooksCalled++; $test->assertEquals('quota', $feature); $test->assertEquals('23 TB', $value); @@ -831,9 +832,9 @@ class UserTest extends TestCase { ['files', 'allow_unlimited_quota', '1', '1'], ]; $config->method('getUserValue') - ->will($this->returnValueMap($userValueMap)); + ->willReturnMap($userValueMap); $config->method('getAppValue') - ->will($this->returnValueMap($appValueMap)); + ->willReturnMap($appValueMap); $this->assertEquals('none', $user->getQuota()); $this->assertEquals(FileInfo::SPACE_UNLIMITED, $user->getQuotaBytes()); @@ -865,9 +866,9 @@ class UserTest extends TestCase { ['files', 'default_quota', '1 GB', '1 GB'], ]; $config->method('getUserValue') - ->will($this->returnValueMap($userValueMap)); + ->willReturnMap($userValueMap); $config->method('getAppValue') - ->will($this->returnValueMap($appValueMap)); + ->willReturnMap($appValueMap); $this->assertEquals('1 GB', $user->getQuota()); $this->assertEquals(1024 * 1024 * 1024, $user->getQuotaBytes()); diff --git a/tests/lib/Util/User/Dummy.php b/tests/lib/Util/User/Dummy.php index d44b9d85d72..93f457184c4 100644 --- a/tests/lib/Util/User/Dummy.php +++ b/tests/lib/Util/User/Dummy.php @@ -8,11 +8,12 @@ namespace Test\Util\User; use OC\User\Backend; +use OCP\IUserBackend; /** * dummy user backend, does not keep state, only for testing use */ -class Dummy extends Backend implements \OCP\IUserBackend { +class Dummy extends Backend implements IUserBackend { private $users = []; private $displayNames = []; diff --git a/tests/lib/UtilCheckServerTest.php b/tests/lib/UtilCheckServerTest.php index ca4cd7d108f..accac40112a 100644 --- a/tests/lib/UtilCheckServerTest.php +++ b/tests/lib/UtilCheckServerTest.php @@ -7,6 +7,11 @@ namespace Test; +use OCP\ISession; +use OCP\ITempManager; +use OCP\Server; +use OCP\Util; + /** * Tests for server check functions * @@ -37,10 +42,10 @@ class UtilCheckServerTest extends \Test\TestCase { protected function setUp(): void { parent::setUp(); - $this->datadir = \OC::$server->getTempManager()->getTemporaryFolder(); + $this->datadir = Server::get(ITempManager::class)->getTemporaryFolder(); file_put_contents($this->datadir . '/.ncdata', '# Nextcloud data directory'); - \OC::$server->getSession()->set('checkServer_succeeded', false); + Server::get(ISession::class)->set('checkServer_succeeded', false); } protected function tearDown(): void { @@ -85,7 +90,7 @@ class UtilCheckServerTest extends \Test\TestCase { // simulate old version that didn't have it unlink($this->datadir . '/.ncdata'); - $session = \OC::$server->getSession(); + $session = Server::get(ISession::class); $oldCurrentVersion = $session->get('OC_Version'); // upgrade condition to simulate needUpgrade() === true @@ -123,7 +128,7 @@ class UtilCheckServerTest extends \Test\TestCase { $result = \OC_Util::checkServer($this->getConfig([ 'installed' => true, - 'version' => implode('.', \OCP\Util::getVersion()) + 'version' => implode('.', Util::getVersion()) ])); $this->assertCount(1, $result); } @@ -134,7 +139,7 @@ class UtilCheckServerTest extends \Test\TestCase { public function testDataDirWritable(): void { $result = \OC_Util::checkServer($this->getConfig([ 'installed' => true, - 'version' => implode('.', \OCP\Util::getVersion()) + 'version' => implode('.', Util::getVersion()) ])); $this->assertEmpty($result); } @@ -148,7 +153,7 @@ class UtilCheckServerTest extends \Test\TestCase { chmod($this->datadir, 0300); $result = \OC_Util::checkServer($this->getConfig([ 'installed' => true, - 'version' => implode('.', \OCP\Util::getVersion()) + 'version' => implode('.', Util::getVersion()) ])); $this->assertCount(1, $result); } @@ -160,7 +165,7 @@ class UtilCheckServerTest extends \Test\TestCase { chmod($this->datadir, 0300); $result = \OC_Util::checkServer($this->getConfig([ 'installed' => false, - 'version' => implode('.', \OCP\Util::getVersion()) + 'version' => implode('.', Util::getVersion()) ])); chmod($this->datadir, 0700); //needed for cleanup $this->assertEmpty($result); diff --git a/tests/lib/UtilTest.php b/tests/lib/UtilTest.php index e124ea687d8..d1145fc3149 100644 --- a/tests/lib/UtilTest.php +++ b/tests/lib/UtilTest.php @@ -8,6 +8,11 @@ namespace Test; use OC_Util; +use OCP\Files; +use OCP\IConfig; +use OCP\ISession; +use OCP\ITempManager; +use OCP\Server; use OCP\Util; /** @@ -95,7 +100,7 @@ class UtilTest extends \Test\TestCase { * If no strict email check is enabled "localhost" should validate as a valid email domain */ public function testGetDefaultEmailAddress(): void { - $config = \OC::$server->getConfig(); + $config = Server::get(IConfig::class); $config->setAppValue('core', 'enforce_strict_email_check', 'no'); $email = Util::getDefaultEmailAddress('no-reply'); $this->assertEquals('no-reply@localhost', $email); @@ -103,7 +108,7 @@ class UtilTest extends \Test\TestCase { } public function testGetDefaultEmailAddressFromConfig(): void { - $config = \OC::$server->getConfig(); + $config = Server::get(IConfig::class); $config->setSystemValue('mail_domain', 'example.com'); $email = Util::getDefaultEmailAddress('no-reply'); $this->assertEquals('no-reply@example.com', $email); @@ -111,7 +116,7 @@ class UtilTest extends \Test\TestCase { } public function testGetConfiguredEmailAddressFromConfig(): void { - $config = \OC::$server->getConfig(); + $config = Server::get(IConfig::class); $config->setSystemValue('mail_domain', 'example.com'); $config->setSystemValue('mail_from_address', 'owncloud'); $email = Util::getDefaultEmailAddress('no-reply'); @@ -121,7 +126,7 @@ class UtilTest extends \Test\TestCase { } public function testGetInstanceIdGeneratesValidId(): void { - \OC::$server->getConfig()->deleteSystemValue('instanceid'); + Server::get(IConfig::class)->deleteSystemValue('instanceid'); $instanceId = OC_Util::getInstanceId(); $this->assertStringStartsWith('oc', $instanceId); $matchesRegex = preg_match('/^[a-z0-9]+$/', $instanceId); @@ -132,37 +137,37 @@ class UtilTest extends \Test\TestCase { * Test needUpgrade() when the core version is increased */ public function testNeedUpgradeCore(): void { - $config = \OC::$server->getConfig(); + $config = Server::get(IConfig::class); $oldConfigVersion = $config->getSystemValue('version', '0.0.0'); - $oldSessionVersion = \OC::$server->getSession()->get('OC_Version'); + $oldSessionVersion = Server::get(ISession::class)->get('OC_Version'); $this->assertFalse(Util::needUpgrade()); $config->setSystemValue('version', '7.0.0.0'); - \OC::$server->getSession()->set('OC_Version', [7, 0, 0, 1]); + Server::get(ISession::class)->set('OC_Version', [7, 0, 0, 1]); self::invokePrivate(new Util, 'needUpgradeCache', [null]); $this->assertTrue(Util::needUpgrade()); $config->setSystemValue('version', $oldConfigVersion); - \OC::$server->getSession()->set('OC_Version', $oldSessionVersion); + Server::get(ISession::class)->set('OC_Version', $oldSessionVersion); self::invokePrivate(new Util, 'needUpgradeCache', [null]); $this->assertFalse(Util::needUpgrade()); } public function testCheckDataDirectoryValidity(): void { - $dataDir = \OC::$server->getTempManager()->getTemporaryFolder(); + $dataDir = Server::get(ITempManager::class)->getTemporaryFolder(); touch($dataDir . '/.ncdata'); $errors = \OC_Util::checkDataDirectoryValidity($dataDir); $this->assertEmpty($errors); - \OCP\Files::rmdirr($dataDir); + Files::rmdirr($dataDir); - $dataDir = \OC::$server->getTempManager()->getTemporaryFolder(); + $dataDir = Server::get(ITempManager::class)->getTemporaryFolder(); // no touch $errors = \OC_Util::checkDataDirectoryValidity($dataDir); $this->assertNotEmpty($errors); - \OCP\Files::rmdirr($dataDir); + Files::rmdirr($dataDir); $errors = \OC_Util::checkDataDirectoryValidity('relative/path'); $this->assertNotEmpty($errors); |