aboutsummaryrefslogtreecommitdiffstats
path: root/tests/lib
diff options
context:
space:
mode:
Diffstat (limited to 'tests/lib')
-rw-r--r--tests/lib/Accounts/AccountManagerTest.php57
-rw-r--r--tests/lib/Accounts/AccountPropertyTest.php12
-rw-r--r--tests/lib/Accounts/AccountTest.php1
-rw-r--r--tests/lib/Accounts/HooksTest.php15
-rw-r--r--tests/lib/Activity/ManagerTest.php22
-rw-r--r--tests/lib/AllConfigTest.php72
-rw-r--r--tests/lib/App/AppManagerTest.php88
-rw-r--r--tests/lib/App/AppStore/Bundles/BundleBase.php1
-rw-r--r--tests/lib/App/AppStore/Bundles/BundleFetcherTest.php1
-rw-r--r--tests/lib/App/AppStore/Bundles/EducationBundleTest.php1
-rw-r--r--tests/lib/App/AppStore/Bundles/EnterpriseBundleTest.php1
-rw-r--r--tests/lib/App/AppStore/Bundles/GroupwareBundleTest.php1
-rw-r--r--tests/lib/App/AppStore/Bundles/SocialSharingBundleTest.php1
-rw-r--r--tests/lib/App/AppStore/Fetcher/AppDiscoverFetcherTest.php7
-rw-r--r--tests/lib/App/AppStore/Fetcher/AppFetcherTest.php931
-rw-r--r--tests/lib/App/AppStore/Fetcher/CategoryFetcherTest.php1
-rw-r--r--tests/lib/App/AppStore/Fetcher/FetcherBase.php1
-rw-r--r--tests/lib/App/AppStore/Version/VersionParserTest.php9
-rw-r--r--tests/lib/App/AppStore/Version/VersionTest.php1
-rw-r--r--tests/lib/App/CompareVersionTest.php6
-rw-r--r--tests/lib/App/DependencyAnalyzerTest.php25
-rw-r--r--tests/lib/App/InfoParserTest.php13
-rw-r--r--tests/lib/App/PlatformRepositoryTest.php9
-rw-r--r--tests/lib/AppConfigTest.php83
-rw-r--r--tests/lib/AppFramework/AppTest.php23
-rw-r--r--tests/lib/AppFramework/Bootstrap/CoordinatorTest.php9
-rw-r--r--tests/lib/AppFramework/Bootstrap/FunctionInjectorTest.php3
-rw-r--r--tests/lib/AppFramework/Bootstrap/RegistrationContextTest.php6
-rw-r--r--tests/lib/AppFramework/Controller/AuthPublicShareControllerTest.php11
-rw-r--r--tests/lib/AppFramework/Controller/ControllerTest.php2
-rw-r--r--tests/lib/AppFramework/Controller/OCSControllerTest.php52
-rw-r--r--tests/lib/AppFramework/Controller/PublicShareControllerTest.php24
-rw-r--r--tests/lib/AppFramework/Db/EntityTest.php13
-rw-r--r--tests/lib/AppFramework/Db/QBMapperDBTest.php5
-rw-r--r--tests/lib/AppFramework/Db/QBMapperTest.php96
-rw-r--r--tests/lib/AppFramework/Db/TransactionalTest.php16
-rw-r--r--tests/lib/AppFramework/DependencyInjection/DIContainerTest.php2
-rw-r--r--tests/lib/AppFramework/DependencyInjection/DIIntergrationTests.php9
-rw-r--r--tests/lib/AppFramework/Http/ContentSecurityPolicyTest.php1
-rw-r--r--tests/lib/AppFramework/Http/DataResponseTest.php3
-rw-r--r--tests/lib/AppFramework/Http/DispatcherTest.php65
-rw-r--r--tests/lib/AppFramework/Http/DownloadResponseTest.php6
-rw-r--r--tests/lib/AppFramework/Http/EmptyContentSecurityPolicyTest.php1
-rw-r--r--tests/lib/AppFramework/Http/FileDisplayResponseTest.php1
-rw-r--r--tests/lib/AppFramework/Http/JSONResponseTest.php7
-rw-r--r--tests/lib/AppFramework/Http/OutputTest.php1
-rw-r--r--tests/lib/AppFramework/Http/PublicTemplateResponseTest.php10
-rw-r--r--tests/lib/AppFramework/Http/RequestStream.php1
-rw-r--r--tests/lib/AppFramework/Http/RequestTest.php37
-rw-r--r--tests/lib/AppFramework/Http/ResponseTest.php16
-rw-r--r--tests/lib/AppFramework/Http/TemplateResponseTest.php2
-rw-r--r--tests/lib/AppFramework/Middleware/AdditionalScriptsMiddlewareTest.php6
-rw-r--r--tests/lib/AppFramework/Middleware/MiddlewareDispatcherTest.php24
-rw-r--r--tests/lib/AppFramework/Middleware/MiddlewareTest.php7
-rw-r--r--tests/lib/AppFramework/Middleware/NotModifiedMiddlewareTest.php15
-rw-r--r--tests/lib/AppFramework/Middleware/OCSMiddlewareTest.php144
-rw-r--r--tests/lib/AppFramework/Middleware/PublicShare/PublicShareMiddlewareTest.php7
-rw-r--r--tests/lib/AppFramework/Middleware/Security/BruteForceMiddlewareTest.php42
-rw-r--r--tests/lib/AppFramework/Middleware/Security/CORSMiddlewareTest.php58
-rw-r--r--tests/lib/AppFramework/Middleware/Security/Mock/CORSMiddlewareController.php3
-rw-r--r--tests/lib/AppFramework/Middleware/Security/Mock/NormalController.php4
-rw-r--r--tests/lib/AppFramework/Middleware/Security/Mock/PasswordConfirmationMiddlewareController.php3
-rw-r--r--tests/lib/AppFramework/Middleware/Security/Mock/SecurityMiddlewareController.php3
-rw-r--r--tests/lib/AppFramework/Middleware/Security/PasswordConfirmationMiddlewareTest.php11
-rw-r--r--tests/lib/AppFramework/Middleware/Security/SameSiteCookieMiddlewareTest.php3
-rw-r--r--tests/lib/AppFramework/Middleware/Security/SecurityMiddlewareTest.php133
-rw-r--r--tests/lib/AppFramework/OCS/BaseResponseTest.php8
-rw-r--r--tests/lib/AppFramework/OCS/V2ResponseTest.php6
-rw-r--r--tests/lib/AppFramework/Routing/RouteParserTest.php347
-rw-r--r--tests/lib/AppFramework/Routing/RoutingTest.php476
-rw-r--r--tests/lib/AppFramework/Services/AppConfigTest.php73
-rw-r--r--tests/lib/AppFramework/Utility/SimpleContainerTest.php59
-rw-r--r--tests/lib/AppScriptSortTest.php1
-rw-r--r--tests/lib/AppTest.php49
-rw-r--r--tests/lib/Archive/TARTest.php5
-rw-r--r--tests/lib/Archive/TestBase.php13
-rw-r--r--tests/lib/Archive/ZIPTest.php9
-rw-r--r--tests/lib/Authentication/Listeners/UserDeletedTokenCleanupListenerTest.php15
-rw-r--r--tests/lib/Authentication/Login/ALoginTestCommand.php (renamed from tests/lib/Authentication/Login/ALoginCommandTest.php)6
-rw-r--r--tests/lib/Authentication/Login/ClearLostPasswordTokensCommandTest.php2
-rw-r--r--tests/lib/Authentication/Login/CompleteLoginCommandTest.php2
-rw-r--r--tests/lib/Authentication/Login/CreateSessionTokenCommandTest.php2
-rw-r--r--tests/lib/Authentication/Login/FinishRememberedLoginCommandTest.php2
-rw-r--r--tests/lib/Authentication/Login/LoggedInCheckCommandTest.php2
-rw-r--r--tests/lib/Authentication/Login/PreLoginHookCommandTest.php2
-rw-r--r--tests/lib/Authentication/Login/SetUserTimezoneCommandTest.php2
-rw-r--r--tests/lib/Authentication/Login/TwoFactorCommandTest.php2
-rw-r--r--tests/lib/Authentication/Login/UidLoginCommandTest.php2
-rw-r--r--tests/lib/Authentication/Login/UpdateLastPasswordConfirmCommandTest.php2
-rw-r--r--tests/lib/Authentication/Login/UserDisabledCheckCommandTest.php2
-rw-r--r--tests/lib/Authentication/LoginCredentials/StoreTest.php14
-rw-r--r--tests/lib/Authentication/Token/ManagerTest.php57
-rw-r--r--tests/lib/Authentication/Token/PublicKeyTokenMapperTest.php11
-rw-r--r--tests/lib/Authentication/Token/PublicKeyTokenProviderTest.php84
-rw-r--r--tests/lib/Authentication/TwoFactorAuth/Db/ProviderUserAssignmentDaoTest.php4
-rw-r--r--tests/lib/Authentication/TwoFactorAuth/EnforcementStateTest.php1
-rw-r--r--tests/lib/Authentication/TwoFactorAuth/ManagerTest.php133
-rw-r--r--tests/lib/Authentication/TwoFactorAuth/ProviderManagerTest.php9
-rw-r--r--tests/lib/Authentication/TwoFactorAuth/RegistryTest.php13
-rw-r--r--tests/lib/AutoLoaderTest.php57
-rw-r--r--tests/lib/Avatar/AvatarManagerTest.php7
-rw-r--r--tests/lib/Avatar/UserAvatarTest.php29
-rw-r--r--tests/lib/BackgroundJob/DummyJobList.php10
-rw-r--r--tests/lib/BackgroundJob/JobListTest.php35
-rw-r--r--tests/lib/BackgroundJob/JobTest.php8
-rw-r--r--tests/lib/BackgroundJob/QueuedJobTest.php4
-rw-r--r--tests/lib/BackgroundJob/TestJob.php16
-rw-r--r--tests/lib/BackgroundJob/TestParallelAwareJob.php16
-rw-r--r--tests/lib/BackgroundJob/TimedJobTest.php4
-rw-r--r--tests/lib/BinaryFinderTest.php8
-rw-r--r--tests/lib/Cache/CappedMemoryCacheTest.php7
-rw-r--r--tests/lib/Cache/FileCacheTest.php46
-rw-r--r--tests/lib/Cache/TestCache.php7
-rw-r--r--tests/lib/Calendar/ManagerTest.php1006
-rw-r--r--tests/lib/Calendar/ResourcesRoomsUpdaterTest.php6
-rw-r--r--tests/lib/CapabilitiesManagerTest.php3
-rw-r--r--tests/lib/Collaboration/Collaborators/GroupPluginTest.php3
-rw-r--r--tests/lib/Collaboration/Collaborators/LookupPluginTest.php5
-rw-r--r--tests/lib/Collaboration/Collaborators/MailPluginTest.php13
-rw-r--r--tests/lib/Collaboration/Collaborators/RemotePluginTest.php14
-rw-r--r--tests/lib/Collaboration/Collaborators/SearchResultTest.php9
-rw-r--r--tests/lib/Collaboration/Collaborators/SearchTest.php7
-rw-r--r--tests/lib/Collaboration/Collaborators/UserPluginTest.php15
-rw-r--r--tests/lib/Command/AsyncBusTestCase.php (renamed from tests/lib/Command/AsyncBusTest.php)37
-rw-r--r--tests/lib/Command/BackgroundModeTest.php9
-rw-r--r--tests/lib/Command/CronBusTest.php9
-rw-r--r--tests/lib/Command/Integrity/SignAppTest.php218
-rw-r--r--tests/lib/Command/Integrity/SignCoreTest.php167
-rw-r--r--tests/lib/Comments/CommentTest.php37
-rw-r--r--tests/lib/Comments/FakeFactory.php4
-rw-r--r--tests/lib/Comments/FakeManager.php1
-rw-r--r--tests/lib/Comments/ManagerTest.php68
-rw-r--r--tests/lib/Config/LexiconTest.php59
-rw-r--r--tests/lib/Config/TestConfigLexicon_I.php5
-rw-r--r--tests/lib/Config/UserConfigTest.php249
-rw-r--r--tests/lib/ConfigTest.php33
-rw-r--r--tests/lib/Contacts/ContactsMenu/Providers/LocalTimeProviderTest.php12
-rw-r--r--tests/lib/ContactsManagerTest.php23
-rw-r--r--tests/lib/DB/AdapterTest.php7
-rw-r--r--tests/lib/DB/ConnectionFactoryTest.php5
-rw-r--r--tests/lib/DB/Exception/DbalExceptionTest.php4
-rw-r--r--tests/lib/DB/MigrationsTest.php15
-rw-r--r--tests/lib/DB/MigratorTest.php12
-rw-r--r--tests/lib/DB/OCPostgreSqlPlatformTest.php1
-rw-r--r--tests/lib/DB/QueryBuilder/ExpressionBuilderDBTest.php18
-rw-r--r--tests/lib/DB/QueryBuilder/ExpressionBuilderTest.php49
-rw-r--r--tests/lib/DB/QueryBuilder/FunctionBuilderTest.php57
-rw-r--r--tests/lib/DB/QueryBuilder/Partitioned/JoinConditionTest.php10
-rw-r--r--tests/lib/DB/QueryBuilder/Partitioned/PartitionedQueryBuilderTest.php1
-rw-r--r--tests/lib/DB/QueryBuilder/QueryBuilderTest.php124
-rw-r--r--tests/lib/DB/QueryBuilder/QuoteHelperTest.php9
-rw-r--r--tests/lib/DateTimeFormatterTest.php82
-rw-r--r--tests/lib/Diagnostics/EventLoggerTest.php1
-rw-r--r--tests/lib/Diagnostics/QueryLoggerTest.php3
-rw-r--r--tests/lib/DirectEditing/ManagerTest.php4
-rw-r--r--tests/lib/EmojiHelperTest.php13
-rw-r--r--tests/lib/Encryption/DecryptAllTest.php21
-rw-r--r--tests/lib/Encryption/EncryptionWrapperTest.php18
-rw-r--r--tests/lib/Encryption/Keys/StorageTest.php16
-rw-r--r--tests/lib/Encryption/ManagerTest.php9
-rw-r--r--tests/lib/Encryption/UpdateTest.php199
-rw-r--r--tests/lib/Encryption/UtilTest.php58
-rw-r--r--tests/lib/ErrorHandlerTest.php16
-rw-r--r--tests/lib/EventSourceFactoryTest.php1
-rw-r--r--tests/lib/Federation/CloudIdManagerTest.php24
-rw-r--r--tests/lib/Federation/CloudIdTest.php6
-rw-r--r--tests/lib/Files/AppData/AppDataTest.php1
-rw-r--r--tests/lib/Files/AppData/FactoryTest.php1
-rw-r--r--tests/lib/Files/Cache/CacheTest.php109
-rw-r--r--tests/lib/Files/Cache/HomeCacheTest.php29
-rw-r--r--tests/lib/Files/Cache/LocalRootScannerTest.php4
-rw-r--r--tests/lib/Files/Cache/MoveFromCacheTraitTest.php9
-rw-r--r--tests/lib/Files/Cache/PropagatorTest.php1
-rw-r--r--tests/lib/Files/Cache/ScannerTest.php13
-rw-r--r--tests/lib/Files/Cache/SearchBuilderTest.php13
-rw-r--r--tests/lib/Files/Cache/UpdaterLegacyTest.php27
-rw-r--r--tests/lib/Files/Cache/UpdaterTest.php16
-rw-r--r--tests/lib/Files/Cache/WatcherTest.php23
-rw-r--r--tests/lib/Files/Cache/Wrapper/CacheJailTest.php23
-rw-r--r--tests/lib/Files/Cache/Wrapper/CachePermissionsMaskTest.php15
-rw-r--r--tests/lib/Files/Config/UserMountCacheTest.php112
-rw-r--r--tests/lib/Files/EtagTest.php18
-rw-r--r--tests/lib/Files/FileInfoTest.php1
-rw-r--r--tests/lib/Files/FilenameValidatorTest.php170
-rw-r--r--tests/lib/Files/FilesystemTest.php162
-rw-r--r--tests/lib/Files/Mount/ManagerTest.php12
-rw-r--r--tests/lib/Files/Mount/MountPointTest.php10
-rw-r--r--tests/lib/Files/Mount/MountTest.php8
-rw-r--r--tests/lib/Files/Mount/ObjectHomeMountProviderTest.php250
-rw-r--r--tests/lib/Files/Mount/RootMountProviderTest.php7
-rw-r--r--tests/lib/Files/Node/FileTest.php88
-rw-r--r--tests/lib/Files/Node/FolderTest.php84
-rw-r--r--tests/lib/Files/Node/HookConnectorTest.php73
-rw-r--r--tests/lib/Files/Node/IntegrationTest.php11
-rw-r--r--tests/lib/Files/Node/NodeTestCase.php (renamed from tests/lib/Files/Node/NodeTest.php)128
-rw-r--r--tests/lib/Files/Node/RootTest.php38
-rw-r--r--tests/lib/Files/ObjectStore/AzureTest.php7
-rw-r--r--tests/lib/Files/ObjectStore/FailDeleteObjectStore.php7
-rw-r--r--tests/lib/Files/ObjectStore/FailWriteObjectStore.php7
-rw-r--r--tests/lib/Files/ObjectStore/LocalTest.php6
-rw-r--r--tests/lib/Files/ObjectStore/MapperTest.php5
-rw-r--r--tests/lib/Files/ObjectStore/ObjectStoreScannerTest.php1
-rw-r--r--tests/lib/Files/ObjectStore/ObjectStoreStorageTest.php31
-rw-r--r--tests/lib/Files/ObjectStore/ObjectStoreStoragesDifferentBucketTest.php10
-rw-r--r--tests/lib/Files/ObjectStore/ObjectStoreStoragesSameBucketTest.php8
-rw-r--r--tests/lib/Files/ObjectStore/ObjectStoreTestCase.php (renamed from tests/lib/Files/ObjectStore/ObjectStoreTest.php)24
-rw-r--r--tests/lib/Files/ObjectStore/S3Test.php11
-rw-r--r--tests/lib/Files/ObjectStore/SwiftTest.php10
-rw-r--r--tests/lib/Files/PathVerificationTest.php37
-rw-r--r--tests/lib/Files/Search/QueryOptimizer/CombinedTests.php1
-rw-r--r--tests/lib/Files/Search/QueryOptimizer/FlattenNestedBoolTest.php1
-rw-r--r--tests/lib/Files/Search/QueryOptimizer/MergeDistributiveOperationsTest.php1
-rw-r--r--tests/lib/Files/Search/QueryOptimizer/OrEqualsToInTest.php1
-rw-r--r--tests/lib/Files/Search/SearchIntegrationTest.php1
-rw-r--r--tests/lib/Files/SimpleFS/SimpleFileTest.php1
-rw-r--r--tests/lib/Files/SimpleFS/SimpleFolderTest.php1
-rw-r--r--tests/lib/Files/Storage/CommonTest.php7
-rw-r--r--tests/lib/Files/Storage/CopyDirectoryTest.php4
-rw-r--r--tests/lib/Files/Storage/HomeTest.php24
-rw-r--r--tests/lib/Files/Storage/LocalTest.php29
-rw-r--r--tests/lib/Files/Storage/Storage.php51
-rw-r--r--tests/lib/Files/Storage/StorageFactoryTest.php8
-rw-r--r--tests/lib/Files/Storage/StoragesTestCase.php (renamed from tests/lib/Files/Storage/StoragesTest.php)8
-rw-r--r--tests/lib/Files/Storage/Wrapper/AvailabilityTest.php11
-rw-r--r--tests/lib/Files/Storage/Wrapper/EncodingTest.php54
-rw-r--r--tests/lib/Files/Storage/Wrapper/EncryptionTest.php112
-rw-r--r--tests/lib/Files/Storage/Wrapper/JailTest.php13
-rw-r--r--tests/lib/Files/Storage/Wrapper/KnownMtimeTest.php1
-rw-r--r--tests/lib/Files/Storage/Wrapper/PermissionsMaskTest.php15
-rw-r--r--tests/lib/Files/Storage/Wrapper/QuotaTest.php29
-rw-r--r--tests/lib/Files/Storage/Wrapper/WrapperTest.php15
-rw-r--r--tests/lib/Files/Stream/DummyEncryptionWrapper.php5
-rw-r--r--tests/lib/Files/Stream/EncryptionTest.php55
-rw-r--r--tests/lib/Files/Stream/HashWrapperTest.php8
-rw-r--r--tests/lib/Files/Stream/QuotaTest.php9
-rw-r--r--tests/lib/Files/Type/DetectionTest.php16
-rw-r--r--tests/lib/Files/Type/LoaderTest.php4
-rw-r--r--tests/lib/Files/Utils/ScannerTest.php37
-rw-r--r--tests/lib/Files/ViewTest.php170
-rw-r--r--tests/lib/FilesTest.php42
-rw-r--r--tests/lib/GlobalScale/ConfigTest.php7
-rw-r--r--tests/lib/Group/Backend.php1
-rw-r--r--tests/lib/Group/DatabaseTest.php7
-rw-r--r--tests/lib/Group/Dummy.php1
-rw-r--r--tests/lib/Group/GroupTest.php47
-rw-r--r--tests/lib/Group/HideFromCollaborationTest.php53
-rw-r--r--tests/lib/Group/ManagerTest.php107
-rw-r--r--tests/lib/Group/MetaDataTest.php21
-rw-r--r--tests/lib/HelperStorageTest.php64
-rw-r--r--tests/lib/HookHelper.php14
-rw-r--r--tests/lib/Hooks/BasicEmitterTest.php64
-rw-r--r--tests/lib/Http/Client/ClientServiceTest.php12
-rw-r--r--tests/lib/Http/Client/ClientTest.php40
-rw-r--r--tests/lib/Http/Client/DnsPinMiddlewareTest.php10
-rw-r--r--tests/lib/Http/Client/NegativeDnsCacheTest.php2
-rw-r--r--tests/lib/Http/Client/ResponseTest.php1
-rw-r--r--tests/lib/ImageTest.php19
-rw-r--r--tests/lib/InfoXmlTest.php29
-rw-r--r--tests/lib/InitialStateServiceTest.php10
-rw-r--r--tests/lib/InstallerTest.php64
-rw-r--r--tests/lib/IntegrityCheck/CheckerTest.php23
-rw-r--r--tests/lib/IntegrityCheck/Helpers/AppLocatorTest.php3
-rw-r--r--tests/lib/IntegrityCheck/Helpers/EnvironmentHelperTest.php1
-rw-r--r--tests/lib/IntegrityCheck/Helpers/FileAccessHelperTest.php13
-rw-r--r--tests/lib/IntegrityCheck/Iterator/ExcludeFileByNameFilterIteratorTest.php13
-rw-r--r--tests/lib/L10N/FactoryTest.php25
-rw-r--r--tests/lib/L10N/L10nTest.php38
-rw-r--r--tests/lib/L10N/LanguageIteratorTest.php7
-rw-r--r--tests/lib/LargeFileHelperGetFileSizeTest.php24
-rw-r--r--tests/lib/LargeFileHelperTest.php7
-rw-r--r--tests/lib/LegacyHelperTest.php212
-rw-r--r--tests/lib/Lock/DBLockingProviderTest.php14
-rw-r--r--tests/lib/Lock/LockingProvider.php37
-rw-r--r--tests/lib/Lock/MemcacheLockingProviderTest.php13
-rw-r--r--tests/lib/Lock/NonCachingDBLockingProviderTest.php10
-rw-r--r--tests/lib/Lockdown/Filesystem/NoFSTest.php6
-rw-r--r--tests/lib/Lockdown/Filesystem/NullCacheTest.php3
-rw-r--r--tests/lib/Lockdown/Filesystem/NullStorageTest.php1
-rw-r--r--tests/lib/Lockdown/LockdownManagerTest.php1
-rw-r--r--tests/lib/Log/FileTest.php11
-rw-r--r--tests/lib/Log/LogFactoryTest.php16
-rw-r--r--tests/lib/Log/PsrLoggerAdapterTest.php16
-rw-r--r--tests/lib/LoggerTest.php39
-rw-r--r--tests/lib/Mail/EMailTemplateTest.php1
-rw-r--r--tests/lib/Mail/MailerTest.php18
-rw-r--r--tests/lib/Mail/MessageTest.php8
-rw-r--r--tests/lib/Mail/Provider/AddressTest.php4
-rw-r--r--tests/lib/Mail/Provider/AttachmentTest.php8
-rw-r--r--tests/lib/Mail/Provider/MessageTest.php18
-rw-r--r--tests/lib/Memcache/APCuTest.php6
-rw-r--r--tests/lib/Memcache/ArrayCacheTest.php4
-rw-r--r--tests/lib/Memcache/Cache.php4
-rw-r--r--tests/lib/Memcache/CasTraitTest.php4
-rw-r--r--tests/lib/Memcache/FactoryTest.php33
-rw-r--r--tests/lib/Memcache/MemcachedTest.php8
-rw-r--r--tests/lib/Memcache/RedisTest.php14
-rw-r--r--tests/lib/MemoryInfoTest.php21
-rw-r--r--tests/lib/Migration/BackgroundRepairTest.php14
-rw-r--r--tests/lib/NaturalSortTest.php20
-rw-r--r--tests/lib/NavigationManagerTest.php34
-rw-r--r--tests/lib/Net/HostnameClassifierTest.php12
-rw-r--r--tests/lib/Net/IpAddressClassifierTest.php12
-rw-r--r--tests/lib/Notification/ActionTest.php29
-rw-r--r--tests/lib/Notification/ManagerTest.php12
-rw-r--r--tests/lib/Notification/NotificationTest.php156
-rw-r--r--tests/lib/OCS/ApiHelperTest.php9
-rw-r--r--tests/lib/OCS/DiscoveryServiceTest.php9
-rw-r--r--tests/lib/OCS/ProviderTest.php16
-rw-r--r--tests/lib/Preview/BackgroundCleanupJobTest.php15
-rw-r--r--tests/lib/Preview/BitmapTest.php5
-rw-r--r--tests/lib/Preview/GeneratorTest.php5
-rw-r--r--tests/lib/Preview/HEICTest.php5
-rw-r--r--tests/lib/Preview/ImageTest.php5
-rw-r--r--tests/lib/Preview/MP3Test.php5
-rw-r--r--tests/lib/Preview/MovieBrokenStuckFfmpegTest.php20
-rw-r--r--tests/lib/Preview/MovieTest.php13
-rw-r--r--tests/lib/Preview/OfficeTest.php14
-rw-r--r--tests/lib/Preview/Provider.php31
-rw-r--r--tests/lib/Preview/SVGTest.php12
-rw-r--r--tests/lib/Preview/TXTTest.php5
-rw-r--r--tests/lib/Profile/Actions/FediverseActionTest.php4
-rw-r--r--tests/lib/Remote/Api/OCSTest.php8
-rw-r--r--tests/lib/Remote/InstanceTest.php3
-rw-r--r--tests/lib/Repair/CleanTagsTest.php9
-rw-r--r--tests/lib/Repair/ClearFrontendCachesTest.php6
-rw-r--r--tests/lib/Repair/ClearGeneratedAvatarCacheTest.php5
-rw-r--r--tests/lib/Repair/NC29/SanitizeAccountPropertiesJobTest.php4
-rw-r--r--tests/lib/Repair/OldGroupMembershipSharesTest.php4
-rw-r--r--tests/lib/Repair/Owncloud/CleanPreviewsBackgroundJobTest.php20
-rw-r--r--tests/lib/Repair/Owncloud/CleanPreviewsTest.php7
-rw-r--r--tests/lib/Repair/Owncloud/UpdateLanguageCodesTest.php6
-rw-r--r--tests/lib/Repair/RepairCollationTest.php6
-rw-r--r--tests/lib/Repair/RepairInvalidSharesTest.php18
-rw-r--r--tests/lib/Repair/RepairMimeTypesTest.php8
-rw-r--r--tests/lib/RepairTest.php24
-rw-r--r--tests/lib/RichObjectStrings/DefinitionsTest.php10
-rw-r--r--tests/lib/RichObjectStrings/ValidatorTest.php4
-rw-r--r--tests/lib/Route/RouterTest.php2
-rw-r--r--tests/lib/Security/Bruteforce/Backend/MemoryCacheBackendTest.php8
-rw-r--r--tests/lib/Security/CSP/ContentSecurityPolicyManagerTest.php25
-rw-r--r--tests/lib/Security/CSRF/CsrfTokenGeneratorTest.php7
-rw-r--r--tests/lib/Security/CSRF/CsrfTokenManagerTest.php19
-rw-r--r--tests/lib/Security/CSRF/CsrfTokenTest.php8
-rw-r--r--tests/lib/Security/CSRF/TokenStorage/SessionStorageTest.php9
-rw-r--r--tests/lib/Security/CertificateManagerTest.php30
-rw-r--r--tests/lib/Security/CertificateTest.php2
-rw-r--r--tests/lib/Security/CredentialsManagerTest.php10
-rw-r--r--tests/lib/Security/CryptoTest.php10
-rw-r--r--tests/lib/Security/FeaturePolicy/FeaturePolicyManagerTest.php9
-rw-r--r--tests/lib/Security/HasherTest.php27
-rw-r--r--tests/lib/Security/Ip/BruteforceAllowListTest.php5
-rw-r--r--tests/lib/Security/Ip/RemoteAddressTest.php4
-rw-r--r--tests/lib/Security/Normalizer/IpAddressTest.php4
-rw-r--r--tests/lib/Security/RateLimiting/LimiterTest.php28
-rw-r--r--tests/lib/Security/RemoteHostValidatorIntegrationTest.php16
-rw-r--r--tests/lib/Security/RemoteHostValidatorTest.php6
-rw-r--r--tests/lib/Security/SecureRandomTest.php28
-rw-r--r--tests/lib/Security/TrustedDomainHelperTest.php6
-rw-r--r--tests/lib/ServerTest.php13
-rw-r--r--tests/lib/Session/CryptoSessionDataTest.php9
-rw-r--r--tests/lib/Session/CryptoWrappingTest.php6
-rw-r--r--tests/lib/Session/MemoryTest.php7
-rw-r--r--tests/lib/Settings/DeclarativeManagerTest.php42
-rw-r--r--tests/lib/Settings/ManagerTest.php23
-rw-r--r--tests/lib/Settings/SectionTest.php1
-rw-r--r--tests/lib/SetupCheck/CheckServerResponseTraitTest.php14
-rw-r--r--tests/lib/SetupTest.php7
-rw-r--r--tests/lib/Share/Backend.php4
-rw-r--r--tests/lib/Share/HelperTest.php17
-rw-r--r--tests/lib/Share/ShareTest.php63
-rw-r--r--tests/lib/Share20/DefaultShareProviderTest.php120
-rw-r--r--tests/lib/Share20/LegacyHooksTest.php47
-rw-r--r--tests/lib/Share20/ManagerTest.php352
-rw-r--r--tests/lib/Share20/ShareByMailProviderTest.php3
-rw-r--r--tests/lib/Share20/ShareHelperTest.php21
-rw-r--r--tests/lib/Share20/ShareTest.php12
-rw-r--r--tests/lib/SubAdminTest.php58
-rw-r--r--tests/lib/Support/Subscription/DummySubscription.php18
-rw-r--r--tests/lib/Support/Subscription/RegistryTest.php9
-rw-r--r--tests/lib/SystemTag/SystemTagManagerTest.php71
-rw-r--r--tests/lib/SystemTag/SystemTagObjectMapperTest.php11
-rw-r--r--tests/lib/TagsTest.php26
-rw-r--r--tests/lib/TaskProcessing/TaskProcessingTest.php138
-rw-r--r--tests/lib/TempManagerTest.php6
-rw-r--r--tests/lib/Template/CSSResourceLocatorTest.php1
-rw-r--r--tests/lib/Template/JSCombinerTest.php9
-rw-r--r--tests/lib/Template/JSResourceLocatorTest.php1
-rw-r--r--tests/lib/Template/ResourceLocatorTest.php5
-rw-r--r--tests/lib/TemplateFunctionsTest.php1
-rw-r--r--tests/lib/TemplateLayoutTest.php2
-rw-r--r--tests/lib/TestCase.php58
-rw-r--r--tests/lib/TestMoveableMountPoint.php5
-rw-r--r--tests/lib/TextProcessing/TextProcessingTest.php20
-rw-r--r--tests/lib/Traits/ClientServiceTrait.php1
-rw-r--r--tests/lib/Traits/EncryptionTrait.php27
-rw-r--r--tests/lib/Traits/MountProviderTrait.php12
-rw-r--r--tests/lib/Traits/UserTrait.php18
-rw-r--r--tests/lib/Updater/ChangesCheckTest.php25
-rw-r--r--tests/lib/Updater/ReleaseMetadataTest.php16
-rw-r--r--tests/lib/Updater/VersionCheckTest.php6
-rw-r--r--tests/lib/UpdaterTest.php5
-rw-r--r--tests/lib/UrlGeneratorTest.php38
-rw-r--r--tests/lib/User/AvatarUserDummy.php1
-rw-r--r--tests/lib/User/Backend.php1
-rw-r--r--tests/lib/User/DatabaseTest.php10
-rw-r--r--tests/lib/User/Dummy.php1
-rw-r--r--tests/lib/User/ManagerTest.php29
-rw-r--r--tests/lib/User/SessionTest.php89
-rw-r--r--tests/lib/User/UserTest.php68
-rw-r--r--tests/lib/Util/Group/Dummy.php1
-rw-r--r--tests/lib/Util/User/Dummy.php4
-rw-r--r--tests/lib/UtilCheckServerTest.php23
-rw-r--r--tests/lib/UtilTest.php106
413 files changed, 6917 insertions, 5950 deletions
diff --git a/tests/lib/Accounts/AccountManagerTest.php b/tests/lib/Accounts/AccountManagerTest.php
index fab3aaf5fdd..2e1dc4ec70c 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);
@@ -461,10 +462,7 @@ class AccountManagerTest extends TestCase {
->getMock();
}
- /**
- * @dataProvider dataTrueFalse
- *
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataTrueFalse')]
public function testUpdateUser(array $newData, array $oldData, bool $insertNew, bool $updateExisting): void {
$accountManager = $this->getInstance(['getUser', 'insertNewUser', 'updateExistingUser']);
/** @var IUser $user */
@@ -488,7 +486,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());
@@ -499,7 +497,7 @@ class AccountManagerTest extends TestCase {
$this->invokePrivate($accountManager, 'updateUser', [$user, $newData, $oldData]);
}
- public function dataTrueFalse(): array {
+ public static function dataTrueFalse(): array {
return [
#$newData | $oldData | $insertNew | $updateExisting
[['myProperty' => ['value' => 'newData']], ['myProperty' => ['value' => 'oldData']], false, true],
@@ -683,9 +681,7 @@ class AccountManagerTest extends TestCase {
];
}
- /**
- * @dataProvider dataParsePhoneNumber
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataParsePhoneNumber')]
public function testSanitizePhoneNumberOnUpdateAccount(string $phoneInput, string $defaultRegion, ?string $phoneNumber): void {
$this->config->method('getSystemValueString')
->willReturn($defaultRegion);
@@ -737,9 +733,7 @@ class AccountManagerTest extends TestCase {
];
}
- /**
- * @dataProvider dataSanitizeOnUpdate
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataSanitizeOnUpdate')]
public function testSanitizingOnUpdateAccount(string $property, string $input, ?string $output): void {
if ($property === IAccountManager::PROPERTY_FEDIVERSE) {
@@ -822,9 +816,7 @@ class AccountManagerTest extends TestCase {
];
}
- /**
- * @dataProvider dataSanitizeFediverseServer
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataSanitizeFediverseServer')]
public function testSanitizingFediverseServer(string $input, ?string $output, bool $hasInternet, ?string $serverResponse): void {
$this->config->expects(self::once())
->method('getSystemValueBool')
@@ -881,9 +873,7 @@ class AccountManagerTest extends TestCase {
}
}
- /**
- * @dataProvider searchDataProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('searchDataProvider')]
public function testSearchUsers(string $property, array $values, array $expected): void {
$this->populateOrUpdate();
@@ -896,7 +886,7 @@ class AccountManagerTest extends TestCase {
}
}
- public function searchDataProvider(): array {
+ public static function searchDataProvider(): array {
return [
[ #0 Search for an existing name
IAccountManager::PROPERTY_DISPLAYNAME,
@@ -948,21 +938,20 @@ class AccountManagerTest extends TestCase {
];
}
- public function dataCheckEmailVerification(): array {
+ public static function dataCheckEmailVerification(): array {
return [
- [$this->makeUser('steve', 'Steve Smith', 'steve@steve.steve'), null],
- [$this->makeUser('emma', 'Emma Morales', 'emma@emma.com'), 'emma@morales.com'],
- [$this->makeUser('sarah@web.org', 'Sarah Foster', 'sarah@web.org'), null],
- [$this->makeUser('cole@web.org', 'Cole Harrison', 'cole@web.org'), 'cole@example.com'],
- [$this->makeUser('8d29e358-cf69-4849-bbf9-28076c0b908b', 'Alice McPherson', 'alice@example.com'), 'alice@mcpherson.com'],
- [$this->makeUser('11da2744-3f4d-4c17-8c13-4c057a379237', 'James Loranger', 'james@example.com'), ''],
+ [['steve', 'Steve Smith', 'steve@steve.steve'], null],
+ [['emma', 'Emma Morales', 'emma@emma.com'], 'emma@morales.com'],
+ [['sarah@web.org', 'Sarah Foster', 'sarah@web.org'], null],
+ [['cole@web.org', 'Cole Harrison', 'cole@web.org'], 'cole@example.com'],
+ [['8d29e358-cf69-4849-bbf9-28076c0b908b', 'Alice McPherson', 'alice@example.com'], 'alice@mcpherson.com'],
+ [['11da2744-3f4d-4c17-8c13-4c057a379237', 'James Loranger', 'james@example.com'], ''],
];
}
- /**
- * @dataProvider dataCheckEmailVerification
- */
- public function testCheckEmailVerification(IUser $user, ?string $newEmail): void {
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataCheckEmailVerification')]
+ public function testCheckEmailVerification(array $userData, ?string $newEmail): void {
+ $user = $this->makeUser(...$userData);
// Once because of getAccount, once because of getUser
$this->config->expects($this->exactly(2))->method('getSystemValue')->with('account_manager.default_property_scope', [])->willReturn([]);
$account = $this->accountManager->getAccount($user);
@@ -988,7 +977,7 @@ class AccountManagerTest extends TestCase {
$this->invokePrivate($this->accountManager, 'checkEmailVerification', [$account, $oldData]);
}
- public function dataSetDefaultPropertyScopes(): array {
+ public static function dataSetDefaultPropertyScopes(): array {
return [
[
[],
@@ -1025,9 +1014,7 @@ class AccountManagerTest extends TestCase {
];
}
- /**
- * @dataProvider dataSetDefaultPropertyScopes
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataSetDefaultPropertyScopes')]
public function testSetDefaultPropertyScopes(array $propertyScopes, array $expectedResultScopes): void {
$user = $this->makeUser('steve', 'Steve Smith', 'steve@steve.steve');
$this->config->expects($this->once())->method('getSystemValue')->with('account_manager.default_property_scope', [])->willReturn($propertyScopes);
diff --git a/tests/lib/Accounts/AccountPropertyTest.php b/tests/lib/Accounts/AccountPropertyTest.php
index 5df66eaa117..b92e45176a3 100644
--- a/tests/lib/Accounts/AccountPropertyTest.php
+++ b/tests/lib/Accounts/AccountPropertyTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2018 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
@@ -56,27 +57,20 @@ class AccountPropertyTest extends TestCase {
$this->assertEquals(IAccountManager::SCOPE_LOCAL, $actualReturn->getScope());
}
- public function scopesProvider() {
+ public static function scopesProvider(): array {
return [
// current values
[IAccountManager::SCOPE_PRIVATE, IAccountManager::SCOPE_PRIVATE],
[IAccountManager::SCOPE_LOCAL, IAccountManager::SCOPE_LOCAL],
[IAccountManager::SCOPE_FEDERATED, IAccountManager::SCOPE_FEDERATED],
[IAccountManager::SCOPE_PUBLISHED, IAccountManager::SCOPE_PUBLISHED],
- // legacy values
- [IAccountManager::VISIBILITY_PRIVATE, IAccountManager::SCOPE_LOCAL],
- [IAccountManager::VISIBILITY_CONTACTS_ONLY, IAccountManager::SCOPE_FEDERATED],
- [IAccountManager::VISIBILITY_PUBLIC, IAccountManager::SCOPE_PUBLISHED],
- ['', IAccountManager::SCOPE_LOCAL],
// invalid values
['unknown', null],
['v2-unknown', null],
];
}
- /**
- * @dataProvider scopesProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('scopesProvider')]
public function testSetScopeMapping(string $storedScope, ?string $returnedScope): void {
if ($returnedScope === null) {
$this->expectException(\InvalidArgumentException::class);
diff --git a/tests/lib/Accounts/AccountTest.php b/tests/lib/Accounts/AccountTest.php
index 34653bd864a..514ff17e58e 100644
--- a/tests/lib/Accounts/AccountTest.php
+++ b/tests/lib/Accounts/AccountTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2018 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
diff --git a/tests/lib/Accounts/HooksTest.php b/tests/lib/Accounts/HooksTest.php
index 75772089f43..622fb3c7461 100644
--- a/tests/lib/Accounts/HooksTest.php
+++ b/tests/lib/Accounts/HooksTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
@@ -43,7 +44,6 @@ class HooksTest extends TestCase {
}
/**
- * @dataProvider dataTestChangeUserHook
*
* @param $params
* @param $data
@@ -51,6 +51,7 @@ class HooksTest extends TestCase {
* @param $setDisplayName
* @param $error
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataTestChangeUserHook')]
public function testChangeUserHook($params, $data, $setEmail, $setDisplayName, $error): void {
if ($error) {
$this->accountManager->expects($this->never())->method('updateAccount');
@@ -96,14 +97,14 @@ class HooksTest extends TestCase {
}
}
+ $params['user'] = $this->createMock(IUser::class);
$this->hooks->changeUserHook($params['user'], $params['feature'], $params['value']);
}
- public function dataTestChangeUserHook() {
- $user = $this->createMock(IUser::class);
+ public static function dataTestChangeUserHook(): array {
return [
[
- ['user' => $user, 'feature' => '', 'value' => ''],
+ ['feature' => '', 'value' => ''],
[
IAccountManager::PROPERTY_EMAIL => ['value' => ''],
IAccountManager::PROPERTY_DISPLAYNAME => ['value' => '']
@@ -111,7 +112,7 @@ class HooksTest extends TestCase {
false, false, true
],
[
- ['user' => $user, 'feature' => 'foo', 'value' => 'bar'],
+ ['feature' => 'foo', 'value' => 'bar'],
[
IAccountManager::PROPERTY_EMAIL => ['value' => 'oldMail@example.com'],
IAccountManager::PROPERTY_DISPLAYNAME => ['value' => 'oldDisplayName']
@@ -119,7 +120,7 @@ class HooksTest extends TestCase {
false, false, false
],
[
- ['user' => $user, 'feature' => 'eMailAddress', 'value' => 'newMail@example.com'],
+ ['feature' => 'eMailAddress', 'value' => 'newMail@example.com'],
[
IAccountManager::PROPERTY_EMAIL => ['value' => 'oldMail@example.com'],
IAccountManager::PROPERTY_DISPLAYNAME => ['value' => 'oldDisplayName']
@@ -127,7 +128,7 @@ class HooksTest extends TestCase {
true, false, false
],
[
- ['user' => $user, 'feature' => 'displayName', 'value' => 'newDisplayName'],
+ ['feature' => 'displayName', 'value' => 'newDisplayName'],
[
IAccountManager::PROPERTY_EMAIL => ['value' => 'oldMail@example.com'],
IAccountManager::PROPERTY_DISPLAYNAME => ['value' => 'oldDisplayName']
diff --git a/tests/lib/Activity/ManagerTest.php b/tests/lib/Activity/ManagerTest.php
index 61eeee82c43..db0bedce359 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;
@@ -74,7 +76,7 @@ class ManagerTest extends TestCase {
self::invokePrivate($this->activityManager, 'getConsumers');
}
- public function getUserFromTokenThrowInvalidTokenData() {
+ public static function getUserFromTokenThrowInvalidTokenData(): array {
return [
[null, []],
['', []],
@@ -86,11 +88,11 @@ class ManagerTest extends TestCase {
}
/**
- * @dataProvider getUserFromTokenThrowInvalidTokenData
*
* @param string $token
* @param array $users
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('getUserFromTokenThrowInvalidTokenData')]
public function testGetUserFromTokenThrowInvalidToken($token, $users): void {
$this->expectException(\UnexpectedValueException::class);
@@ -98,7 +100,7 @@ class ManagerTest extends TestCase {
self::invokePrivate($this->activityManager, 'getUserFromToken');
}
- public function getUserFromTokenData() {
+ public static function getUserFromTokenData(): array {
return [
[null, '123456789012345678901234567890', 'user1'],
['user2', null, 'user2'],
@@ -107,12 +109,12 @@ class ManagerTest extends TestCase {
}
/**
- * @dataProvider getUserFromTokenData
*
* @param string $userLoggedIn
* @param string $token
* @param string $expected
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('getUserFromTokenData')]
public function testGetUserFromToken($userLoggedIn, $token, $expected): void {
if ($userLoggedIn !== null) {
$this->mockUserSession($userLoggedIn);
@@ -190,7 +192,7 @@ class ManagerTest extends TestCase {
$this->activityManager->publish($event);
}
- public function dataPublish() {
+ public static function dataPublish(): array {
return [
[null, ''],
['test_author', 'test_author'],
@@ -198,10 +200,10 @@ class ManagerTest extends TestCase {
}
/**
- * @dataProvider dataPublish
* @param string|null $author
* @param string $expected
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataPublish')]
public function testPublish($author, $expected): void {
if ($author !== null) {
$authorObject = $this->getMockBuilder(IUser::class)
@@ -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 e892e441ecf..80a38d590f4 100644
--- a/tests/lib/AllConfigTest.php
+++ b/tests/lib/AllConfigTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -14,17 +15,19 @@ 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 */
+ /** @var IDBConnection */
protected $connection;
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 +37,7 @@ class AllConfigTest extends \Test\TestCase {
->disableOriginalConstructor()
->getMock();
}
- return new \OC\AllConfig($systemConfig, $connection);
+ return new AllConfig($systemConfig, $connection);
}
public function testDeleteUserValue(): void {
@@ -42,8 +45,8 @@ class AllConfigTest extends \Test\TestCase {
// preparation - add something to the database
$this->connection->executeUpdate(
- 'INSERT INTO `*PREFIX*preferences` (`userid`, `appid`, ' .
- '`configkey`, `configvalue`) VALUES (?, ?, ?, ?)',
+ 'INSERT INTO `*PREFIX*preferences` (`userid`, `appid`, '
+ . '`configkey`, `configvalue`) VALUES (?, ?, ?, ?)',
['userDelete', 'appDelete', 'keyDelete', 'valueDelete']
);
@@ -91,6 +94,27 @@ class AllConfigTest extends \Test\TestCase {
$config->deleteUserValue('userSet', 'appSet', 'keySet');
}
+ /**
+ * This test needs to stay! Emails are expected to be lowercase due to performance reasons.
+ * This way we can skip the expensive casing change on the database.
+ */
+ public function testSetUserValueSettingsEmail(): void {
+ $selectAllSQL = 'SELECT `userid`, `appid`, `configkey`, `configvalue` FROM `*PREFIX*preferences` WHERE `userid` = ?';
+ $config = $this->getConfig();
+
+ $config->setUserValue('userSet', 'settings', 'email', 'mixed.CASE@domain.COM');
+
+ $result = $this->connection->executeQuery($selectAllSQL, ['userSet'])->fetchAll();
+
+ $this->assertEquals(1, count($result));
+ $this->assertEquals([
+ 'userid' => 'userSet',
+ 'appid' => 'settings',
+ 'configkey' => 'email',
+ 'configvalue' => 'mixed.case@domain.com'
+ ], $result[0]);
+ }
+
public function testSetUserValueWithPreCondition(): void {
$config = $this->getConfig();
@@ -125,7 +149,7 @@ class AllConfigTest extends \Test\TestCase {
$config->deleteUserValue('userPreCond', 'appPreCond', 'keyPreCond');
}
- public function dataSetUserValueUnexpectedValue() {
+ public static function dataSetUserValueUnexpectedValue(): array {
return [
[true],
[false],
@@ -135,9 +159,9 @@ class AllConfigTest extends \Test\TestCase {
}
/**
- * @dataProvider dataSetUserValueUnexpectedValue
* @param mixed $value
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataSetUserValueUnexpectedValue')]
public function testSetUserValueUnexpectedValue($value): void {
$this->expectException(\UnexpectedValueException::class);
@@ -147,7 +171,7 @@ class AllConfigTest extends \Test\TestCase {
public function testSetUserValueWithPreConditionFailure(): void {
- $this->expectException(\OCP\PreConditionNotMetException::class);
+ $this->expectException(PreConditionNotMetException::class);
$config = $this->getConfig();
@@ -183,7 +207,7 @@ class AllConfigTest extends \Test\TestCase {
}
public function testSetUserValueWithPreConditionFailureWhenResultStillMatches(): void {
- $this->expectException(\OCP\PreConditionNotMetException::class);
+ $this->expectException(PreConditionNotMetException::class);
$config = $this->getConfig();
@@ -231,8 +255,8 @@ class AllConfigTest extends \Test\TestCase {
$connectionMock = $this->createMock(IDBConnection::class);
$connectionMock->expects($this->once())
->method('executeQuery')
- ->with($this->equalTo('SELECT `configvalue` FROM `*PREFIX*preferences` ' .
- 'WHERE `userid` = ? AND `appid` = ? AND `configkey` = ?'),
+ ->with($this->equalTo('SELECT `configvalue` FROM `*PREFIX*preferences` '
+ . 'WHERE `userid` = ? AND `appid` = ? AND `configkey` = ?'),
$this->equalTo(['userSetUnchanged', 'appSetUnchanged', 'keySetUnchanged']))
->willReturn($resultMock);
$connectionMock->expects($this->never())
@@ -296,8 +320,8 @@ class AllConfigTest extends \Test\TestCase {
];
foreach ($data as $entry) {
$this->connection->executeUpdate(
- 'INSERT INTO `*PREFIX*preferences` (`userid`, `appid`, ' .
- '`configkey`, `configvalue`) VALUES (?, ?, ?, ?)',
+ 'INSERT INTO `*PREFIX*preferences` (`userid`, `appid`, '
+ . '`configkey`, `configvalue`) VALUES (?, ?, ?, ?)',
$entry
);
}
@@ -322,8 +346,8 @@ class AllConfigTest extends \Test\TestCase {
];
foreach ($data as $entry) {
$this->connection->executeUpdate(
- 'INSERT INTO `*PREFIX*preferences` (`userid`, `appid`, ' .
- '`configkey`, `configvalue`) VALUES (?, ?, ?, ?)',
+ 'INSERT INTO `*PREFIX*preferences` (`userid`, `appid`, '
+ . '`configkey`, `configvalue`) VALUES (?, ?, ?, ?)',
$entry
);
}
@@ -360,8 +384,8 @@ class AllConfigTest extends \Test\TestCase {
];
foreach ($data as $entry) {
$this->connection->executeUpdate(
- 'INSERT INTO `*PREFIX*preferences` (`userid`, `appid`, ' .
- '`configkey`, `configvalue`) VALUES (?, ?, ?, ?)',
+ 'INSERT INTO `*PREFIX*preferences` (`userid`, `appid`, '
+ . '`configkey`, `configvalue`) VALUES (?, ?, ?, ?)',
$entry
);
}
@@ -401,8 +425,8 @@ class AllConfigTest extends \Test\TestCase {
];
foreach ($data as $entry) {
$this->connection->executeUpdate(
- 'INSERT INTO `*PREFIX*preferences` (`userid`, `appid`, ' .
- '`configkey`, `configvalue`) VALUES (?, ?, ?, ?)',
+ 'INSERT INTO `*PREFIX*preferences` (`userid`, `appid`, '
+ . '`configkey`, `configvalue`) VALUES (?, ?, ?, ?)',
$entry
);
}
@@ -435,8 +459,8 @@ class AllConfigTest extends \Test\TestCase {
];
foreach ($data as $entry) {
$this->connection->executeUpdate(
- 'INSERT INTO `*PREFIX*preferences` (`userid`, `appid`, ' .
- '`configkey`, `configvalue`) VALUES (?, ?, ?, ?)',
+ 'INSERT INTO `*PREFIX*preferences` (`userid`, `appid`, '
+ . '`configkey`, `configvalue`) VALUES (?, ?, ?, ?)',
$entry
);
}
@@ -481,8 +505,8 @@ class AllConfigTest extends \Test\TestCase {
];
foreach ($data as $entry) {
$this->connection->executeUpdate(
- 'INSERT INTO `*PREFIX*preferences` (`userid`, `appid`, ' .
- '`configkey`, `configvalue`) VALUES (?, ?, ?, ?)',
+ 'INSERT INTO `*PREFIX*preferences` (`userid`, `appid`, '
+ . '`configkey`, `configvalue`) VALUES (?, ?, ?, ?)',
$entry
);
}
diff --git a/tests/lib/App/AppManagerTest.php b/tests/lib/App/AppManagerTest.php
index 19039366aa8..6637c529a1e 100644
--- a/tests/lib/App/AppManagerTest.php
+++ b/tests/lib/App/AppManagerTest.php
@@ -12,6 +12,7 @@ namespace Test\App;
use OC\App\AppManager;
use OC\AppConfig;
+use OC\Config\ConfigManager;
use OCP\App\AppPathNotFoundException;
use OCP\App\Events\AppDisableEvent;
use OCP\App\Events\AppEnableEvent;
@@ -36,10 +37,7 @@ use Test\TestCase;
* @package Test\App
*/
class AppManagerTest extends TestCase {
- /**
- * @return AppConfig|MockObject
- */
- protected function getAppConfig() {
+ protected function getAppConfig(): AppConfig&MockObject {
$appConfig = [];
$config = $this->createMock(AppConfig::class);
@@ -50,7 +48,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] = [];
}
@@ -71,37 +69,32 @@ class AppManagerTest extends TestCase {
return $values;
}
});
+ $config->expects($this->any())
+ ->method('searchValues')
+ ->willReturnCallback(function ($key, $lazy, $type) use (&$appConfig) {
+ $values = [];
+ foreach ($appConfig as $appid => $appData) {
+ if (isset($appData[$key])) {
+ $values[$appid] = $appData[$key];
+ }
+ }
+ return $values;
+ });
return $config;
}
- /** @var IUserSession|MockObject */
- protected $userSession;
-
- /** @var IConfig|MockObject */
- private $config;
-
- /** @var IGroupManager|MockObject */
- protected $groupManager;
-
- /** @var AppConfig|MockObject */
- protected $appConfig;
-
- /** @var ICache|MockObject */
- protected $cache;
-
- /** @var ICacheFactory|MockObject */
- protected $cacheFactory;
-
- /** @var IEventDispatcher|MockObject */
- protected $eventDispatcher;
-
- /** @var LoggerInterface|MockObject */
- protected $logger;
-
+ protected IUserSession&MockObject $userSession;
+ private IConfig&MockObject $config;
+ protected IGroupManager&MockObject $groupManager;
+ protected AppConfig&MockObject $appConfig;
+ protected ICache&MockObject $cache;
+ protected ICacheFactory&MockObject $cacheFactory;
+ protected IEventDispatcher&MockObject $eventDispatcher;
+ protected LoggerInterface&MockObject $logger;
protected IURLGenerator&MockObject $urlGenerator;
-
protected ServerVersion&MockObject $serverVersion;
+ protected ConfigManager&MockObject $configManager;
/** @var IAppManager */
protected $manager;
@@ -119,6 +112,7 @@ class AppManagerTest extends TestCase {
$this->logger = $this->createMock(LoggerInterface::class);
$this->urlGenerator = $this->createMock(IURLGenerator::class);
$this->serverVersion = $this->createMock(ServerVersion::class);
+ $this->configManager = $this->createMock(ConfigManager::class);
$this->overwriteService(AppConfig::class, $this->appConfig);
$this->overwriteService(IURLGenerator::class, $this->urlGenerator);
@@ -141,12 +135,11 @@ class AppManagerTest extends TestCase {
$this->eventDispatcher,
$this->logger,
$this->serverVersion,
+ $this->configManager,
);
}
- /**
- * @dataProvider dataGetAppIcon
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataGetAppIcon')]
public function testGetAppIcon($callback, ?bool $dark, ?string $expected): void {
$this->urlGenerator->expects($this->atLeastOnce())
->method('imagePath')
@@ -159,15 +152,15 @@ class AppManagerTest extends TestCase {
}
}
- public function dataGetAppIcon(): array {
- $nothing = function ($appId) {
- $this->assertEquals('test', $appId);
+ public static function dataGetAppIcon(): array {
+ $nothing = function ($appId): void {
+ self::assertEquals('test', $appId);
throw new \RuntimeException();
};
$createCallback = function ($workingIcons) {
return function ($appId, $icon) use ($workingIcons) {
- $this->assertEquals('test', $appId);
+ self::assertEquals('test', $appId);
if (in_array($icon, $workingIcons)) {
return '/path/' . $icon;
}
@@ -284,6 +277,7 @@ class AppManagerTest extends TestCase {
$this->eventDispatcher,
$this->logger,
$this->serverVersion,
+ $this->configManager,
])
->onlyMethods([
'getAppPath',
@@ -301,7 +295,7 @@ class AppManagerTest extends TestCase {
$this->assertEquals('["group1","group2"]', $this->appConfig->getValue('test', 'enabled', 'no'));
}
- public function dataEnableAppForGroupsAllowedTypes() {
+ public static function dataEnableAppForGroupsAllowedTypes(): array {
return [
[[]],
[[
@@ -314,10 +308,9 @@ class AppManagerTest extends TestCase {
}
/**
- * @dataProvider dataEnableAppForGroupsAllowedTypes
- *
* @param array $appInfo
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataEnableAppForGroupsAllowedTypes')]
public function testEnableAppForGroupsAllowedTypes(array $appInfo): void {
$group1 = $this->createMock(IGroup::class);
$group1->method('getGID')
@@ -338,6 +331,7 @@ class AppManagerTest extends TestCase {
$this->eventDispatcher,
$this->logger,
$this->serverVersion,
+ $this->configManager,
])
->onlyMethods([
'getAppPath',
@@ -361,7 +355,7 @@ class AppManagerTest extends TestCase {
$this->assertEquals('["group1","group2"]', $this->appConfig->getValue('test', 'enabled', 'no'));
}
- public function dataEnableAppForGroupsForbiddenTypes() {
+ public static function dataEnableAppForGroupsForbiddenTypes(): array {
return [
['filesystem'],
['prelogin'],
@@ -372,11 +366,11 @@ class AppManagerTest extends TestCase {
}
/**
- * @dataProvider dataEnableAppForGroupsForbiddenTypes
*
* @param string $type
*
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataEnableAppForGroupsForbiddenTypes')]
public function testEnableAppForGroupsForbiddenTypes($type): void {
$this->expectException(\Exception::class);
$this->expectExceptionMessage('test can\'t be enabled for groups.');
@@ -400,6 +394,7 @@ class AppManagerTest extends TestCase {
$this->eventDispatcher,
$this->logger,
$this->serverVersion,
+ $this->configManager,
])
->onlyMethods([
'getAppPath',
@@ -605,6 +600,7 @@ class AppManagerTest extends TestCase {
$this->eventDispatcher,
$this->logger,
$this->serverVersion,
+ $this->configManager,
])
->onlyMethods(['getAppInfo'])
->getMock();
@@ -665,6 +661,7 @@ class AppManagerTest extends TestCase {
$this->eventDispatcher,
$this->logger,
$this->serverVersion,
+ $this->configManager,
])
->onlyMethods(['getAppInfo'])
->getMock();
@@ -776,9 +773,7 @@ class AppManagerTest extends TestCase {
];
}
- /**
- * @dataProvider isBackendRequiredDataProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('isBackendRequiredDataProvider')]
public function testIsBackendRequired(
string $backend,
array $appBackends,
@@ -806,6 +801,7 @@ class AppManagerTest extends TestCase {
$this->eventDispatcher,
$this->logger,
$this->serverVersion,
+ $this->configManager,
])
->onlyMethods([
'getAppInfo',
@@ -837,6 +833,7 @@ class AppManagerTest extends TestCase {
$this->eventDispatcher,
$this->logger,
$this->serverVersion,
+ $this->configManager,
])
->onlyMethods([
'getAppInfo',
@@ -867,6 +864,7 @@ class AppManagerTest extends TestCase {
$this->eventDispatcher,
$this->logger,
$this->serverVersion,
+ $this->configManager,
])
->onlyMethods([
'getAppInfo',
diff --git a/tests/lib/App/AppStore/Bundles/BundleBase.php b/tests/lib/App/AppStore/Bundles/BundleBase.php
index 28fb8a7736b..71acaa052b3 100644
--- a/tests/lib/App/AppStore/Bundles/BundleBase.php
+++ b/tests/lib/App/AppStore/Bundles/BundleBase.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2017 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
diff --git a/tests/lib/App/AppStore/Bundles/BundleFetcherTest.php b/tests/lib/App/AppStore/Bundles/BundleFetcherTest.php
index 225dd78a1b4..ab6f5502fde 100644
--- a/tests/lib/App/AppStore/Bundles/BundleFetcherTest.php
+++ b/tests/lib/App/AppStore/Bundles/BundleFetcherTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2017 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
diff --git a/tests/lib/App/AppStore/Bundles/EducationBundleTest.php b/tests/lib/App/AppStore/Bundles/EducationBundleTest.php
index 50942d8df97..88a3b2d8d67 100644
--- a/tests/lib/App/AppStore/Bundles/EducationBundleTest.php
+++ b/tests/lib/App/AppStore/Bundles/EducationBundleTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2017 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
diff --git a/tests/lib/App/AppStore/Bundles/EnterpriseBundleTest.php b/tests/lib/App/AppStore/Bundles/EnterpriseBundleTest.php
index 464d48102b2..a02ee11d15c 100644
--- a/tests/lib/App/AppStore/Bundles/EnterpriseBundleTest.php
+++ b/tests/lib/App/AppStore/Bundles/EnterpriseBundleTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2017 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
diff --git a/tests/lib/App/AppStore/Bundles/GroupwareBundleTest.php b/tests/lib/App/AppStore/Bundles/GroupwareBundleTest.php
index 5ba9ee4c4e1..be756dbc55e 100644
--- a/tests/lib/App/AppStore/Bundles/GroupwareBundleTest.php
+++ b/tests/lib/App/AppStore/Bundles/GroupwareBundleTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2017 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
diff --git a/tests/lib/App/AppStore/Bundles/SocialSharingBundleTest.php b/tests/lib/App/AppStore/Bundles/SocialSharingBundleTest.php
index a2681cb0238..f3437fb51e6 100644
--- a/tests/lib/App/AppStore/Bundles/SocialSharingBundleTest.php
+++ b/tests/lib/App/AppStore/Bundles/SocialSharingBundleTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2017 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
diff --git a/tests/lib/App/AppStore/Fetcher/AppDiscoverFetcherTest.php b/tests/lib/App/AppStore/Fetcher/AppDiscoverFetcherTest.php
index e7652d5c50c..b9866396662 100644
--- a/tests/lib/App/AppStore/Fetcher/AppDiscoverFetcherTest.php
+++ b/tests/lib/App/AppStore/Fetcher/AppDiscoverFetcherTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
@@ -71,9 +72,7 @@ class AppDiscoverFetcherTest extends FetcherBase {
$this->assertEquals([], $this->fetcher->get());
}
- /**
- * @dataProvider dataGetETag
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataGetETag')]
public function testGetEtag(?string $expected, bool $throws, string $content = ''): void {
$folder = $this->createMock(ISimpleFolder::class);
if (!$throws) {
@@ -104,7 +103,7 @@ class AppDiscoverFetcherTest extends FetcherBase {
}
}
- public function dataGetETag(): array {
+ public static function dataGetETag(): array {
return [
'file not found' => [null, true],
'empty file' => [null, false, ''],
diff --git a/tests/lib/App/AppStore/Fetcher/AppFetcherTest.php b/tests/lib/App/AppStore/Fetcher/AppFetcherTest.php
index 61fe24be1a9..a6dd801aca8 100644
--- a/tests/lib/App/AppStore/Fetcher/AppFetcherTest.php
+++ b/tests/lib/App/AppStore/Fetcher/AppFetcherTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
@@ -45,13 +46,13 @@ class AppFetcherTest extends TestCase {
[{"id":"direct_menu","categories":["customization"],"userDocs":"","adminDocs":"","developerDocs":"","issueTracker":"https://github.com/juliushaertl/direct_menu/issues","website":"","created":"2016-10-01T09:16:06.030994Z","lastModified":"2016-10-06T14:01:05.584192Z","releases":[{"version":"0.9.2","phpExtensions":[],"databases":[],"shellCommands":[],"phpVersionSpec":"*","platformVersionSpec":">=9.0.0 <12.0.0","minIntSize":32,"download":"https://github.com/juliushaertl/direct_menu/releases/download/v0.9.2/direct_menu.tar.gz","created":"2016-10-06T14:01:05.578297Z","licenses":["agpl"],"lastModified":"2016-10-06T14:01:05.643813Z","isNightly":false,"rawPhpVersionSpec":"*","rawPlatformVersionSpec":">=9 <=11","signature":"ERBS9G5bZ3vwCizz2Ht5DehsVJmb63bzF3aYcH7xjbDVMPagOFWdUAiLDwTeZR1n\ni4gdZ73J/IjHQQJoOPwtCjgbZgLPFqL5x13CLUO9mb/33dZe/+gqEDc/3AuJ4TlA\nXUdLxHRb1bwIlJOwuSr/E24452VG20WUhLXBoM0Zm7WcMxvJWo2zAWnuqnLX3dy9\ncPB4PX+6JU2lUMINj8OYQmM1QnqvjG8YV0cYHbBbnSicOGwXEnni7mojsC8T0cn7\nYEJ2O2iO9hh3fvFEXUzDcL7tDQ5bZqm63Oa991bsAJxFo/RbzeJRh//DcOrd8Ufn\nu2SqRhwybS8j4YvfjAL9RPdRfPLwf6X2gx/Y6QFrKHH0QMI/9J/ZFyoUQcqKbsHV\n85O+yuWoqVmza71tkp4n9PuMdprCinaVvHbHbNGUf2SIh9BWuEQuVvvnvB+ZW8XY\n+Cl+unzk3WgOgT0iY3uEmsQcrLIo4DSKhcNgD1NS13fR/JTSavvmOqBarUMFZfVC\nbkR1DTBCyDjdpNBidpa3/26675dz5IT5Zedp4BBBREQzX08cIhJx5mgqDdX3CU09\nuWtzoaLi71/1BWTFAN+Y9VyfZ8/Z3Pg3vKedRJ565mztIj0geL3riEsC5YnPS0+C\n+a3B9sDiiOa101EORzX3lrPqL7reEPdCxrIwN+hKFBQ=","translations":{}}],"screenshots":[{"url":"https://bitgrid.net/~jus/direct_menu_nc.png"}],"translations":{"en":{"name":"Direct Menu","summary":"Provide easy access to all apps in the header.","description":"Provide easy access to all apps in the header."}},"isFeatured":false,"authors":[{"name":"Julius Härtl","mail":"","homepage":""}],"ratingRecent":0.5,"ratingOverall":0.5,"ratingNumRecent":0,"ratingNumOverall":0,"certificate":"-----BEGIN CERTIFICATE-----\r\nMIIEBjCCAu4CAhADMA0GCSqGSIb3DQEBCwUAMHsxCzAJBgNVBAYTAkRFMRswGQYD\r\nVQQIDBJCYWRlbi1XdWVydHRlbWJlcmcxFzAVBgNVBAoMDk5leHRjbG91ZCBHbWJI\r\nMTYwNAYDVQQDDC1OZXh0Y2xvdWQgQ29kZSBTaWduaW5nIEludGVybWVkaWF0ZSBB\r\ndXRob3JpdHkwHhcNMTYwOTE0MTI1MDU0WhcNMjYxMjIxMTI1MDU0WjAWMRQwEgYD\r\nVQQDDAtkaXJlY3RfbWVudTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIB\r\nAMkzWsAkKP/40ktvJMpnr0IJNVoPOR0hvh24igcDskL1WKiD2eiRUenj5LE0Nvn+\r\nsiGmWsAqRVpdiz+Y8ghQqQMzKi43IrRN0AxlCrHWrSqBZT3wIAUcFz4RzEoFxc1N\r\nUZzWma6ljukGnvt4V1ZyT+H/cjqxUkBhh/y9SS0jUen1a1grND6Rw54X46V2dlCu\r\nFH+pLsfPJJGw+QLeTGHn7dqdv18cYMAlWDCzPixVnNiCXHZcUtKMmstU2xU4R2e6\r\nzimp2rgkE4TNHrafpjH8xGdNi2FG5Dmokob/L5Q2r8jyNaW7UsFfrvLTRj371b3/\r\n2FhhxoGUvDzaG2An02Exwm52LJfdTVMHAMPZub5poHfy5vAEdZGPQ/m02l8ZK/Y2\r\n7yT807GlfPMXfdfjCxR6wNtmv7rvBDdrUZmIRNJfpFSdvlH/+MOTWnabyfQv2K4Q\r\nBIwltX6Elh0lh4ntvt1ZVtvFv+PL1Dc7QLV+w19+/LJA0mnsh7GIFYKFlbA65gA0\r\nc/w+uqDy0+5MxkR9WGPpd79KRA1tKWTis4Ny1lApK5y3zIsVGa3DfBHXcwqkWHbV\r\nwIpyuyyDsFtC1b9LTFONX7iU9cbNk5C5GTM331MdA2kLcD/D5k42GNTBSca7MkPx\r\nFx/ETSn0Ct167el30symf2AxvXjw+mBYPN71rVTMDwe9AgMBAAEwDQYJKoZIhvcN\r\nAQELBQADggEBAC0fJKnbEhXA8M283jA9GxABxLyTBcQyVVNnz2L/bYYNi81Y9iZv\r\n+U0S3qaIfoqNcV9FTKAutbsKvWyolnI7MRRK6feNuFfoP2jKubM1CnawpyT/RF2Q\r\ne/zxnB1EmeI2X5D2xceJDLB7Fy5W0EGrLixRIdFaSUommWFUm9E2hSIaNlziSBdc\r\n1J/mOQeNYO5zg5ouEt1rzQW4Mhh1I2uNQmGe4ip+Jl/2LAv3FZuu4NrSEcoXH3ro\r\nG2dF9Gtu4GiQ5fuaJknaxlgXHovfqeZwZJX9o4M+Ug81AqiY7XjdiaCPdh0Tthcx\r\n2OmWZo7UBREWenjKyFZZ/iKoqH5sdenBtpo=\r\n-----END CERTIFICATE-----"},{"id":"apporder","categories":["customization"],"userDocs":"","adminDocs":"","developerDocs":"","issueTracker":"https://github.com/juliushaertl/apporder/issues","website":"","created":"2016-10-01T09:16:47.111889Z","lastModified":"2016-10-12T19:50:16.038821Z","releases":[{"version":"0.3.3","phpExtensions":[],"databases":[],"shellCommands":[],"phpVersionSpec":"*","platformVersionSpec":">=9.0.0 <12.0.0","minIntSize":32,"download":"https://github.com/juliushaertl/apporder/releases/download/0.3.3/apporder.tar.gz","created":"2016-10-12T19:14:10.802359Z","licenses":["agpl"],"lastModified":"2016-10-12T19:50:16.104357Z","isNightly":false,"rawPhpVersionSpec":"*","rawPlatformVersionSpec":">=9 <=11","signature":"nhlT9lhrmBxIsqh/e3RLm2NDw/U8ZvvoMyYQTLMM3H19DQmVcPYPYC9QWVTsowUzXblVaOXVGylbpKma9yOlOAqJtF3qyXecLl4+tA/Awb6BBhKPgHFdcLDAL5yy1K7/uei3SgEojMlJoI9vEK5I1C5YTh43yNH+//Im6MAuNYFUTlMXK426zdOe6ogpCI5GlYdXopqYANxcpT+WXWET6DDSM5Ev+MYwMcSAY4r8+tvARRU4ZAenRgjkBT6R5z6cD76emRax14tbV6vkjjwRcO+dQtM0tFPbd+5fsNInbauv50VzIMgjA6RnKTOI17gRsSdGlsV4vZn2aIxEPWauu6T/UohMvAE9HMn13vtbpPBSFwJAktj6yHASYGzupNQLprA0+OdyALoLZPpQAKNEXA42a4EVISBKu0EmduHJlUPeqhnIGkkGgVNWS8AWqzP2nFoPdXBgUWateiMcBTHxgEKDac5YmNc9lsXpzf1OxBaXHBhGYKuXPwIfyH3jTWb1OdwixJEuRe9dl63T9qOTRre8QWns/bMqKLibGfMtFhVB21ARJayBuX70eVvabG/2N7Y5t1zUlFygIKu51tvo3AVCRDdRrFWDvkAjxzIz5FIdALVZ+DReFYu/r4WF/w3V9rInFuEDSwb/OH4r8sQycs07tSlMyA74Y3FpjKTBxso=","translations":{}},{"version":"0.3.2","phpExtensions":[],"databases":[],"shellCommands":[],"phpVersionSpec":"*","platformVersionSpec":">=9.0.0 <12.0.0","minIntSize":32,"download":"https://github.com/juliushaertl/apporder/releases/download/0.3.2/apporder.tar.gz","created":"2016-10-06T14:00:51.532409Z","licenses":["agpl"],"lastModified":"2016-10-06T14:00:51.598455Z","isNightly":false,"rawPhpVersionSpec":"*","rawPlatformVersionSpec":">=9 <=11","signature":"gRVFOtj9414ZNSdRH/qNB2SwVZUQh+gaFnNLFjjXjJ1MdRMCISzvwb+QU1qYuK/y\nuL8K0pn1+fFQf8A3VsC2pb6yaLQ5U9C3Guf886Flf4qtYw1P8UWRA9yOJ+6Md+PH\n6pTEiDIdm4xbmM0KkBhsE5kL8dvLIq4EwwcAh2Qq8fjytzAk1YiP+KrTaYrVwskM\nDmm0lgP4NVnjRBTX9myW6tr6N3w0tq2jJ/+a/vEDJv+5ozKJx8N5gbJNdrtI4k7I\nyaQNWJ7cngtAHmUREeoBggV5uJayDceu83PPQR6N9/WVyNyZjw1Q8/Q6e/NyiXT2\no8mGv5tHl3DBOVuv8v7gBQgDh6ppp12M81aiCZymn2XIgjw50VQ+K15KHnLHuFFw\nwuHZVcoQ7b6oR4K4TURSfPFUeNgGS4R9v6gjg1RUcSm1Pnryc6pYnh10AUY8dk6q\n1CZ6Upt6SScP2ZEGWsFwVjjQhY/ZJmNfnhaGoFOZ5L9CnzyNCkGXFg0rL36i6djb\naqFy/z+Brnklng5ct6XWoP7uDt5BaHznQj1NHSfHn0GUQ0N968zWm9vQvy+dyXyC\nxR7vKeu2ppZ2ydoeQ9CVwfhOEsGs5OvrpapQdh9KbUHcX7b7ql01J7/P6dFuNuHe\n+7/y4ex3sEVg5YBmDtF8iZ6d7zsHd6peL1s1EsLnenQ=","translations":{}}],"screenshots":[{"url":"https://bitgrid.net/~jus/apporder-nc.gif"}],"translations":{"en":{"name":"AppOrder","summary":"Sort apps in the menu with drag and drop","description":"\nEnable sorting for icons inside the app menu. The order will be saved for each\nuser individually. Administrators can define a custom default order.\nAppOrder works with the default owncloud menu as well as with the direct_menu\napp.\n\n## Set a default order for all new users\n\nGo to the Admin settings > Additional settings and drag the icons under App order.\n\n## Use first app as default app\n\nYou can easily let Nextcloud redirect your user to the first app in their\npersonal order by changing the following parameter in your config/config.php:\n\n'defaultapp' => 'apporder',\n\nUsers will now get redirected to the first app of the default order or to the\nfirst app of the user order.\n "}},"isFeatured":false,"authors":[{"name":"Julius Härtl","mail":"jus@bitgrid.net","homepage":""}],"ratingRecent":0.5,"ratingOverall":0.5,"ratingNumRecent":0,"ratingNumOverall":0,"certificate":"-----BEGIN CERTIFICATE-----\r\nMIIEAzCCAusCAhAEMA0GCSqGSIb3DQEBCwUAMHsxCzAJBgNVBAYTAkRFMRswGQYD\r\nVQQIDBJCYWRlbi1XdWVydHRlbWJlcmcxFzAVBgNVBAoMDk5leHRjbG91ZCBHbWJI\r\nMTYwNAYDVQQDDC1OZXh0Y2xvdWQgQ29kZSBTaWduaW5nIEludGVybWVkaWF0ZSBB\r\ndXRob3JpdHkwHhcNMTYwOTE0MTI1MjQ4WhcNMjYxMjIxMTI1MjQ4WjATMREwDwYD\r\nVQQDDAhhcHBvcmRlcjCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAKVK\r\nKn5jivCu+eRfe5BECjDOzNaGHlpiegb49Hf4nh0W7DqcoLHip5c1O2BcEYdH6rkw\r\n20WclvjoQpgavG5aFXzXzur6eKTT5TpgY5oZTLoWjbx4e+fKdhyDPTpqNZzs1pxz\r\nsZLDL/ElpbSErE0s+QK/pzP11WNPylAkI9AKSyDMO3Mbllg8I8Bt+bT7LJKYOO/T\r\nLhv9m0anLZ4HrdfimhVIoMiu3RpyRigk8titXZA94+F8Fbf7ZQ9f14Y/v3+rfJFQ\r\nii9cDoox5uUrjplH2LrMr5BodfCfydLu4uVpPWYkdccgvcZ1sugjvNXyCQgdzQDK\r\npOpiwVkkiQFaQJYbGSDblFWPl/cLtA/P/qS7s8tWyTQuc1rYlEpCHG/fG8ZFkSVK\r\n9eCMGxK908VB4IU2DHZHOHi7JvtOz8X/Ak6pIIFdARoW3rfKlrz6DD4T9jEgYq0n\r\nRe7YwCKEIU3liZJ+qG6LCa+rMlp/7sCzAmqBhaaaJyX4nnZCa2Q2cNZpItEAdwVc\r\nqxLYL1FiNFMSeeYhzJJoq5iMC3vp2LScUJJNoXZj9zv+uqTNGHr+bimchR2rHUBo\r\nPzDLFJmat03KdWcMYxcK5mxJNGHpgyqM7gySlbppY/cgAospE8/ygU2FlFWIC9N0\r\neDaY+T8QA1msnzsfMhYuOI8CRYigan1agGOMDgGxAgMBAAEwDQYJKoZIhvcNAQEL\r\nBQADggEBAGsECd+meXHg1rr8Wb6qrkDz/uxkY1J+pa5WxnkVcB6QrF3+HDtLMvYm\r\nTTS02ffLLyATNTOALZFSy4fh4At4SrNzl8dUaapgqk1T8f+y1FhfpZrEBsarrq+2\r\nCSKtBro2jcnxzI3BvHdQcx4RAGo8sUzaqKBmsy+JmAqpCSk8f1zHR94x4Akp7n44\r\n8Ha7u1GcHMPzSeScRMGJX/x06B45cLVGHH5GF2Bu/8JaCSEAsgETCMkc/XFMYrRd\r\nTu+WGOL2Ee5U4k4XFdzeSLODWby08iU+Gx3bXTR6WIvXCYeIVsCPKK/luvfGkiSR\r\nCpW1GUIA1cyulT4uyHf9g6BMdYVOsFQ=\r\n-----END CERTIFICATE-----"},{"id":"twofactor_totp","categories":["tools"],"userDocs":"","adminDocs":"","developerDocs":"","issueTracker":"","website":"","created":"2016-10-08T14:13:54.356716Z","lastModified":"2016-10-12T14:38:56.186269Z","releases":[{"version":"0.4.1","phpExtensions":[],"databases":[],"shellCommands":[],"phpVersionSpec":">=5.4.0 <7.1.0","platformVersionSpec":">=10.0.0 <12.0.0","minIntSize":32,"download":"https://github.com/ChristophWurst/twofactor_totp/releases/download/0.4.1/twofactor_totp.tar.gz","created":"2016-10-12T14:38:56.174612Z","licenses":["agpl"],"lastModified":"2016-10-12T14:38:56.248223Z","isNightly":false,"rawPhpVersionSpec":">=5.4 <=7.0","rawPlatformVersionSpec":">=10 <=11","signature":"bnwWxmHEn8xkoWbtwhC1kIrJ0dQfAI3PUtU62k+Tru/BHt1G2aVxqO8bCdghojZ7\nzdFMlIJw4kekYFsVfLk8jzjUTZKVbNVKCdkHrVTQ0bUUryMAMLqGQ3PSRI5NX6D5\nFpkvwO1coYwU0XVWF8KAS0meX0ztSkT3Mv96LLrxr8F8SrB/MGmKIE4WTjt1fAIa\nZLAVEUo/3sNFTGLYBtL3wjctrkZvJltP8abeRfls9FkRHu+rN7R3uLFzk42uZn3X\nWpt5BBmlYm5ORbnJ2ApsxEkMNK+rOy8GIePaz5277ozTNrOnO04id1FXnS9mIsKD\n20nRzjekZH+nneQYoCTfnEFg2QXpW+a+zINbqCD5hivEU8utdpDAHFpNjIJdjXcS\n8MiCA/yvtwRnfqJ5Fy9BxJ6Gt05/GPUqT8DS7P1I1N+qxhsvFEdxhrm2yIOhif8o\nh7ro5ls+d3OQ8i3i4vdZm821Ytxdu/DQBHiVoOBarvFWwWAv2zd2VAvpTmk6J5yv\n3y+csRqpEJYd9fcVMPsTu7WBRRrpBsAqdAHJcZEwak2kz1kdOgSf8FIzP1z6Q71d\nMl2RKcPeutMHHSLiGIN/h7fM5aSs49wGgGZmfz28fHVd7/U0HFSMYmkT/GMq5tMP\nIyc+QZAN4qbX8G0k/QSTkK/L4lOT2hQiQqiSqmWItMk=","translations":{}}],"screenshots":[],"translations":{"en":{"name":"Two Factor TOTP Provider","summary":"A Two-Factor-Auth Provider for TOTP (e.g. Google Authenticator)","description":"A Two-Factor-Auth Provider for TOTP (e.g. Google Authenticator)"}},"isFeatured":true,"authors":[{"name":"Christoph Wurst","mail":"","homepage":""}],"ratingRecent":0.5,"ratingOverall":0.5,"ratingNumRecent":0,"ratingNumOverall":0,"certificate":"-----BEGIN CERTIFICATE-----\r\nMIIECTCCAvECAhASMA0GCSqGSIb3DQEBCwUAMHsxCzAJBgNVBAYTAkRFMRswGQYD\r\nVQQIDBJCYWRlbi1XdWVydHRlbWJlcmcxFzAVBgNVBAoMDk5leHRjbG91ZCBHbWJI\r\nMTYwNAYDVQQDDC1OZXh0Y2xvdWQgQ29kZSBTaWduaW5nIEludGVybWVkaWF0ZSBB\r\ndXRob3JpdHkwHhcNMTYxMDEyMDkzNDMxWhcNMjcwMTE4MDkzNDMxWjAZMRcwFQYD\r\nVQQDDA50d29mYWN0b3JfdG90cDCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoC\r\nggIBALC1K94104L/nOtmTygx7QNjUcnHs3yrn71mw4pMxTlonXOnMTpwxsfL1Hhu\r\n/5GMSgupTbQPlevSl6J86UMs455/sPShd6ifmAuhb8VFaAsjpizjs0RMaUg1sjmF\r\nuV18PD9FXLourx51V/c4MG5kpavlV+bLUrVMAjbsJY2+k30tCC/XkP5u8jUWmM/T\r\n5REChn7/obPgaeddhuJoILYhKEW3VNrR8Fm9SYiviB3FLhM7URDZ97IBnXYqbvbT\r\nZnvq+E74Zc7HgYwQwrjU/AqQAInhNpAR4ZM6CkWWWWaL96O1q3lCfKJNaxqC0Kg/\r\nkGn/pxYkl9062jtMUz60s9OPDyuisfyl68UyM68Ozyz4SMRLmDVbewOqQAwmAbtz\r\n8p9AQrX3Pr9tXhARR4pDSsQz1z+8ExEd6EKbhMyiTtHtZQ1Vm9qfoR52snpznb5N\r\ne4TcT2qHAkOWV9+a9ESXmQz2bNjgThxEl5edTVY9m4t248lK5aBTGq5ZKGULNHSQ\r\nGGpr/ftMFpII45tSvadexUvzcR/BHt3QwBAlPmA4rWtjmOMuJGDGk+mKw4pUgtT8\r\nKvUMPQpnrbXSjKctxb3V5Ppg0UGntlSG71aVdxY1raLvKSmYeoMxUTnNeS6UYAF6\r\nI3FiuPnrjVFsZa2gwZfG8NmUPVPdv1O/IvLbToXvyieo8MbZAgMBAAEwDQYJKoZI\r\nhvcNAQELBQADggEBAEb6ajdng0bnNRuqL/GbmDC2hyy3exqPoZB/P5u0nZZzDZ18\r\nLFgiWr8DOYvS+9i6kdwWscMwNJsLEUQ2rdrAi+fGr6dlazn3sCCXrskLURKn5qCU\r\nfIFZbr2bGjSg93JGnvNorfsdJkwpFW2Z9gOwMwa9tAzSkR9CsSdOeYrmdtBdodAR\r\ndIu2MkhxAZk9FZfnFkjTaAXcBHafJce7H/IEjHDEoIkFp5KnAQLHsJb4n8JeXmi9\r\nVMgQ6yUWNuzOQMZpMIV7RMOUZHvxiX/ZWUFzXNYX0GYub6p4O2uh3LJE+xXyDf77\r\nRBO7PLY3m4TXCeKesxZlkoGke+lnq7B8tkADdPI=\r\n-----END CERTIFICATE-----"},{"id":"contacts","categories":["office","organization","social"],"userDocs":"https://docs.nextcloud.com/server/11/user_manual/pim/contacts.html","adminDocs":"https://docs.nextcloud.com/server/11/admin_manual/configuration_server/occ_command.html?highlight=occ%20commands#dav-label","developerDocs":"https://github.com/nextcloud/contacts#building-the-app","issueTracker":"https://github.com/nextcloud/contacts/issues","website":"https://github.com/nextcloud/contacts#readme","created":"2016-10-30T14:00:58.922766Z","lastModified":"2016-11-22T22:08:01.904319Z","releases":[{"version":"1.5.0","phpExtensions":[],"databases":[],"shellCommands":[],"phpVersionSpec":"*","platformVersionSpec":">=9.0.0 <12.0.0","minIntSize":32,"download":"https://github.com/nextcloud/contacts/releases/download/v1.5.0/contacts.tar.gz","created":"2016-11-22T22:08:01.861942Z","licenses":["agpl"],"lastModified":"2016-11-22T22:08:02.306939Z","isNightly":false,"rawPhpVersionSpec":"*","rawPlatformVersionSpec":">=9 <=11","signature":"ZqqhqtbHcNB+rzGCQ7FDIjjvHjit+dhAE1UhFgiXApkx3tmPP4nJOBAGNjHe+2Ao\nVcTIX2SrWEfieRrA4Gp+0k7pUPWag1Z0T1OVOwO4cmS1AVFyGIOE1bRvDhMfsWTU\n4CI4oXaKBFAY6mtnf7VJ7EeIdNqhImkohyWDQ88NiPRLM1XNkJJk6AvZBcT0fvCv\no145X4dLpbixSXsN99QFNJ/oXvK+9tBGwTd5i/WnNFY90vcNRLia8aRo7SA0YJRx\nLnxnj2HMqwTTDQEKE+1elYKWsqQ2DeqwScP97UIKe5bZXnrwOi9kH9PDmR4abtzd\nlHL8E1Wgw25ePDeHG7APrx0tVOJy1bP+g8vcarpGynWZoizDkBvYZD+xtxizpBXC\nJsDOSzczApptY6dnOtv0Vat8oh/Z/F99gBUahEu4WZ16ZgR1nj40PDK1Snl18Cgk\nMe1EZcde8SLEpTbCWYIfIw/O9Fkp5cWD/dAqoiO6g+gNxSZ/gGp57qoGfFxn7d/x\nH3aH8GljatAFjrwItw1JzR0THt0ukkOK+bw/pfCslk10sjHMitmz/GXa4qMS91DZ\nBKLUd0dSfQUQzkfwcojImbzJRvca4/DYe3mfG7+RCH0tDL6t72dKL9joB++u5R1u\nVZPgkToexlXcKWpiDB8H2/SEShKr4udAOjR5de9CYWM=","translations":{}}],"screenshots":[{"url":"https://raw.githubusercontent.com/nextcloud/screenshots/master/apps/Contacts/contacts.png"}],"translations":{"en":{"name":"Contacts","summary":"The new and improved app for your Contacts.","description":"The new and improved app for your Contacts."}},"isFeatured":true,"authors":[{"name":"Alexander Weidinger","mail":"","homepage":""},{"name":"Jan-Christoph Borchardt","mail":"","homepage":""},{"name":"Hendrik Leppelsack","mail":"","homepage":""}],"ratingRecent":0.5,"ratingOverall":0.5,"ratingNumRecent":0,"ratingNumOverall":0,"certificate":"-----BEGIN CERTIFICATE-----\r\nMIIEAzCCAusCAhATMA0GCSqGSIb3DQEBCwUAMHsxCzAJBgNVBAYTAkRFMRswGQYD\r\nVQQIDBJCYWRlbi1XdWVydHRlbWJlcmcxFzAVBgNVBAoMDk5leHRjbG91ZCBHbWJI\r\nMTYwNAYDVQQDDC1OZXh0Y2xvdWQgQ29kZSBTaWduaW5nIEludGVybWVkaWF0ZSBB\r\ndXRob3JpdHkwHhcNMTYxMDEyMjAzNzIyWhcNMjcwMTE4MjAzNzIyWjATMREwDwYD\r\nVQQDDAhjb250YWN0czCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBANzx\r\n/zJF+5/s4lOJLWIlfKQgTy+UpvIpiUXCgrsHsDZTx+hjQAhIWukH88a+7NVAL7Ys\r\nkQNC0Tlm755FJi/T6EdR7edOwIRdo2ZwakOWLZXd209+6cCd2UloHL0bgnbWepTl\r\nR/4YgbLg/G+FVKCfkEiYc3PuDZ3EVrcwQFcg7h74X9ne6CHH0Z1WQLydxJuVEb2n\r\nX9I+nIRpPHcVostkSiUmzHR7C5TjTIo2PzzgnCU6GC0iBa6z6dDYfz24QEp/b8UA\r\nZaLhjkyKghVGMnoF/s9KPgH4NM8pvvtadQN8pxlOPju4wbmKPUrsXo4ujurDXbbc\r\nYkzNt8ojobGwdTXoyDogAsGZLQd2FQksWpRvY+I3zVPokBfPMdUPLllG5VcV0VA5\r\nDRK+h2ms+XmspdBvGonjF+XdbFm9hEmDoFmoi9aU6C6AdofjmG/e9+pw/20dXUWk\r\nmMorWwXQ5yLmIn5LnpRXrOuK7CS28VRhBYuVNMlsyKhzU0rophbsD9OFXxYLjr6s\r\n7UPNwZ5h+kjXZDBKD89QctBSViT8RhLe8nulRIm0iJn1sb9hca/CF63KmsFzENfK\r\nQeM6MO0H34PB84iNyz5AX1OIy+1wHD4Wrzt9O/i2LkWK6tBhL69aZiBqdLXWKffj\r\nARDCxxIfews51EZFyHzwsw65I97y46aBKxY382q7AgMBAAEwDQYJKoZIhvcNAQEL\r\nBQADggEBACLypX0spxAVAwQIS9dlC9bh1X/XdW2nAvSju2taUTBzbp074SnW6niI\r\nbnY4ihYs4yOuGvzXxnp/OlvWH7qhOIchJUq/XPcEFMa7P03XjVpcNnD3k0zQWlZb\r\ntGonX9EUOeLZKdqI4fkrCkMLScfjgJzoHGYQrm8vlIg0IVuRLCKd5+x4bS7KagbG\r\niuPit2pjkw3nWz0JRHneRXz/BNoAWBnJiV7JMF2xwBAHN4ghTM8NSJzrGTurmpMI\r\nGld7yCP47xNPaAZEC66odcClvNtJ2Clgp8739jD6uJJCqcKDejeef0VU1PG7AXId\r\n52bVrGMxJwOuL1393vKxGH0PHDzcB1M=\r\n-----END CERTIFICATE-----"},{"id":"mail","categories":["tools"],"userDocs":"","adminDocs":"https://github.com/nextcloud/mail#readme","developerDocs":"","issueTracker":"","website":"","created":"2016-10-19T19:41:41.710285Z","lastModified":"2016-10-19T19:57:33.689238Z","releases":[{"version":"0.6.0","phpExtensions":[],"databases":[],"shellCommands":[],"phpVersionSpec":">=5.4.0 <7.1.0","platformVersionSpec":">=10.0.0 <12.0.0","minIntSize":32,"download":"https://github.com/nextcloud/mail/releases/download/v0.6.0/mail.tar.gz","created":"2016-10-19T19:57:33.676730Z","licenses":["agpl"],"lastModified":"2016-10-19T19:57:33.834580Z","isNightly":false,"rawPhpVersionSpec":">=5.4 <=7.0","rawPlatformVersionSpec":">=10 <=11","signature":"VbMsvDpt+gSPeFM8LrZXEK10rk8kkLlgCcblgqNdCSeGZeVpwDAYv3CccVSLa0+l\nlTSqQ0VIoH+OIU6vIQNBKHmSCzTplk7OrY0+L5FajXx8LnBaOh892GfGSlEt1neN\nKyM0i0uOjO/xpCP/NoUlgkz6hnmYY5XEdN6DTsJtJ/XZhDQ45IYuIkMkHE/eFehS\n0JnOagIz+PSipeBY2Ry+tV8YbRa7bC1JAvZzlod0dyI015AHZESeitRUY+MwMWkt\nN/me7g7/Kev0wggIQQZm9aYcw63GMk/1VHUPB7Y0ESW9tx2nR5+KwTDn/Jy4DGf1\nrg8h0t5I+aPhHOBLrpczH0qaZWY2lsVZWq8KWjJI9aR9P0v2f2aXixXzD/Cuz1cK\nhvhKWkOSla4D+/FxeyHGjQvdXMG8gXm0ZmTimKChCoVuCbncDd8pzkdyNoGXcvuk\nsP8OrkQFooL4E7S4BWfdSiN/a8jUITJQkuXp/OVrVGeCupLWJh7qegUw6DvoqyGy\nD4c6b+qYn68kx3CLaPPiz+tFAZQZQdj7+Kx/lohso8yTnVSiGYrMj4IvvCbpsQjg\nWF3WSqF/K/tTnPYTWb9NUPSihTbVNv6AXOfTsPEp/ba2YSS5DjvjVjkr5vhR9eg1\nikQ3Cw6lW3vaA4LVCC+hFkMRnI4N0bo5qQavP3PnZPc=","translations":{"en":{"changelog":"### Added\n- Alias support\n [#1523](https://github.com/owncloud/mail/pull/1523) @tahaalibra\n- New incoming messages are prefetched\n [#1631](https://github.com/owncloud/mail/pull/1631) @ChristophWurst\n- Custom app folder support\n [#1627](https://github.com/owncloud/mail/pull/1627) @juliushaertl\n- Improved search\n [#1609](https://github.com/owncloud/mail/pull/1609) @ChristophWurst\n- Scroll to refresh\n [#1595](https://github.com/owncloud/mail/pull/1593) @ChristophWurst\n- Shortcuts to star and mark messages as unread\n [#1590](https://github.com/owncloud/mail/pull/1590) @ChristophWurst\n- Shortcuts to select previous/next messsage\n [#1557](https://github.com/owncloud/mail/pull/1557) @ChristophWurst\n\n## Changed\n- Minimum server is Nextcloud 10/ownCloud 9.1\n [#84](https://github.com/nextcloud/mail/pull/84) @ChristophWurst\n- Use session storage instead of local storage for client-side cache\n [#1612](https://github.com/owncloud/mail/pull/1612) @ChristophWurst\n- When deleting the current message, the next one is selected immediatelly\n [#1585](https://github.com/owncloud/mail/pull/1585) @ChristophWurst\n\n## Fixed\n- Client error while composing a new message\n [#1609](https://github.com/owncloud/mail/pull/1609) @ChristophWurst\n- Delay app start until page has finished loading\n [#1634](https://github.com/owncloud/mail/pull/1634) @ChristophWurst\n- Auto-redirection of HTML mail links\n [#1603](https://github.com/owncloud/mail/pull/1603) @ChristophWurst\n- Update folder counters when reading/deleting messages\n [#1585](https://github.com/owncloud/mail/pull/1585)"}}}],"screenshots":[],"translations":{"en":{"name":"Mail","summary":"Easy to use email client which connects to your mail server via IMAP and SMTP.","description":"Easy to use email client which connects to your mail server via IMAP and SMTP."}},"isFeatured":false,"authors":[{"name":"Christoph Wurst, Thomas Müller, Jan-Christoph Borchardt, Steffen Lindner & many more …","mail":"","homepage":""}],"ratingRecent":0.5,"ratingOverall":0.5,"ratingNumRecent":0,"ratingNumOverall":0,"certificate":"-----BEGIN CERTIFICATE-----\nMIID/zCCAucCAhAVMA0GCSqGSIb3DQEBCwUAMHsxCzAJBgNVBAYTAkRFMRswGQYD\nVQQIDBJCYWRlbi1XdWVydHRlbWJlcmcxFzAVBgNVBAoMDk5leHRjbG91ZCBHbWJI\nMTYwNAYDVQQDDC1OZXh0Y2xvdWQgQ29kZSBTaWduaW5nIEludGVybWVkaWF0ZSBB\ndXRob3JpdHkwHhcNMTYxMDE5MTkzMDM0WhcNMjcwMTI1MTkzMDM0WjAPMQ0wCwYD\nVQQDDARtYWlsMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAp++RuliQ\nlBeeiPtP0ecBn00OaU1UCpft/NVI5pnSiT9nU4l2kc5IvKjA8UxDB3gWfYTOeBFh\ntUHQ2P6UKCmHZT9sApHhqLu2n0V+YhlFIViuaxndSID/M414cl56xOYQusV3Pcae\no2dOSeRRzLab3tEaVHlkBSFkGmAwPZItsmTklvV3h1sUysDicYgfXPCkf7K+JgWA\nBP7vsWC8B7MDRhcB3enYv5tTcpsyvtGX7bb1oTIWVypcmKsGYfTX12VNBxKzNBIG\n8pwdb8Xo0o14TytWsWN7mSHf1XbwfwYMjDWOlMqiRc+mcoKMBH41TfM/CXslSivI\nsyvxasEaFdlj8lmKPENdzw1OfYRs43usIf4szwyt4rb8ocXfDipnY3P2hccN6YcZ\nl8y8Vsr69ASluDj2A2Pl5vH6xp6tNybZRnN5G6sghhaYaLNDU/TdMyYzz4AY33Ra\nHSaMypfcXjd76Aj8jZvcwk1BH+ZsvFqNK7ZKCb7WVcMH8KRcU1sxZ4rp9vviM2fL\nL7EVtznm3bSI9jjHXbiwq7RvNRRy+F6YRpAdWGwTU8uUkDabPFi41FikYyzNWauK\nJhlDJXl514XjKyMVBjAZYVr5gZZkO1J7C4XzLFbC5UzYNSzW5Iwx/1j5OeYJRxh6\n5rhiUwR+COT1wdVsl6khMC8MfBR4unSd338CAwEAATANBgkqhkiG9w0BAQsFAAOC\nAQEATBvpqz75PUOFPy7Tsj9bJPaKOlvBSklHH7s43fDDmQbJwswXarZi3gNdKf8D\nyO/ACZvO8ANWAWL/WahkOyQtKOYzffaABGcEIP7636jzBdKtgwSGzW3fMwDghG10\nqBr2dE6ruOEdSpuZxgMgh2EulgknZUXaHAMI2HjjtAMOBScLQVjOgUqiOHmICrXy\nZETmzhx0BXDt5enJYs8R2KMYJNIme1easQRYmWKliXogNY09W7ifT9FHtVW1HX+K\nxRS4JXbapjolkxyGSpP+iYSgItVnYzl6o9KZResR4yDsBv7G/8fpV4GQU9IS3zLD\nPiZOosVHWJdpUKCw9V4P1prGTQ==\n-----END CERTIFICATE-----"},{"id":"audioplayer","categories":["multimedia"],"userDocs":"https://github.com/rello/audioplayer/wiki#user-documentation","adminDocs":"https://github.com/rello/audioplayer/wiki#admin-documentation","developerDocs":"","issueTracker":"https://github.com/rello/audioplayer/issues","website":"https://github.com/rello/audioplayer","created":"2016-09-16T05:44:24.857567Z","lastModified":"2016-11-17T22:34:34.637028Z","releases":[{"version":"1.3.1","phpExtensions":[],"databases":[],"shellCommands":[],"phpVersionSpec":">=5.4.0","platformVersionSpec":">=9.0.0 <12.0.0","minIntSize":32,"download":"https://github.com/Rello/audioplayer/releases/download/1.3.1/audioplayer-1.3.1.tar.gz","created":"2016-11-17T22:34:34.215350Z","licenses":["agpl"],"lastModified":"2016-11-17T22:34:34.867778Z","isNightly":false,"rawPhpVersionSpec":">=5.4","rawPlatformVersionSpec":">=9 <=11","signature":"p6Zz0IEFrxvw6y/3jHgGWWCxR6qpMzvU2HKfxcIVsK6sJnoRUhWLeAXwZ432fH2a S2llj+IGS9OvW+5VQElrXgPtEjDK1BT00DRJnp5RFCRlUv0LNoedJMzx6B6AHqPP JBufk3cG1O/CO0M0L1ITGSmSOzfKvWTRo3lxVGF792NyBaP/SyZCkH1N1TzBQzUi Ywl3+HiglPcXbHjtJm/arnKorbJWVKoaN93xFuaBapd2ozQSpi0fE0uGRsici+U7 HNa1M5WFE1rzUJoufE0E9246At07rFY1e+TdNEq8IlLgCXg5vGCKkEyuWpWno6aX LfRaIiT9x39UTAwNvuDKS0c+n4uWDYPsGfKhDx9N7CXpUrthfXVEWRzZEXG7as10 6ANvrRPJemSZH8FUSrdJhD7k12qa9R825y7mIG68Li8P71V92EOxFfo9tNXqXwBt VuDGxBqByFVPqSCj5I8hrzJzQl2Xt40g8+8ZcSF96RMg/pM+bwRMTv+mz0V+vQQ4 DWjqnWVPalaJ1PPD5/QFFErtXuNRbyxKZ6BMWxfJlLM9Kz66P75K+8fYaSwz+2KG NxY7I3svzS2K9LGH3fBLUy1t3Hl+c3zGFq/ll1MJrf9NswV4yxt2WmISfM/KDww8 yELkGs2cRzbw2tCvnmYlJJhIqRLkyFAbDzWRH/XdVx4=","translations":{"en":{"changelog":"2016-11-17\n- fix: one-click-play for wav not working\n- fix: wrong sql statement for PostgreSQL [#90](https://github.com/rello/audioplayer/issues/90)"}}},{"version":"1.3.0","phpExtensions":[],"databases":[],"shellCommands":[],"phpVersionSpec":">=5.4.0","platformVersionSpec":">=9.0.0 <12.0.0","minIntSize":32,"download":"https://github.com/Rello/audioplayer/releases/download/1.3.0/audioplayer-1.3.0.tar.gz","created":"2016-11-15T18:11:19.539636Z","licenses":["agpl"],"lastModified":"2016-11-15T18:11:19.592881Z","isNightly":false,"rawPhpVersionSpec":">=5.4","rawPlatformVersionSpec":">=9 <=11","signature":"lbp7wd3JhMHW5mC8kVnQFvcwzf3aTIhYhq3ak/C/vfDXJDIPFuQ1odVRWtaHXEKQ XmKYIoTobV1TAU5q9G0O0Kds73T/XtHG4ATLxMZE8RsUWNSj5v3H4YDub6A0uoX6 rzyLEYV6SGEtdPFMwLcUjDExKpzAzKpgxcd9uyz2NhcHJEO8FJmirn34bm69//TO vjjiMW4zpL+dho+7LQbOX+L1SmwmdBqwypE9zzeuIuhUWDEQtImHAvjIO6Temajm lX0H5JaowJa8kvP6Jkh3KAvsHQ4sJklvWTPGcv0gboN+o6CmjWNOb+3LeSH0nhe6 BmiPloUDJcPQwq2gQejH2pY+qJEdRcULSKS09/dRbE3gOSlG36FThN0INpv6uNP4 qVIiYs3/SEHMmlS5CHvJDt2S2XN9LT9IX7QPeuS/0CMcuopaG/+cdC4KscVCq4D4 bllgew9asiBqix8iV8C4oerYOiC5vWcgBrZhGShoJT1Qq+NKz+H10dFgjFCAZuPj nVagJkbXmf2NdcvpSC7qsufhyEZyCSp+I7QEYsbo1PW3aUU35Syt47lgeVFX0hVQ jC1wMIhEW5Rm2nCkRSZkRupKDQ+N6uWuB0lykeMV2ShcDvvUZrhN3c49sooWgigB yIqKryzM4fLErjjNHdYgwCq6bbgPDLK3ic9b3B4rF3E=","translations":{"en":{"changelog":"2016-11-15\n- fix: handling of temporary scanner files [#68](https://github.com/rello/audioplayer/issues/68)\n- fix: simpler analysis of incorrect files in scanner [#57](https://github.com/rello/audioplayer/issues/57)\n- fix: album sorted correctly by artist and album [#80](https://github.com/rello/audioplayer/issues/80)\n- fix: neutral cover for unknown album [#16](https://github.com/rello/audioplayer/issues/16)\n- fix: error message from ID3 editor shown in front-end [#77](https://github.com/rello/audioplayer/issues/77)\n- enhancement: occ support for library scan and reset [#72](https://github.com/rello/audioplayer/issues/72)\n- enhancement: select a dedicated folder for scanning in personal settings [#79](https://github.com/rello/audioplayer/issues/79)\n- enhancement: exclude folders from scanning via .noaudio file [#79](https://github.com/rello/audioplayer/issues/79)\n- enhancement: significantly reduce database reads during scanning [#79](https://github.com/rello/audioplayer/issues/79)\n- enhancement: cleanup of classes; move from \\OC\\Files\\View to \\OCP\\Files\\IRootFolder [#72](https://github.com/rello/audioplayer/issues/72)"}}},{"version":"1.2.2","phpExtensions":[],"databases":[],"shellCommands":[],"phpVersionSpec":">=5.4.0","platformVersionSpec":">=9.0.0 <12.0.0","minIntSize":32,"download":"https://github.com/Rello/audioplayer/releases/download/1.2.2/audioplayer-1.2.2.tar.gz","created":"2016-10-06T21:21:05.414691Z","licenses":["agpl"],"lastModified":"2016-10-06T21:21:05.483224Z","isNightly":false,"rawPhpVersionSpec":">=5.4","rawPlatformVersionSpec":">=9 <=11","signature":"toeS45z50Lm0djgrQokOTN7gA8a113IZtiKKiLsGUKWrCV/6AKJBmEFcSun6rhLH\nbz/RtIdFKwQql6O3E0m1Zch2y1A8aLWHzFTO+5orLCVi7y15SshrJYbb9aI5Pj3i\nSR7+kMHGS8uNx2uIn3B4mO6UYF8AzCfp+ule18DOjnpu86KWvEOGtFXsQkLtgepp\nbJhOGWW/uOVIos/T1xPP4GCmtVmgn7U3b9q0pMYRH7ONXEiNsfQxDrR66EZH3Jfo\nlVyM9UvQmMKoDSdBUlvLlhCEGJGqFOD7hFntLYloI4oXv9uGqcagaJVh3TkEysY2\nMbBZpVhch5zRJ/HGlZOvmEzZ8Inxkk3iap+JmJ5/gZTefwfKUyYHALsILlh820U2\nNA/1B5A015XH5a5uflGE/tnlPtrOeecIN4mg+1njo2RG89HJWJNHM2ZDO4SkXjSR\njgygmAS5aR5+KKifiA/pwjhLozDWPU4lNzsj3Foz3bx3Okopy7eq83LORqieT4Jp\nFvP64q/45LOSRBWIWLitYzRzZp7HYywMsnz12WpxtqxIjO7+7y/ByeWWOBNU1IJC\nK2D+035ZGWZr0CxDJte33WOISwjVoSwrcov++O3BQW8lM5IkcDNcJFyzNPKAXcQU\nPUXmQpYurHoIw6odAYcbrG6iOiSesuNOf2kQWbjV3/c=","translations":{"en":{"changelog":"2016-09-18\n- fix: icon issues with alternative apps folder [#65](https://github.com/rello/audioplayer/issues/65)"}}}],"screenshots":[{"url":"https://github.com/rello/screenshots/raw/master/audioplayer_main.png"},{"url":"https://github.com/rello/screenshots/raw/master/audioplayer_lists.png"},{"url":"https://github.com/rello/screenshots/raw/master/audioplayer_share.png"}],"translations":{"en":{"name":"Audio Player","summary":"Audio Player for ownCloud and Nextcloud","description":"Audio Player for MP3, MP4, Ogg, and Wave with a lot of flexibility for all your needs."}},"isFeatured":false,"authors":[{"name":"Marcel Scherello","mail":"","homepage":""}],"ratingRecent":0.5,"ratingOverall":0.5,"ratingNumRecent":0,"ratingNumOverall":0,"certificate":"-----BEGIN CERTIFICATE-----\r\nMIIEBjCCAu4CAhAIMA0GCSqGSIb3DQEBCwUAMHsxCzAJBgNVBAYTAkRFMRswGQYD\r\nVQQIDBJCYWRlbi1XdWVydHRlbWJlcmcxFzAVBgNVBAoMDk5leHRjbG91ZCBHbWJI\r\nMTYwNAYDVQQDDC1OZXh0Y2xvdWQgQ29kZSBTaWduaW5nIEludGVybWVkaWF0ZSBB\r\ndXRob3JpdHkwHhcNMTYwOTE1MjExMjA4WhcNMjYxMjIyMjExMjA4WjAWMRQwEgYD\r\nVQQDDAthdWRpb3BsYXllcjCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIB\r\nALyC+iLscLs62NeNmUXEBmg+xMuUtDmZKr+xzJWtl6SSNRz+8K1JygvUIXFJ3RIL\r\nCYA3xyq8/wyZH1gNrLKyz5eTeYawG+eT3ges/FT6MWGUbZoRrBrikVcLC94QzxTH\r\nxOl8Dn+SCV/2bhcvPTQdhK+dqtvGilOtjHa40iMrk9gSdlKVys5CK/xdlEp8uiMa\r\nkz1WENn8MVCCJV58bAUbaCupDWXR9CCoSsw8XinNsCenZ2B2XlnmbM44280w0ojs\r\n72rfQRgj3yDG+ZUUyUOuxIuodu8liXYciLf0ph6t/f/qoSmctbBdsR5Fl1Upj1Ac\r\nqeHb5Yf/B3Vi6Mn3XfDx0H2EHk1v9Dhzxay+v9BHUzyIX2iH/q+7TE0/Jzo5AwBW\r\nvFKWXvG7wXaALcHYZf5v/M93IE0iCHsv2EsZKQPBnzXVGmp4DwFSP4po1B7hcog1\r\ngAMaellAzzvUAizgCovN6Qct3qDEANYniPlvtnlcaQGonajW4N019kFQRHLIzPFR\r\njab5iUMMwSnT8FhZO2ZOWuWhJven+gXjxC8mfMVgBfZnAVgydNfx9rN+KzTc88ke\r\nobUdZ0OOeBzA7pIxGEFg9V6KTEEWZ+qH048vxXz4HI9B1I+2wQLBrZl8CvweEZ5U\r\n5ID8XrrE/UaNZ1CvLKtCgB24gj/m1Elkh7wA3gEcEo2JAgMBAAEwDQYJKoZIhvcN\r\nAQELBQADggEBACtgUp+FCmjWIkQUuWSdzKWdO+IH4v9wBIrF9mo0OLIakFyDYyM5\r\nLlkYZXbplGXd4cfn3ruIqJNzlIb4xa5CU0bM4TMbD4oOSlLMKM/EamKPHI3bzr++\r\nzi7mQDFxmAE6FWSMBgKKUb4tqLc5oBap8e12tPEZl/UR6d9iUB2ltvrm3T3vrjjl\r\n2Worm0eYBNqnagXmX5+wS11AQqeJemGqRy5e1yXRlTgB0IJhH0dCsFNwifEigutp\r\nFNvGFVBn4r5qCiChEoq+rCXHRjPi/eCfbW21XeLFDiLxapcZyc85JIcA7znUYoFe\r\nP7Y/ekMscwWhLbF91OaQlcWpRtEMyde/DaI=\r\n-----END CERTIFICATE-----"},{"id":"calendar","categories":["organization"],"userDocs":"https://docs.nextcloud.com/server/10/user_manual/pim/calendar.html","adminDocs":"","developerDocs":"","issueTracker":"https://github.com/nextcloud/calendar/issues","website":"https://github.com/nextcloud/calendar/","created":"2016-10-01T12:40:39.060903Z","lastModified":"2016-11-22T20:31:13.029921Z","releases":[{"version":"1.4.1","phpExtensions":[],"databases":[],"shellCommands":[],"phpVersionSpec":"*","platformVersionSpec":">=9.0.0 <12.0.0","minIntSize":32,"download":"https://github.com/nextcloud/calendar/releases/download/v1.4.1/calendar.tar.gz","created":"2016-11-22T20:31:13.020268Z","licenses":["agpl"],"lastModified":"2016-11-22T20:31:13.087340Z","isNightly":false,"rawPhpVersionSpec":"*","rawPlatformVersionSpec":">=9 <=11","signature":"nThwe9CJBCan9nuDLdhfBiQyPhmum6Aa0UcYsIDdhGMw+C2acf81KhEmBJuTTWxo\nWGby6WcrcJJmeuCW+ePU91ju7Pd76RirprhVXIEceIDzSCxin+K0oZCZ1IGVIJjP\nIkVehTsLuCeTBbjvz1b3k5QFyhUhvd32Xt7k5d7VARyI4OqnqYYNBtH9vvgeRrFw\nAxsQr4o4axof6i3iykLg6WfWarYArY4dIuu5DkPuGPWf2bbgjwWEra4sQejhOs7G\nsk1xcsfYv2NpArIbpw/wnATdjiax+Gjz1URMD3NgL5ky0ecuZmNvN25QErg3nlVr\nhh1FBfA5pvCJbkJ6nr5bU4bKaffwDX1nr5h77FS5zzn0Pyd7ZIExmVmNtaeJfnfV\n5vnclapzXMNU+R6t/ATJQd1srvSJhyljQapzsqnrjNMEUojOEvqqygJp0KwNVPqs\n3g9XGSoOnO+WULWBeISW7UVOg8BOF8pwvHIU2++bSzOdpypW0Eq6p2DPWO6qL/H1\neFLKrUg3EvnTjvknbBxMB55h9jNJr0SAlkrmyEVm6+CE3BwRWpKB+cJMBuGiwPwv\nr/ASRiJrkDThbNWAUtX70rUmCqDV6/MujLXViqOc/Q2OHvcXd1oGDccJSQT92/1z\n7nonnedyYQIDqUt7u68WL8JRxp7pFsEqKLVuWSgxW3c=","translations":{}},{"version":"1.4.0","phpExtensions":[],"databases":[],"shellCommands":[],"phpVersionSpec":"*","platformVersionSpec":">=9.0.0 <12.0.0","minIntSize":32,"download":"https://github.com/nextcloud/calendar/releases/download/v1.4.0/calendar.tar.gz","created":"2016-10-06T19:58:12.724588Z","licenses":["agpl"],"lastModified":"2016-10-06T19:58:12.790604Z","isNightly":false,"rawPhpVersionSpec":"*","rawPlatformVersionSpec":">=9 <=11","signature":"b//hJbICFMLR0Va1BGMzpLpaPREOo9QhjgfrHvDOfXVpddhvCM8ocz74X1s5hKyy\nGg67EE0pOp0dBf6RyJjduI+Dz1wQX55My7J9G1vXGCN30C/8zAcKSJoA218IWcub\nICavLkz2PkiitIOSZyBCAfEiSAeHPop/JGkq3KxQDC7QwFC78BnE9/adD9tO55c/\nDGLhvP/uTJIeH8RUifikTqVMmPH+aP3uPbZzl+AxhUezRiNCpEtZPA5QGqtQdJU4\nFc6x3d9y4IWbJV4TEIAP8jdfqtLVUQ6szFVnN8Oi1wtN9e8LIylBSYbmIZRj0+qh\nZcgntzEq6U843ZwXcAnL5jNYV0m+KNI+EkXFeWHkjvbwfCdvGPBvgFVbhc0YPzXU\nqHOe4Lvcx9X20ALG/MacV9zX69GzNnWgbBp9RnIHuaSRPFEKrNXUeXl2THuKsTyQ\nF9QtTwS5U5DcMyTO2RAN45NrRxIh8IL4stoIg5rmF7/ZaOm/Jza2gnUquOTarDE/\ntiWnNW5kWUAWyYYHvQgQix/of9qXvc2hhZaw0y623WDNrEwA+rngnjDMLA/vNv3B\nhgwQ6NbCOuHWsRK3S8DcJFpB9Kj/i7CDvDLEuJYnjSTvQ/q1XqawbJPDoRlydX43\n3/L0LvHvKVakYybv2OE5gy6bQ2Dw8e7D27DtZ6XTaBY=","translations":{}}],"screenshots":[{"url":"https://raw.githubusercontent.com/nextcloud/calendar/master/screenshots/1.png"},{"url":"https://raw.githubusercontent.com/nextcloud/calendar/master/screenshots/2.png"},{"url":"https://raw.githubusercontent.com/nextcloud/calendar/master/screenshots/3.png"},{"url":"https://raw.githubusercontent.com/nextcloud/calendar/master/screenshots/4.png"}],"translations":{"en":{"name":"Calendar","summary":"Calendar GUI for Nextcloud's CalDAV server","description":"The Nextcloud calendar app is a user interface for Nextcloud's CalDAV server.\n\nIt integrates with other apps, allows you to manage calendars and events, display external calendars and invite attendees to your events"}},"isFeatured":true,"authors":[{"name":"Georg Ehrke","mail":"","homepage":"https://georg.coffee"},{"name":"Raghu Nayyar","mail":"","homepage":"http://raghunayyar.com"},{"name":"Thomas Citharel","mail":"","homepage":"https://tcit.fr"}],"ratingRecent":0.944444444444444,"ratingOverall":0.944444444444444,"ratingNumRecent":9,"ratingNumOverall":9,"certificate":"-----BEGIN CERTIFICATE-----\r\nMIIEAzCCAusCAhARMA0GCSqGSIb3DQEBCwUAMHsxCzAJBgNVBAYTAkRFMRswGQYD\r\nVQQIDBJCYWRlbi1XdWVydHRlbWJlcmcxFzAVBgNVBAoMDk5leHRjbG91ZCBHbWJI\r\nMTYwNAYDVQQDDC1OZXh0Y2xvdWQgQ29kZSBTaWduaW5nIEludGVybWVkaWF0ZSBB\r\ndXRob3JpdHkwHhcNMTYxMDAzMTMyNjQwWhcNMjcwMTA5MTMyNjQwWjATMREwDwYD\r\nVQQDEwhjYWxlbmRhcjCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAMm6\r\nFTeqgzCXprkU83VM4/DrZWn3kqtfaR/edkC4gYT3ug7RHa/Uv1C/S++vr7pvgpnk\r\nYzQoavl/0Qlh5sKEYX+0ud/LQDoiidwBRDckFUQ1bRfVLxAD9UAVvDRHxDqJMOx2\r\ngZArbeQ3ztdSHZp4ThzBFWq2FILsJD86weG7LwHjzhW6SWgLb/YTLbuuW6tRCDVV\r\nbtB0I/a0vCwj2u91Chw3u6pWWjPakc9DQrIDH4HCIBKQ4zVrYDxAmJDRFGDvVVWx\r\nuIAeux8sd8drqSMqAhX+XMcZPRD71NQTWbCupSwWO8kgjmZnBpIiBNpzvMQzJf3A\r\nQloZtjZ2RDXAQG88eTeT8pp8yEOCEoDLpGdraKxJrh/z2Dsk30JP3lOiNYJ9vBaB\r\nC8NJbJ3oAlG7THwUaFF9fsdAKoTwzs5Xms04TI7W/v4Z/GClOzMymnR1T4sR72Oy\r\n3WaMNHv/1QGffvQn2/TtZt23Ou3P083xWx2vn5FgTcac8+x85vRgWsVCA4hq9v6m\r\nAlktB0+UWDEXpDTKD9BdFNWM8Ig9jQf7EJrvTLNnS7FIJZMB4GK8lpvPxyvACWnh\r\nR2hQOe987Zvl3B1JZNO5RvtSeYld9Y9UfMgW1aPRweDNjSuZYAKlugx1ZoyI5HyA\r\nQjfzAwicIMwZsCJDV/P5ZO8FE+23rdWaoJczpBqDAgMBAAEwDQYJKoZIhvcNAQEL\r\nBQADggEBAHQXwvj8q5khWR/ilg3JGYpmMNBYHE9OeDaOcNArkKaGMd478SDPOXeu\r\nyW7hCvNEpiTk5g0h3g3yleZFws0xH8fPsQgZANgvQXb3RCcD61NL77d0cMTr7Xzr\r\nN3Lq/ML1YLc/WwL4uV1XvpMQMwALFL1p63BU2c0ysO31zbLOjMKAJi0hHFDYz5ZQ\r\nD3xxtc17ll3B5IqrMnMHRqmOQ39Sbe56Y7T4agaIz/sUWpseo85D5kt7UAIOR+Mr\r\nQ0Bl/QinETk72afGR46Qvc7tC1t9JjQQD3AUbEGuJdGvXjJJ9GREYu01XoODmPdT\r\njXXOI8XIOK6kxXhPHUc3iWu9b4KqGm0=\r\n-----END CERTIFICATE-----"},{"id":"gpxpod","categories":["multimedia","tools"],"userDocs":"https://gitlab.com/eneiluj/gpxpod-oc/wikis/userdoc","adminDocs":"https://gitlab.com/eneiluj/gpxpod-oc/wikis/admindoc","developerDocs":"https://gitlab.com/eneiluj/gpxpod-oc/wikis/devdoc","issueTracker":"https://gitlab.com/eneiluj/gpxpod-oc/issues","website":"https://gitlab.com/eneiluj/gpxpod-oc","created":"2016-10-31T10:57:44.387319Z","lastModified":"2016-11-23T17:27:37.793159Z","releases":[{"version":"1.0.8","phpExtensions":[],"databases":[{"id":"pgsql","versionSpec":">=9.4.0","rawVersionSpec":">=9.4"},{"id":"sqlite","versionSpec":"*","rawVersionSpec":"*"},{"id":"mysql","versionSpec":">=5.5.0","rawVersionSpec":">=5.5"}],"shellCommands":[],"phpVersionSpec":">=5.6.0","platformVersionSpec":">=9.0.0","minIntSize":32,"download":"https://gitlab.com/eneiluj/gpxpod-oc/uploads/963bbf246412bcbe8979bccadb3b8d03/gpxpod-1.0.8.tar.gz","created":"2016-11-23T17:27:37.783365Z","licenses":["agpl"],"lastModified":"2016-11-23T17:27:37.862469Z","isNightly":false,"rawPhpVersionSpec":">=5.6","rawPlatformVersionSpec":">=9.0","signature":"hqhMh1l/mnwbYf4uPzEjjLFtZWHidzgR57X471OuXv2K/s87T5WhIkTSKk+2r8sp\nS7CtrF5+Pc5AgCCHvwzawN3e2+4eO4cK0+HD9CCzygzzHZEbSjufNHMMQucVoSD8\nPqR6MV9azzUpwHa/5d8fp3cFLVAle+aG0o4v5eHky9c7eaKxVJcgfjw3pjDE73N6\ngJVdtw1jf1kOFYk5pZQxDfBKFDrO5BRo5ZfZGuOuP2u/SmTwj42oTZiT7oTVWhqd\nLvJw+2TPv7B8s0Gin+J5e9K1Rs6CEWQ6WBxM+NhS5KgWB5Ig3pwm0QvMgza2cvoh\nlwVobOotfKLUBJzg0+wR7B2YH9Ao+m94h93vg7H0OKPReoTKhlDj2UExoTyeurV8\nhJdQv8sKVAxjC7/xrVaGSjM4YxFdBpzq8Zl8z4zq1o2voH5+u4ko3c62C1loDpsC\n8KrL1t6A7QpMk/XAMrPqwEPmFqlLEdv6FhzpOGyt4IEVnv6vdMTShcYw3tPvU/mD\njPtiVwpo8gWbGVIfpmwBg4wPaTrWK8V3+/1iTahIQHZfu4Lebb5mzht80HLQIcd8\n+oB4cGDEX4Rix1WxnCmE5ZzURY8xQXcvqYN+mTrUDh/3OtxQPSm5yC945SGoFNpr\nBYxfEyQcwulZrOMBdY0Ssj1AB5NOeC9OHwjJrnVe7dQ=","translations":{"en":{"changelog":"### Added\n- save/restore options for logged user\n- option to choose picture style (popup/small/big marker)\n [#25](https://gitlab.com/eneiluj/gpxpod-oc/issues/25) @eneiluj\n- add average speed and average moving speed in comparison table\n\n### Changed\n\n### Fixed\n- bug when python PIL is not available\n- deletion of bad parameter given to getGeoPicsFromFolder() in controller\n [#20](https://gitlab.com/eneiluj/gpxpod-oc/issues/20) @eneiluj\n- bug in file cleaning, bad use of array\\_unique\n [#22](https://gitlab.com/eneiluj/gpxpod-oc/issues/22) @eneiluj\n- python script do not need to be exectuable now\n [#23](https://gitlab.com/eneiluj/gpxpod-oc/issues/23) @eneiluj\n- jquery.colorbox was brought by \"First run wizard\" app, now included\n [#21](https://gitlab.com/eneiluj/gpxpod-oc/issues/21) @eneiluj\n- avoid JS error when failed to get options values by ajax"}}},{"version":"1.0.8","phpExtensions":[],"databases":[{"id":"pgsql","versionSpec":">=9.4.0","rawVersionSpec":">=9.4"},{"id":"sqlite","versionSpec":"*","rawVersionSpec":"*"},{"id":"mysql","versionSpec":">=5.5.0","rawVersionSpec":">=5.5"}],"shellCommands":[],"phpVersionSpec":">=5.6.0","platformVersionSpec":">=9.0.0","minIntSize":32,"download":"https://pluton.cassio.pe/~julien/gpxpod-nightly.tar.gz","created":"2016-11-16T14:06:33.937534Z","licenses":["agpl"],"lastModified":"2016-11-16T14:06:33.971502Z","isNightly":true,"rawPhpVersionSpec":">=5.6","rawPlatformVersionSpec":">=9.0","signature":"JtUhKRDFGYDx9xtHjdfEUFOb0O4idexUYw6ixlBhKPP8Dn7NfyBfV6KH6MJTIVLU\nQ5Jw6tv/Nr1YDOvVikcWPG0p23mQdn1+7w8DzzIGKmknxCat9/vKr83oJZdWYxS7\nTJ4I7qTvWNlbMfK8OEdl13VJXgc6ftX+1isluLYqLjEm3aBFCS+/awYNMmXO55a1\nyG0NgJRu3pw1CBCMhDaRLsunhpRNDVLsamZj1SPmeT8qy0I/arFaG6hQnAo6JosE\ndi1XkvK6TEt9g16L6eizd+JpGE7xiWFP9ZEmMmmQSOLQYwU5Sk1YWcrW3EX4vtz5\nWnEIC0SENyyAyzBO6YJfu/EP2lLnlbNJiuc4zzKLqRw/zyz3j+imJLcXHIA78ZkQ\nuyUOBkkk3xeyBGeUcYfDuBqYQOQs+F/7+cNMsIBKJhx9ef3OPURBc7X16upk3mxV\n6GsOktbHkgUwWk3WiXRriBIqbAZocvDp0+PN++PAEZVWFEZEJzztd4Fxaeo+QSN5\n5Pz/9yXYRsoSPZv82Tlh7dx5tIPUvYb+UsANh5eGWUGufTSwgYBN0H2KT/iO35D7\nkDzNyh1qNakfBhAgPjrC2p4mBKBJJjlM0D9erDwr5D4GSTW2fp92vlRHeD0X8sqo\n3kBbwGuWnmhdJhbd7zYy0jVM6tVX/zgbhycimNALG0I=","translations":{"en":{"changelog":"### Added\n- save/restore options for logged user\n- option to choose picture style (popup/small/big marker)\n [#25](https://gitlab.com/eneiluj/gpxpod-oc/issues/25) @eneiluj\n\n### Changed\n\n### Fixed\n- bug when python PIL is not available\n- deletion of bad parameter given to getGeoPicsFromFolder() in controller\n [#20](https://gitlab.com/eneiluj/gpxpod-oc/issues/20) @eneiluj\n- bug in file cleaning, bad use of array\\_unique\n [#22](https://gitlab.com/eneiluj/gpxpod-oc/issues/22) @eneiluj\n- python script do not need to be exectuable now\n [#23](https://gitlab.com/eneiluj/gpxpod-oc/issues/23) @eneiluj\n- jquery.colorbox was brought by \"First run wizard\" app, now included\n [#21](https://gitlab.com/eneiluj/gpxpod-oc/issues/21) @eneiluj"}}},{"version":"1.0.7","phpExtensions":[],"databases":[{"id":"pgsql","versionSpec":">=9.4.0","rawVersionSpec":">=9.4"},{"id":"sqlite","versionSpec":"*","rawVersionSpec":"*"},{"id":"mysql","versionSpec":">=5.5.0","rawVersionSpec":">=5.5"}],"shellCommands":[],"phpVersionSpec":">=5.6.0","platformVersionSpec":">=9.0.0","minIntSize":32,"download":"https://pluton.cassio.pe/~julien/gpxpod-1.0.7.tar.gz","created":"2016-11-14T00:57:37.521001Z","licenses":["agpl"],"lastModified":"2016-11-14T20:35:45.363487Z","isNightly":false,"rawPhpVersionSpec":">=5.6","rawPlatformVersionSpec":">=9.0","signature":"SigBof6QJZ9IMZyFgc+B3LO2+EXaAPvnxUHjJQjIl3jLzomocpDGR6WjO6gtvB81\nzXUHjJ8+huc+P9TvgjUGRTmn9a/29HZ4IKTXnYBKIUY7wSLcJNMbJSp2Zd3OFHAG\nJwRaEdh/cIRk2X6NE1VT6dFCxB+LhTM4BXOEwuNYQvU1lZDVQgTz/r68zFLWBt6R\nqhBCNJHrVp87ecS4+XaGq/CfT4k1ihiOv+f4eX9iaPzUhxBJ71iYKF7wHpDoVmIk\nNrzWFUJH3BLBuW9oiC0PApli6Xu5RXrWUsOV7OAmxXgylRCPuTFwe09hw16JMbiS\nii8WFiUtp4qW53+7eoS7Fllm7CRi/Dg6Jvjtp3msrf1m+OiYM7dLyoKw22/S4P/a\nBIErZpSCHaCfrZ+DBXrAYcas27GWE7HizzG3yXk3aDJMa0Otcsq56bSPo01JDfNx\nm1y9iuwmlon8zKKoxsJCwxaFDnQpqazaLcUO0ATHUk8LdomTA7MCXVvNFPaO86Ea\n16iyw7Cfs0k3GrvN71+SdpvWss359CEEwBMpDwJZqwSFbLRyHtogUgbRWLIJqR4n\n5uVvJqirxWkr/EtXw6UkDWAI3ZoMhMRtjn4H4ekANP5mC8R0yp+UuFs2RkEC5uA0\nKzzh73WmxmpeUl6jcMZ49gXn3PTCC2fJNrdmSYch5Dc=","translations":{"en":{"changelog":"### Added\n- option to choose waypoint style\n- show elevation, lat, lng in waypoint popup\n- ability to display geotagged jpg pictures on the map\n- pictures slideshow with colorbox\n- pictures work in public dir link\n- use NC/OC thumbnails to display pictures on the map\n- options block hidden by default\n\n### Fixed\n- fix bug in geojson generation for waypoint-only files"}}},{"version":"1.0.6","phpExtensions":[],"databases":[],"shellCommands":[],"phpVersionSpec":">=5.6.0","platformVersionSpec":">=9.0.0","minIntSize":32,"download":"https://pluton.cassio.pe/~julien/gpxpod-1.0.6.tar.gz","created":"2016-11-07T12:11:00.619161Z","licenses":["agpl"],"lastModified":"2016-11-07T12:11:00.699921Z","isNightly":false,"rawPhpVersionSpec":">=5.6","rawPlatformVersionSpec":">=9.0","signature":"WBts2fm2rW/7LMHYjcx9a0k0WTXV6PnGRxTl+158cjfV7ruMpNvhK58iTjrox69k\nFWAoIi1wNAlLBu9Xet1j7HKi4TC9q61IEN+lPlnwBCu0uHawiqS2gqB4i8A019Ei\noLsgAPWh8ndy6+gyUtPhVLVduLH76aT6KTwAiHPknV0zPtxsUy1P6nbbNOS5A5rG\nSQBqljy0TbcjOctTudEPp1IqjJIwcd12eZ9MLG4CEIO13n53pMAsuXJf4jnKSCm0\ngimvsFOwFRjBab3ZPwtOqeVw6aIh/lYF3U3/k8YBpaDN74m30nDtkp8teXBgshSY\nVYvX3yOAYe0PIR419IX0eoHb61K0VfZYvPT4FsOqjDr0zlVB8Rjq+6SiK4vMD2+6\neGE0aHbjR9HV5jymUnFYdm/hlhcZGaKrAiQKfBY6Vh0SWKfIv7bdGfQYauePAdZt\njlsV8lIwOy7FGAeP81CcjzWWfDeBgYr+MSzfoDNoTi41MvUaT14iWPIU/s5P1/Qv\nALGxgsbmB19wEgNbdh1UtTUY3xARLpWPYdUqU7yDcsddX9vCoCG2G5wCcbYJRj8o\nC+H7wdgPJoiMY/p4Go/lyWkvmzhfXrOeXytZIFXjb3ERVd1vD9WSt1DSy/7gsFYt\nxzzOPgqMvL3BbeluNuzNv366oT872s3OuFKa1ZOYY7A=","translations":{}},{"version":"1.0.5","phpExtensions":[],"databases":[],"shellCommands":[],"phpVersionSpec":">=5.6.0","platformVersionSpec":">=9.0.0","minIntSize":32,"download":"https://pluton.cassio.pe/~julien/gpxpod-1.0.5.tar.gz","created":"2016-10-31T11:08:41.017766Z","licenses":["agpl"],"lastModified":"2016-10-31T11:08:41.068782Z","isNightly":false,"rawPhpVersionSpec":">=5.6","rawPlatformVersionSpec":">=9.0","signature":"UXeZVh5f0/WZE+r/dHWc1pu9q4qr/zACX6XraMhhIuKIp7vNCwUESeqJtVc99QZw\nw9kJp0isvib6l0zbQBRS1vI7xwKKBQyeaEhIciEs1JjsaCiato1Gyi26N+fY2N0Z\nFWlTwCsF3DdlwERXTYfeCpsOWCoxLxHKhnJIjUc0PVme/Ste4zxYj+5Su1RpadSw\n4vGnkW8zy/0tzua50NQCrOg+B4jXzH9kMWAP47w3sdP5CYalHSHl8EX0D1RjgGU5\n7vZYX3wF853FvQDbL4JXXCJupj3wZe8py8McWpQIcgz1p3KmE7A7d/rdNWExT+T+\nDxtStJ56qTRMz4aFwoSFxJrrEfgHIsE9Gv+Vo7nshCUYA8gkfHeckiaUtH1EiFTh\nVNeO6mTIqGpRosFvfUrZMKcuF5j74vGQjNM1o+M5N31gtLoPSkU605f/U4v+j2oC\n3/N1rYF2SEDFO0EgAGXaXVhB0ltSDkHJw6vZJ1L8Qz6tooUMDxaMri8vycA6LHvE\nqN+z+S6TXMfLvN/6ATYPGhicrWmkMT/k7v1az/hcnfH+zRyLZyFx94s88JWF7Jf+\nI+tgDbfqTMAIcytJUC+KfdQW1ueXh5F0owrOYM6jgBRvhqj1T8s+Twgw8orGmRPe\n9h8G9Z3wZAooQvmC0KdVhLuOeIkqt/S5krELNFFBRnk=","translations":{}}],"screenshots":[{"url":"https://gitlab.com/eneiluj/gpxpod-oc/uploads/db5af6ba7ae1cd4d22ea81d418f5c762/screen1.jpg"},{"url":"https://gitlab.com/eneiluj/gpxpod-oc/uploads/123588561a8067185572a8d1887ef906/screen2.jpg"},{"url":"https://gitlab.com/eneiluj/gpxpod-oc/uploads/427688b80bf8428dd45bd15d69b19075/screen3.jpg"}],"translations":{"en":{"name":"GpxPod","summary":"Display, analyse, compare and share gpx tracks","description":"\n# GpxPod owncloud/nextcloud application\n\nIf you want to help to translate this app in your language, take the english=>french files in \"l10n\" directory as examples.\n\nThis app's purpose is to display gpx, kml and tcx files collections,\nview elevation profiles and tracks stats, filter tracks,\n color tracks by speed, slope, elevation and compare divergent parts of similar tracks.\n\nIt's compatible with SQLite, MySQL and PostgreSQL databases.\n\nIt works with gpx/kml/tcx files anywhere in your files, files shared with you, files in folders shared with you.\nkml and tcx files will be displayed only if GpsBabel is found on the server system.\nElevations can be corrected for entire folders or specific track if SRTM.py (gpxelevations) is found.\nPersonal map tile servers can be added.\nIt works with encrypted data folder (server side encryption).\nA public link pointing to a specific track/folder can be shared if the corresponding gpx file/folder is already shared by public link.\n!!! GpxPod now uses the owncloud database to store meta-information. If you want to get rid of the .geojson, .geojson.colored and .markers produced by previous gpxpod versions, there are two buttons at the bottom of the \"Settings\" tab in user interface. !!!\nGeolocated pictures can be displayed if python PIL is installed on the server.\n\nGpxPod proudly uses Leaflet with lots of plugins to display the map.\n\nThis app is tested under Owncloud/Nextcloud 9.0/10 with Firefox and Chromium.\nThis app is under development.\n\nLink to Owncloud application website : https://apps.owncloud.com/content/show.php/GpxPod?content=174248\n\n## Install\n\nNo special installation instruction except :\n!! Server needs python2.x or 3.x \"gpxpy\" and \"geojson\" module to work !!\nThey may be installed with pip.\n\nFor example, on Debian-like systems :\n\n```\nsudo apt-get install python-pip\nsudo pip install gpxpy geojson\n```\nor on Redhat-like systems :\n```\nsudo yum install python-pip\nsudo pip install gpxpy geojson\n```\n\nThen put gpxpod directory in the Owncloud/Nextcloud apps to install.\nThere are several ways to do that.\n\n### Clone the git repository\n\n```\ncd /path/to/owncloud/apps\ngit clone https://gitlab.com/eneiluj/gpxpod-oc.git gpxpod\n```\n\n### Download from apps.owncloud.org\n\nExtract gpxpod archive you just downloaded from apps.owncloud.org :\n```\ncd /path/to/owncloud/apps\ntar xvf 174733-gpxpod-1.0.0.tar.gz\n```\n\n### Post install precautions\n\nJust in case, make python scripts executables :\n```\ncd /path/to/owncloud/apps\nchmod +x gpxpod/*.py\n```\n\n## Known issues\n\n* bad management of file names including simple or double quotes\n* _WARNING_, kml conversion will NOT work with recent kml files using the proprietary \"gx:track\" extension tag.\n\nAny feedback will be appreciated.\n\n "}},"isFeatured":false,"authors":[{"name":"Julien Veyssier","mail":"","homepage":""},{"name":"Fritz Kleinschroth","mail":"","homepage":""}],"ratingRecent":0.5,"ratingOverall":0.5,"ratingNumRecent":0,"ratingNumOverall":0,"certificate":"-----BEGIN CERTIFICATE-----\nMIIEATCCAukCAhAaMA0GCSqGSIb3DQEBCwUAMHsxCzAJBgNVBAYTAkRFMRswGQYD\nVQQIDBJCYWRlbi1XdWVydHRlbWJlcmcxFzAVBgNVBAoMDk5leHRjbG91ZCBHbWJI\nMTYwNAYDVQQDDC1OZXh0Y2xvdWQgQ29kZSBTaWduaW5nIEludGVybWVkaWF0ZSBB\ndXRob3JpdHkwHhcNMTYxMDMxMTA1MTI2WhcNMjcwMjA2MTA1MTI2WjARMQ8wDQYD\nVQQDDAZncHhwb2QwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQCq9p5l\nzNzR98l/xPgrplWrGQBhF6aQSLpnIyCdLAYKk+CmXn47W1pHh5CRYyCCyB8YPBBG\nTwbpP69pP1updfK2vUt+ShYmCXLxOLB3qEdhnwgqFfwpC48Ocev9d6XcacYp7jwu\nRNtv0ocMkm5o0TWWupcutQWkmqzCVq+OkrqM0xrf3mfPymuM6edEREshukoL86Ei\ngTuMMGT0XO99LikszvdceNQYEATix1MHzSVhkE7jHCNBXb95H6nQGr0v7R1MIbrI\nGFlgqxwwNNKwBFNfPMWZVnKwz9hoIwW6WOuu7ntwVcPqwB/gUsRZJTu7EjIW0trX\nnhA6xLlc4X66W1sdUCkJOxsV+Y21akz6wynI0SzIfjALLI2Ls4QWrPM8GOX8nPVM\nm+Y5WXzqLJScdWYoefFJKS7kxwUJRewREB9ykCG5OdDubV+Iu/6jh6HWx3h4p3ih\nqkDypPWoxpfLgA8VZkLD1RRKGkRa858QBGdF/RHbYT3JfLEp9l9gJVKZE/yw7HKk\nwsZ/T6CMpLyorpd1XWtp2wLX8lr3pp9ecVDOdAMSqD2thDMDsZA82JrJ/vITwkCF\nBlqtDZmT0UnpxYNYTfYBam5Cd00jsqCt+Hr+QkODNe8Yae9c/D0zE3h2Vt7g9H+W\n7Ei+rF5nDYTBAApoETxK7+aUZpycBf3THAJOcwIDAQABMA0GCSqGSIb3DQEBCwUA\nA4IBAQBbCGAEwg3M5QJDMnZgu0zNOH2f9bamAS9ksyCZqzLoeQic1W7GYYe9NqAi\n7lO5jXRZpTN4L133IUQPtxCxuDooD2vFmCne92tLxJbc7uqlSVfhL8uMVOlnrA99\nKTAhySTZU5so8/OibrngnBmcdWwbhaWoCQ671M8aXM1wg2FVYDqB2GP3RvbpW11L\nOc+4tfh4mO4TwXygf7KYMOJyJW8mNNY7PZ+XW2Qe3vSXR3DuN8H8fgMh5wppXPJf\nE0+yNs42hwFjSojtI8BCb0s5DTleaakpDo8HQGNzEXP8tBlUYudtjzdP0jxFXbFa\nsT9pcMdeJ0/t5HqJSx1EjUCLYS4y\n-----END CERTIFICATE-----"},{"id":"ownpad","categories":["tools"],"userDocs":"https://github.com/otetard/ownpad/blob/master/README.md#mimetype-detection","adminDocs":"","developerDocs":"","issueTracker":"https://github.com/otetard/ownpad/issues","website":"","created":"2016-09-29T15:58:52.814912Z","lastModified":"2016-11-19T17:37:52.278497Z","releases":[{"version":"0.5.6","phpExtensions":[],"databases":[],"shellCommands":[],"phpVersionSpec":"*","platformVersionSpec":">=9.0.0 <12.0.0","minIntSize":32,"download":"https://github.com/otetard/ownpad/releases/download/v0.5.6/ownpad.tar.gz","created":"2016-11-19T17:37:52.234684Z","licenses":["agpl"],"lastModified":"2016-11-19T17:37:52.423930Z","isNightly":false,"rawPhpVersionSpec":"*","rawPlatformVersionSpec":">=9 <=11","signature":"dh+Txg1iVfqXr8+cxplNQuBZGErSnXUo0ewGwnybNMJqp8/EjEo72+zPpW3dVnhY\n67YCvhrm2bo+VRdFFymEfymzSJu9nWVFkGJhEwvTxPyIdAtuD5YAVrzmnR6L+H7m\n7Q1nXE63ICPCAQpHkxIfIXLh25OhWeyofBB8AVsjDUNn58FEYJ8fFkr6dCgPriZS\nsM2J+xtZMDYufy+xFMsVf/Q3WopjFuBjMC3qOecW76ZTwtREaswOC2RtpzUku2r1\nsogrfFlFer3Ii9/CWgOktnLfjB1DzbTwdEkM2xNVBRJgdMXt2VLA9FsxFFkjmr5A\nl7x9cNLWA8RLpOIpIMBbaef75u5HgRBvSvq114UsA9GCu/EYbIgD8YxEt7xuKd4t\nenksJB5gJ2IQNdHrPbsil59AsJ/dismDN6ktYgWQEk5dINzvm9EAvucueW0Gt+Jr\nqEC5WBgJucsFxSvkHh52v43M8jgPYBfHWEL/M/+377z3+mbuIh+BcQ+vcDdiqxTF\no3n0+gw3QYIhLEe75sUhxG6ynVUdW25AKKju1kVj3KJnZTBH1R8t8/zy4DnJG8d4\nuRGqyU4BXpZjEC3nVlsC7vCncWWhxl0WZQ/MWKqsfjVAU4I88E518D6NioqMnPEJ\niCZ2x+69UCDEQyfCSKajgAYT17r3OhZei8F9KSCH8Vw=","translations":{}},{"version":"0.5.5","phpExtensions":[],"databases":[],"shellCommands":[],"phpVersionSpec":"*","platformVersionSpec":">=9.0.0 <11.0.0","minIntSize":32,"download":"https://github.com/otetard/ownpad/releases/download/v0.5.5/ownpad.tar.gz","created":"2016-10-06T07:51:05.278637Z","licenses":["agpl"],"lastModified":"2016-10-06T07:51:05.348825Z","isNightly":false,"rawPhpVersionSpec":"*","rawPlatformVersionSpec":">=9 <=10","signature":"nYsQ9U5r7uXwtcquaWGm2XMJBNYCcA95aUx9gLZ/wEmjCHqId7+MzcCdBnom33+j\nat2XR2a4R96UAUP78bfSC4Yb7nPepFT51Y8CSpV3mDT85/+SgJdq500fXldq+qGY\nffXLneadAztyOfZO9TXljaCLdREYI0LJIGVENsxBQVKM/eyGIuZO7fF70cH5vbfS\ns37+BXB+fxcDTlP2Xuulra8HsNoS81bzjsdVMLM7B7QwwO6rZ1zd5c3UzQ1LmY5g\npQUBNd0KjfHfZ6+Fd64XZO6NGfgucGNmL3lgxdsfUqKiLtikvFxK39dYW5MckV8p\nvLoS2nZ7cgETQmAW9Ahn3ro7gXWcPxzL41oWtZOOHRRC2Yz5zlZ3Bky1o+bF9g5a\nYdDF13zV6utUkhlplZhWbjKaXa04rzOvmut8Iqhx/tmDtZRYtaQXJZWutVJYtPC3\nH86uJJnUHHNFHeoT560mp1Hq0dTeR+G+yWsPacPD1rTYgZOUVEtj3Y+YdbTODR2o\nOdGzeYFl+6CL/OcY4wPGRUCTFwvc31lIUd4DK5SPfN+IGtuuXhAqVhwy6lpkcKRs\ncj8sBoVXbMvEtMnt5uARBvA4tyVffUL4oyoIsUnvXz4u+q4WVt3T17swLm6HjGVC\nNVqU0srHN7EeBRhHlXP1CrKQWGQlS4k9j9Li4Iw+X8s=","translations":{}}],"screenshots":[],"translations":{"en":{"name":"Ownpad","summary":"\n Create and open Etherpad and Ethercalc documents.\n ","description":"\n Ownpad is an ownCloud application that allows to create and open\n Etherpad and Ethercalc documents.\n\n This application requires to have access to an instance of\n Etherpad and/or Ethercalc to work properly.\n "}},"isFeatured":false,"authors":[{"name":"Olivier Tétard","mail":"olivier.tetard@miskin.fr","homepage":""}],"ratingRecent":0.5,"ratingOverall":0.5,"ratingNumRecent":0,"ratingNumOverall":0,"certificate":"-----BEGIN CERTIFICATE-----\nMIIEATCCAukCAhAPMA0GCSqGSIb3DQEBCwUAMHsxCzAJBgNVBAYTAkRFMRswGQYD\nVQQIDBJCYWRlbi1XdWVydHRlbWJlcmcxFzAVBgNVBAoMDk5leHRjbG91ZCBHbWJI\nMTYwNAYDVQQDDC1OZXh0Y2xvdWQgQ29kZSBTaWduaW5nIEludGVybWVkaWF0ZSBB\ndXRob3JpdHkwHhcNMTYwOTI5MTU1NDA3WhcNMjcwMTA1MTU1NDA3WjARMQ8wDQYD\nVQQDDAZvd25wYWQwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQC6CY7I\nHRJTaqDu376vt+kruX+QOL864joScxRuh3IOVcQktCvxasuA0EtrX7TCAQrV1tBK\nfkqJxU9uOV54RTgyh30yH/ZtnF2bYQwViGM06Snc0riqWydFrN5fxK52dpZWs63o\nUFCNhHxrX4aUGyfXu5nQMISLm4QHoZ3LDLofk1ZsiK62fM/Jz8N2PM8qeHzf1ATo\nSKcAOd3UeaS9C8bv2DuiZM7unkSO/tjrBzkMiq8ds9sIzBBsyk6BRh2HQjHPOtmO\ned+pS9mIZmc2xhssXoHL4IfZwTqwhktpsaTl7v0ROw2dwDATz/QoKMkUpboQ5lkz\nwgLQhoIZw6uAZ1R/Qjze59I3iU8zIo9quDarHBotZNXboYCmg9FRfE4mHtegVaa8\nv1a1JvFQ5gvsWEsKSV6Bzb65GTp4KG4q7YnUrzh6HJyDCGLvLlWm5OWsFj6sNzXX\nwLOv6JLORMbF4ZIo2iybb3x7gdfCu9JxMZ4JtOUC8KSJ6+ub15C1Aia3lN68dNts\nY6KwUF1Ted0o4OQPAulq5pUc+g6dTYmIKsavIiPKhMtl86AbUK50vRTeuGdFsT7X\nav73IanPdFI9bKth+tajgvB6dxcVnvBXbrsLUyEcsxsxtBJvQcMYS4aZ6ZJYLTep\n7AdK0Zt1iMdXB8+4PCps4rcG6bYB/uJeEAVm7QIDAQABMA0GCSqGSIb3DQEBCwUA\nA4IBAQCM10O+sCYhIExnx01vGzKlnRS7MSQNx8ZMmbR5Elfz4AVJAEJ96ytS2DXH\n2c+hcD0wAenXQEFk920AEqFQBT8DP34p0FmF83aMHW08ovzFiu4MdlhcqrLnko0h\ncZTXHVyS/8JZh+o6SVm8R0/BBLF1MQQ5TqRkJehbmk6gL0+MSYxehUDKWTjJITkR\nifneTw/Ba1d0AXBOq0c0HFyGxMPIlWe4qn5LtxH5t0wyVGeSj4jyv4nvd3ZGuAgY\nEUa2uYht/z475k4+vf0YhV98iQH07GnmlfD2TDZgmOCQGKlNfJh1v88OZyLLa3dz\ngRHzGwKbAiJ8T8bbpZ3e2ozXxADr\n-----END CERTIFICATE-----"},{"id":"announcementcenter","categories":["organization"],"userDocs":"","adminDocs":"","developerDocs":"","issueTracker":"https://github.com/nextcloud/announcementcenter/issues","website":"https://github.com/nextcloud/announcementcenter","created":"2016-09-14T10:38:53.939634Z","lastModified":"2016-11-24T11:21:50.324839Z","releases":[{"version":"2.0.1","phpExtensions":[],"databases":[],"shellCommands":[],"phpVersionSpec":"*","platformVersionSpec":">=10.0.0 <11.0.0","minIntSize":32,"download":"https://github.com/nextcloud/announcementcenter/releases/download/v2.0.1/announcementcenter-2.0.1.tar.gz","created":"2016-11-24T11:21:50.317635Z","licenses":["agpl"],"lastModified":"2016-11-24T11:21:50.386203Z","isNightly":false,"rawPhpVersionSpec":"*","rawPlatformVersionSpec":">=10 <=10","signature":"lmqeE6xBqUJfhuXPbjCfuWiIP0FEB4V/SsF/OvYar6rLpvDpJVf3DJoeIoxXurRP\nE9/xCcNN44P8PreRRDnFLCa0XsKOtwoGa56Lxk7IKvtiQG6xu4J6PKM+q/tIeF9K\nakw0LQXtjZB5InPhnCDDbY5YS9jgGEBylSHsgNgrElipcW+BzOBu1Amw4FECVlQw\ncQ83bio+YPZvsnE5+v3/bAx0m6QNxfyN9Sn6rMEqRkY3jfA3vejXGQH/XkputfV+\n5hOz48KbOVg7cKxg+ieJlSwC0aYjb+RXiopjc3icCoIF1llltOOeSsVYSflOb080\nupociPgQ6qIab/VNNXa2YQ==","translations":{}},{"version":"2.0.0","phpExtensions":[],"databases":[],"shellCommands":[],"phpVersionSpec":"*","platformVersionSpec":">=10.0.0 <12.0.0","minIntSize":32,"download":"https://github.com/nextcloud/announcementcenter/releases/download/v2.0.0/announcementcenter-2.0.0.tar.gz","created":"2016-10-06T12:41:56.195206Z","licenses":["agpl"],"lastModified":"2016-10-06T12:41:56.263124Z","isNightly":false,"rawPhpVersionSpec":"*","rawPlatformVersionSpec":">=10 <=11","signature":"NVWYz73KtuoZ7ti2sluztJO5aFUc7PzhlDcg0VWyAQd1H7sk5wjw7i0bhrjw8O7M\nLsrb+PegnsL9eMlYM2WrRom+RF1PDP482xymZf1T8vh8qcTCm3TK89xSuiSm8yoA\niWUb/Uv/ODj74wVDWqWxAFKaAG/FestCB3InOOZQqQZLzlAV0U9ziYDGNzBjFqof\n9rLNxJ2IOqZOA7hhMIKhSrpA0KkSfNhBsVf8CWClYnVkZQiq0LoYkHkHIlXmXUr3\nOfQFKEjtsx+bNLa6CkAaocHGHJXAofX3GQZ9cjBsjZqiTfbXfcVk0kRfz7pwL92L\nI1McfJYvgMxDQG5bjRpNJw==","translations":{}}],"screenshots":[{"url":"https://github.com/nextcloud/announcementcenter/raw/stable10/docs/AnnouncementCenterFrontpage.png"}],"translations":{"en":{"name":"Announcement Center","summary":"An announcement center for Nextcloud","description":"An announcement center for Nextcloud"}},"isFeatured":true,"authors":[{"name":"Joas Schilling","mail":"","homepage":""}],"ratingRecent":0.75,"ratingOverall":0.75,"ratingNumRecent":0,"ratingNumOverall":0,"certificate":"-----BEGIN CERTIFICATE-----\r\nMIIDDTCCAfUCAhABMA0GCSqGSIb3DQEBCwUAMHsxCzAJBgNVBAYTAkRFMRswGQYD\r\nVQQIDBJCYWRlbi1XdWVydHRlbWJlcmcxFzAVBgNVBAoMDk5leHRjbG91ZCBHbWJI\r\nMTYwNAYDVQQDDC1OZXh0Y2xvdWQgQ29kZSBTaWduaW5nIEludGVybWVkaWF0ZSBB\r\ndXRob3JpdHkwHhcNMTYwODIzMDkyNTQ0WhcNMjYxMTI5MDkyNTQ0WjAdMRswGQYD\r\nVQQDDBJhbm5vdW5jZW1lbnRjZW50ZXIwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAw\r\nggEKAoIBAQDPx4Hp1HdBo5v7bDEiVcv2UrVjNW+fPPKS/5rwbagtPcE/1v3WDcwX\r\nvFwaXk8qCn2UpPSQ2b1rTuTDm51G1ZmEZhNiio+rBfEe9F+3tLsq9lElqIPKhkAq\r\nEUVI6dcN+jSqvLmLhuwloEoQQSYaLrX75mY3lGqTb83h1l2Pk/brVixuVf4vJW31\r\nTgeieuGKnC+keLzKOrvTHffJakU8ktwB2Nuu1o+jN5a7u1bxKkP3LjEWPjq236hk\r\nAoOcW/wi1dUEyUKUZsZQeJyvTJh1UXdLHKwYywtUu1/VLZ1IUtNyPBfiQ8ukPp3T\r\nTnSSmG3ZnvsfM6DmAvLZ8bBQkMBzEcTLAgMBAAEwDQYJKoZIhvcNAQELBQADggEB\r\nAAB3i2NgiZ4rpNag7cXYdaFxAxdDWnke1+LX2V2R3hzGmx73/W6cKLpo3JBn9+zT\r\n1aEjlqkt0yHu4aAPVYQzOa5zIV8mjP84p3ODSyV9J8lfjFNXT7wdA8+9PVx3lVki\r\n2ONoCNBh1kOxnxI4+BsMlQfF00ZbBSuGcMm3Ep3lTFWXzuUn3MQITzPwkL5LkW6a\r\nsli/yAYQRTVDsXD8A3ACYT7BG31jGxyXtIHzqCci0MhZFdKKayMYkwfjZchIUtGN\r\nJJoU8LQoHwGRtp3wutk0GlFzpEQEvSsn/Lsvvot5IfIe46tnzA6MVj5s64s5G8+Q\r\nphhXFlzXqO/VxquPdbfYjvU=\r\n-----END CERTIFICATE-----"},{"id":"ocsms","categories":["tools"],"userDocs":"","adminDocs":"","developerDocs":"","issueTracker":"https://github.com/nerzhul/ocsms/issues","website":"https://github.com/nerzhul/ocsms","created":"2016-09-19T21:56:04.745481Z","lastModified":"2016-11-11T16:29:55.864273Z","releases":[{"version":"1.10.1","phpExtensions":[],"databases":[],"shellCommands":[],"phpVersionSpec":"*","platformVersionSpec":">=9.0.0","minIntSize":32,"download":"https://ftp.unix-experience.fr/owncloud-sms/v1.10.1.tar.gz","created":"2016-11-11T16:29:55.856768Z","licenses":["agpl"],"lastModified":"2016-11-11T16:29:55.947926Z","isNightly":false,"rawPhpVersionSpec":"*","rawPlatformVersionSpec":">=9.0","signature":"hVzbkmmtJCtiOkZGe1mkWElqS3IPQ8wLtSzikVvoKmcg+Zq3YLQjpQWzy0t3UVjo\n9I/BfnL0bF+kjtGc9xF6M8IQaFqPrfJmN+lNT8WYIKLI97TTsLmJGg8Q8PAux3nY\n8/NxMjWdByMw9nVBClKo0o9eSW4+EnaUSJ62Gl/XWjq728kbB16WZm+iesk8LjJJ\nqqAgczWGwz6lkZTCN5o9n0a/YoLJTf4iT+OItHZyS609Cqaxx9CAmZPj/Xn5g1fm\n8hqO2ITAXLoBj4rYS/QsZTMcubtGkJ8fq3XYKVSv2UXZfvGsNWbbGV7puKN33uWJ\n5MrdoMlJ8XnJRPDlCBcb00LY+AB+hAMooLnNy765/Ew6ztp4KNLEPWGG+Ut8/Lkk\n0jIULl1RF/FjlW8P26NfwH36K30RCJFY06OFcWnxGBkkQaNFORDIsKcqTAxkl4x5\nnfKBkNdQZppCVfOSKOZj4NkWfWx75Ouq1S0QksmOsMZoOcjy1TbBKR8h6dt9DQub\nWpYBL0QwyQShGp0Vb1qCKkP69ZQAHVUJNzIFPz9LyoguvFyv8iZmAPLYDnFBvlf2\nnSHtA19rnJmZ4H7RJ02r6BdkstxISvEiHU7RLjNQxcb+DptIWX5C03wH87HTNIhr\nvptPorEoSY1KwW9fqUvvLE/c+vfkr5cvIEwZlyVKVXU=","translations":{}}],"screenshots":[],"translations":{"en":{"name":"ownCloud SMS","summary":"A app to sync SMS with your ownCloud","description":"A app to sync SMS with your ownCloud"}},"isFeatured":false,"authors":[{"name":"Loic Blot","mail":"","homepage":""}],"ratingRecent":0.5,"ratingOverall":0.5,"ratingNumRecent":0,"ratingNumOverall":0,"certificate":"-----BEGIN CERTIFICATE-----\r\nMIIEADCCAugCAhALMA0GCSqGSIb3DQEBCwUAMHsxCzAJBgNVBAYTAkRFMRswGQYD\r\nVQQIDBJCYWRlbi1XdWVydHRlbWJlcmcxFzAVBgNVBAoMDk5leHRjbG91ZCBHbWJI\r\nMTYwNAYDVQQDDC1OZXh0Y2xvdWQgQ29kZSBTaWduaW5nIEludGVybWVkaWF0ZSBB\r\ndXRob3JpdHkwHhcNMTYwOTE5MjE1MzU5WhcNMjYxMjI2MjE1MzU5WjAQMQ4wDAYD\r\nVQQDDAVvY3NtczCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBANqZVIzM\r\nwBJuacuvgYKr2KnXuYhjKjZ58nfspSebsaGLr0ifBbo8L+NH5eaynnLCNhpegmu0\r\nO8D+KrbM1LtIkcdg1/eFpN5dTc6G2OAc9H9stmHs9nroF6MNhszgdZCz8Q8xkSoD\r\nGdSm8hdPg5GcfLrH27UilGtzdQlWJ1DralLMt3l+SfGJo152c/dc+e6SuT8+EbY2\r\nCeLdH5ImasXNpUgY+tAoEt2ZvhBrUghykBJTJVOjwL1jGLT37ybMtV4FBKo6hpeg\r\ntq/YzEk1ijBAC4pmoNWixDKCdolpVJVz0fijI9mlda3llurcp8eMhxfYJ9soXLHp\r\njvLX02YY6RfPcyy48uWVk4IEt9BvZWEVAAp7hCGA2yXrVSsR37E6sDbLsBcKav9A\r\n6dkGAgfmGkr2WT6O1/EhK/MakmnYO4WD1B+E7PnxtP/wOa+aQBmntQcd7igDiwzG\r\n6h05NYAWcRhqfZ4KWYsq0t0SezMbuHOhwzzi22q8wijC5YZbmhKSh+b3N8XwYKDi\r\nZaw+fSahPbRWaLyR3wn9zh7vKCwqrG3ugrNo6CtyoACAnmxKZ97ROFJIQTe3ndLL\r\nmv7Wy8iCZLhRYUaW/GKrF11AFwBVec9xmvkgU+PIKq2HSjwi9sCF+pFyhVjmq29C\r\nmZEPKUV7ySIpNHXpsXm8kTJJfqjSdb2ECbLfAgMBAAEwDQYJKoZIhvcNAQELBQAD\r\nggEBABvn97e8Nw8KAscf6FX/nZ99rEX+3IrZxTC8fmBgNwAvlbF2A+QZQcFI4G9/\r\n85nHK117+u7XDuwWl4QG3flWlI0hDE59Ud9Bd4AiTQ12VoXlNdYoTg/mXARxVozb\r\nKYqZ+1xRQclZKb2AqW8YiGo18okIKovn9VVRAFYPYx4O3Ve1FjgfsaMlIZLiXUFm\r\nkk+2qWo6kYsdU9FABLo6izx7RFOMbnYNre5FmDrWP1Dga/U7ErK/Dilh8g9b3HrP\r\nwP8OIZhdtFWw21wDTfyqrb9EhC/tsjPVP9u+bqyognHeiMhjbVYRbSvz5o8T7Mhj\r\nbxalCt4/LnMIfMwVyIvye7Uy2GY=\r\n-----END CERTIFICATE-----"},{"id":"rainloop","categories":["social","tools"],"userDocs":"","adminDocs":"","developerDocs":"","issueTracker":"https://github.com/RainLoop/rainloop-webmail/issues","website":"http://www.rainloop.net/","created":"2016-10-20T04:17:37.217555Z","lastModified":"2016-11-18T11:36:04.309739Z","releases":[{"version":"4.26.0","phpExtensions":[],"databases":[],"shellCommands":[],"phpVersionSpec":">=5.4.0","platformVersionSpec":">=10.0.0 <12.0.0","minIntSize":32,"download":"https://github.com/pierre-alain-b/rainloop-nextcloud/releases/download/v4.26.0/rainloop-4.26.0.tar.gz","created":"2016-10-20T04:28:21.491747Z","licenses":["agpl"],"lastModified":"2016-11-18T11:36:04.619927Z","isNightly":false,"rawPhpVersionSpec":">=5.4","rawPlatformVersionSpec":">=10 <=11","signature":"nTYIVSB6mIwKtXIrKoVGsOGFflpLjed8jFem1VLQNtXQj4bztnNrdc4YaPIn0yzM\nyLpMSqRDNzdYNFuOeDiyKLPJPTA++MotLCNjEe7kxUekek+m+qzgnGBdcT7RQT6R\np9xWGecnVx94d6aA55uiRhgQRyHpdDMMLCOz1be+HvpwHy69DRFZ1+SPmGUt6eW0\nu5yS0vHCu1K22cbrVNXFKjxAOlGcIDm61oQuz7ycl3uAujZO4rZbWt55jilgKGak\new559A5gTp9W+j+TWKIcg6LIZ9zLRlGjcQrWJrsc+OBZQcqiYimSFyO6HhfT9TPS\nPof//I+dSsd+H0SRGGeL8DvSnK+NKZL1q5EX5pziqsv6nZFITpCDwmAN+I8AnXXL\nSNkFi53M8RZTOABpD2x7YPYP1cEvwrRweqV/C/oHcYnpfh7D2DjFeWwXsjeAXrHY\nhgFhPrg+7rf7g6UmJFOCp0dC9sBdyQ3KtJkv7bGqPr854r2cdA7xW0QHWQ2in9qQ\nLhIczc32ECi3ZVVgyF8zyT4Y/3MRS05oX3FHvHyt88mjni6bVaO78F7ZRSha8gHh\nNOAkku7AMXPvUCHaZP2iVCCoAViEso8GeR3O8xh2G42Ai61RLYwx8LB1+23EoJTr\nmfFuRYNSg+qAKCokXNnh+lDlwu4AkaQo3vtKGPXvU7A=","translations":{}}],"screenshots":[{"url":"https://raw.githubusercontent.com/pierre-alain-b/rainloop-nextcloud/master/screenshots/2016.10.20-screenshot.jpg"}],"translations":{"en":{"name":"RainLoop","summary":"RainLoop Webmail","description":"Simple, modern and fast web-based email client."}},"isFeatured":false,"authors":[{"name":"RainLoop Team","mail":"","homepage":""}],"ratingRecent":0.5,"ratingOverall":0.5,"ratingNumRecent":0,"ratingNumOverall":0,"certificate":"-----BEGIN CERTIFICATE-----\nMIIEAzCCAusCAhAXMA0GCSqGSIb3DQEBCwUAMHsxCzAJBgNVBAYTAkRFMRswGQYD\nVQQIDBJCYWRlbi1XdWVydHRlbWJlcmcxFzAVBgNVBAoMDk5leHRjbG91ZCBHbWJI\nMTYwNAYDVQQDDC1OZXh0Y2xvdWQgQ29kZSBTaWduaW5nIEludGVybWVkaWF0ZSBB\ndXRob3JpdHkwHhcNMTYxMDE5MTkzNDEwWhcNMjcwMTI1MTkzNDEwWjATMREwDwYD\nVQQDDAhyYWlubG9vcDCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBANqB\n5jnF9qZ/qjckt0kRjpHCOMtJumW/KiQoMeNP5nGv4ad0DS3KemOapUef8Zn7qCYb\nMnODhK7HBwPifFzI1j8bnT2hP6E0geFLb0MdN59d2NF0n4CCs1+BnepQPJ1kFbPK\n35wQRi0RDeTf/GQ+/owEVCU9a9W1P/VUXk8Z0vMoQxCXEdRqnB63SgsKl7DB9G/C\n4SYrgGor+OHVGl4ntMZhJujiM996DttrNK3iZRGkQ07L+lfUIwQ52XOhQNRdic4p\nB03lw7PpChwPGMv/EEvdR5HpCJQBJniqJbbu3Jh8bMBKTE/8fCzN3vMXICB2g3Bq\nlKkZW6fnJRGsrZ79fsQnl+WBPNSrWRLOxOfe1fyCFV1ljFB4nTH7uF3pC8ZRgJes\nkHIESHz3GJm28hn4+17ESMGHBCbs7L9FK2GY31cobU0VRntLxpSG+d9njbIAgMG1\nS7U+oKVFQhSVpdXNOaUNqhcQ3HkbQTLEP0k53A/lhLQb2+KPd8nntaELjwNyrmZg\nsVMgHj/zdlvrbguZjZFzUzDBFvkuv/5M58lNT/D1C6ufVp/R6eLsYI+nnk1ojAjz\nl7N6U8X5SXpD+Bm7+Kn1PH+bHl7cViCx8oXJXO2RhP+COXckw7BDZKtjItYHNG7M\npFwgYqWpvCu9LN6IN5a/eLqSI76dOOP3iYbaTH+NAgMBAAEwDQYJKoZIhvcNAQEL\nBQADggEBAGB0Vq0l6ndGTgNbZxSEFyBR3u3tiR3pWK81DYjsui7qBoO6P/BaGmf+\nraSwHPaBOwA9XNS8jcGLh5xdqY2p/m0dTS64xNjVL9nweWsG+FwVnPANo8C4nXdm\n9ajJ4cdg54stQK8qn1uh/xPcd23GKfYJazjYSwYmZ3pXXdzlGN9NxkeYJQxJ6B+5\npzAeVGiABI/e5URpxzz2UayRX7EE+vtpe3B84hzkLqsq0N39ZN6KLfaTyEBGLzqE\niLYeXQTV0XSRs8xVt+iyGlj7nPkv2DR0oCqRpWUFWeSBI//niDG5WxS3qg8kacSW\nfDSYhSN+IjrnIkwNtc8V9t7/GeQB5FE=\n-----END CERTIFICATE-----"},{"id":"richdocuments","categories":["integration","office"],"userDocs":"https://nextcloud.com/collaboraonline/","adminDocs":"https://nextcloud.com/collaboraonline/","developerDocs":"","issueTracker":"https://github.com/owncloud/richdocuments/issues","website":"","created":"2016-10-31T08:55:45.631429Z","lastModified":"2016-11-24T12:13:53.905352Z","releases":[{"version":"1.1.3","phpExtensions":[],"databases":[],"shellCommands":[],"phpVersionSpec":"*","platformVersionSpec":">=8.2.0 <9.3.0","minIntSize":32,"download":"https://github.com/owncloud/richdocuments/releases/download/1.1.3/richdocuments.tar.gz","created":"2016-10-31T09:03:40.389355Z","licenses":["agpl"],"lastModified":"2016-10-31T09:03:40.439510Z","isNightly":false,"rawPhpVersionSpec":"*","rawPlatformVersionSpec":">=8.2 <=9.2","signature":"s5giQeiU2zwV5X6FmxWXiG9LtNDeKBlFqK+hfvGNbGZ+nic77Y+AnXHodV4lb3Ko\n0C0ThFLuafaZRdp9rBIN2K/acCfCYKJewGuYErb7FlEl+P9J4OQbb9pva0htZJw6\niuG5eyeTufi5MKB4vuj4+jo9zhepOFAtZMa7o+ZCfJkt8vDBuq5AXxomEiZRtW+n\nf9PPUnq0z7DJVwINhHvvBZJlSLjkpJ6VIHAr+/ElWr8O/mDKq5S5ohbvpDcPqR7b\njnsBckFDLFUz1FX9dA0JCJEKMMfkcfGqZcjH17NdjKAxRW2soN5cEKluu5MkOhz9\nFEPKfshzbrfUIm5MaFGv6w==","translations":{}},{"version":"1.1.14","phpExtensions":[],"databases":[],"shellCommands":[],"phpVersionSpec":"*","platformVersionSpec":">=9.0.0 <12.0.0","minIntSize":32,"download":"https://github.com/owncloud/richdocuments/releases/download/1.1.14/richdocuments.tar.gz","created":"2016-11-24T12:10:13.337165Z","licenses":["agpl"],"lastModified":"2016-11-24T12:13:53.963638Z","isNightly":false,"rawPhpVersionSpec":"*","rawPlatformVersionSpec":">=9 <=11","signature":"prDGlfRPxqT6LP0BsAFPwGww7P4Bngha2N4u5B6+F02N+RVOjGtTcXKqvM1KjZb1\nCo7qJvgJmjpvIvDmB+rup02i8ObfwP2ct6UdsD7ouzOWJG2sJANXK31bHyvOmQ2h\nvKu5eNcOkf+WFyFKYi51TbsfWn2+1Wge3WWujKAVcEvqtcOOz+uMWNtqzBptEupk\nE1aaRnQfTx488YB8Ubul06LIY0PNCHgGCWPgy817tOVT7JA+V0P0FFonl/PXE0dr\nWgtxRJmvGaNiFzYq+kQmdKMfayZTm3kdVgP0W52t5wp878K0i4s2KPg5lANvjTz7\nDCT+VV2IGIE52o4RpMUGyQ==","translations":{}}],"screenshots":[{"url":"https://nextcloud.com/wp-content/themes/next/assets/img/features/collabora-document.png"},{"url":"https://nextcloud.com/wp-content/themes/next/assets/img/features/collabora-app.png"},{"url":"https://nextcloud.com/wp-content/themes/next/assets/img/features/collabora-presentation.png"},{"url":"https://nextcloud.com/wp-content/themes/next/assets/img/features/collabora-spreadsheet.png"}],"translations":{"en":{"name":"Collabora Online","summary":"Edit office documents directly in your browser.","description":"Collabora Online allows you to to work with all kinds of office documents directly in your browser. This application requires Collabora Cloudsuite to be installed on one of your servers, please read the documentation to learn more about that."}},"isFeatured":false,"authors":[{"name":"Collabora Productivity based on work of Frank Karlitschek, Victor Dubiniuk","mail":"","homepage":""}],"ratingRecent":0.5,"ratingOverall":0.5,"ratingNumRecent":0,"ratingNumOverall":0,"certificate":"-----BEGIN CERTIFICATE-----\nMIIDCDCCAfACAhAZMA0GCSqGSIb3DQEBCwUAMHsxCzAJBgNVBAYTAkRFMRswGQYD\nVQQIDBJCYWRlbi1XdWVydHRlbWJlcmcxFzAVBgNVBAoMDk5leHRjbG91ZCBHbWJI\nMTYwNAYDVQQDDC1OZXh0Y2xvdWQgQ29kZSBTaWduaW5nIEludGVybWVkaWF0ZSBB\ndXRob3JpdHkwHhcNMTYxMDMxMDg1NDExWhcNMjcwMjA2MDg1NDExWjAYMRYwFAYD\nVQQDEw1yaWNoZG9jdW1lbnRzMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKC\nAQEA1jk29m6JykcJ2Ld0YEpjPMYh6kwxY6GysNJnfkA/th7tPWL3+vBJ9oTYyVnZ\njwAE1Cqwfa9MyBKMZ2IdfIqtT8PeWzuFP7Ib942EdxUpwwh9F3lykeGsj0h4zQwX\nF9OooiS99PfLX+JpkKm15Ujb00iLB6xQmq0+3NeOT1CTD1ziJ1ueOcxBKMwaFp2a\nPuz3F5ywqCvpmxG/OBuOs0LI3/zStXhBNbUMxBrWblr7zaVNJXl/I2JCKj8Wah/H\nXUEEGbW15fAUP1f+90eQSxpEoCZDBHXOQCTJYzySGv+BjU+qlI9/gS0QbrsiyzUf\nO5lyvi8LvUZBzpBw+yg1U75rqQIDAQABMA0GCSqGSIb3DQEBCwUAA4IBAQA9jU3m\nZmD0ywO3MUsG/GLigFtcWi/p7zp2BliR+NpuY2qNFYDcsIb8ZUudmUc/cJRRctzy\nAPaLLj/d+h5RFaxjTVvim1PSe6M7urK/IMSvyUVYCeQRYpG8ZJixKTCOVIBaWHMz\nxTfc51tm9EPlpJpK6JtaWrYYoWGE3k9sINdJ4JkvKkE2CBAqVhX6ZGyEQ0bnEhtk\nRu1DXn+LW7TJ4NZ8VtLWvmW/6Kfmi7dQ1V++Kmn0lO5ntRt5altePbStCHC8bhGp\nmyBOrjhrJgLIwvgH26MYZhdiSkFzoE38nMPZdrUmUDxcPCwucWJqgzDPudguFthj\nWCVZ3TTG/2z3+tWM\n-----END CERTIFICATE-----"},{"id":"ocr","categories":["files","tools"],"userDocs":"https://janis91.github.io/ocr/","adminDocs":"https://github.com/janis91/ocr/wiki","developerDocs":"https://github.com/janis91/ocr/wiki","issueTracker":"https://github.com/janis91/ocr/issues","website":"https://janis91.github.io/ocr/","created":"2016-09-19T12:07:49.220376Z","lastModified":"2016-11-21T11:22:21.024501Z","releases":[{"version":"1.0.0","phpExtensions":[],"databases":[{"id":"pgsql","versionSpec":"*","rawVersionSpec":"*"},{"id":"mysql","versionSpec":"*","rawVersionSpec":"*"},{"id":"sqlite","versionSpec":"*","rawVersionSpec":"*"}],"shellCommands":["ocrmypdf","tesseract"],"phpVersionSpec":">=5.6.0 <8.0.0","platformVersionSpec":">=10.0.0 <12.0.0","minIntSize":32,"download":"https://github.com/janis91/ocr/releases/download/v1.0.0/ocr.tar.gz","created":"2016-10-24T06:50:43.283900Z","licenses":["agpl"],"lastModified":"2016-11-21T11:22:21.269108Z","isNightly":false,"rawPhpVersionSpec":">=5.6 <=7","rawPlatformVersionSpec":">=10 <=11","signature":"CBJkCIiUKyf2NuWfz2zJ3grhf8p7wJes7DPV/OxUzhlxIH0Fh7K54+U5A9JOOi6f\nWPhjXG1ylkyIVY1glr/B8svWNsD4jAclpnUi1/9ZW5UPT8LnRBfTbtF9Uoj0OgNs\ntsGQYbpuREoHnjbJWTRe0kq1OsOfX44xuf8PuX43B+lpQPW4iRSSz3ZIhdPcDGq1\n7pyqQM7gdKhBQ6/tOiwd7Enyt5Hi4V6jhwhUOCYeTNiLD2V3yKL+qA9DzpXUfNNw\nLGTjcaMrifibHQIZBZWbPPMmCfMJZ7GO9oR4gWHwkhWqt0yVWAJXAHJBLd5vXC5I\njtRTXRpHO/k6Dtqem8tZCVoDE5MAC7fDZ/0XzoFiXHciP6MenVasVcXo6xJOJc5y\nGsrecNftUEhP/ngxA6lMBVkLmmdpiexVisvsavPi64i34OUA6qOuxjgNVBDwg56i\n2lOEVvHa3nn0UX7ZZoQ/Nu6Mz7J3Hx/VDlttPuWe42eeJAphyDGubT1M62gW8dVB\nD3tJOF7spnK6I3BhVLviou/zs30AIRVBDTU0Orzx78cbInwy6/vyJib2a1olAaHz\nv05SzlQRnBWM4jYBe0mA/2ds9AO6VrXGrT/iLlHemj6JYoGBM185TGewA7OJyX3a\nHSlSDqaremmi+aS3onx3AKhXykDxTRkMVarePwTzzFs=","translations":{}},{"version":"0.8.8","phpExtensions":[],"databases":[{"id":"pgsql","versionSpec":"*","rawVersionSpec":"*"},{"id":"mysql","versionSpec":"*","rawVersionSpec":"*"},{"id":"sqlite","versionSpec":"*","rawVersionSpec":"*"}],"shellCommands":["ocrmypdf","tesseract"],"phpVersionSpec":">=5.6.0 <8.0.0","platformVersionSpec":">=10.0.0 <12.0.0","minIntSize":32,"download":"https://github.com/janis91/ocr/releases/download/v0.8.8-beta/ocr-0.8.8-beta.tar.gz","created":"2016-10-10T18:01:16.076330Z","licenses":["agpl"],"lastModified":"2016-10-10T18:01:16.169733Z","isNightly":false,"rawPhpVersionSpec":">=5.6 <=7","rawPlatformVersionSpec":">=10 <=11","signature":"uEvhHfQCrzb6z+QuOoO8rYXiMsZFkrFWEqDvTyOTSgFKvo7dVoj3EfDfaApgcKEB\nIM/SqjLSO0lNhrp8F2mST3twbvLDprKsfrDWKFE6eiH0yKl2aNB+cHWE27utARaX\n/QZBD114vbWeDnbaBa4b9OwtBXDqKJrnO1LmqSLFP8guAlVTkU1jSPkRTpmwAcAZ\nJA/aiN/D2LSGfiNp/YdeTuzU+gPINIs9dCb6+PPkyam8PCBaXUSSaW+c0lAQHln+\ntb3EXxZ5YXdjPWrpEyHvFLk1N8s/w615QoMxr5fEs1M8D29aGbcL/wu7LXH4X0Yn\noiWwIFbpfrpJQlrIFumxWZR74JXiNr9J7ijnQ7SjxdHCcrLxMdnZ2cwq4iD6PnYm\nnIojhlhPOqUIzsWYCYutLWDQbUQz9eyWbj/+7XL+5KjetUUr/MnCu6xJ27IqFbAX\nHc8KRCO+9I0/qMQ2/rCZXBMeo39MGhhkgkVl5YAKwC1IEN/jlfyVNXZwYlfcHLKj\n6aNQ4zN6gGOerWWZ8qXtOeNJN+qv0nmXUKrZdnZUAhxOdB4G9Ym+JujxJZ9yNIWV\nsiqAI9J+OIzCwv/dzZhaHadONoo/RTF+Fl6Hy56HyBtMehb8w9p8ksVediqf33yt\nFAE/tzKtNK5NiRd+8MZkq/GbocaFUv3C7Y6pLMpTE1c=","translations":{}}],"screenshots":[{"url":"https://raw.githubusercontent.com/janis91/ocr/master/screenshots/sc1.png"},{"url":"https://raw.githubusercontent.com/janis91/ocr/master/screenshots/sc2.png"},{"url":"https://raw.githubusercontent.com/janis91/ocr/master/screenshots/sc3.png"}],"translations":{"en":{"name":"OCR","summary":"Character recoginition for your images and pdf files.","description":"# Description\n\nNextcloud OCR (optical character recoginition) processing for images and PDF with tesseract-ocr and OCRmyPDF brings OCR capability to your Nextcloud 10.\nThe app uses tesseract-ocr, OCRmyPDF and a php internal message queueing service in order to process images (png, jpeg, tiff) and PDF (currently not all PDF-types are supported, for more information see [here](https://github.com/jbarlow83/OCRmyPDF)) asynchronously and save the output file to the same folder in nextcloud, so you are able to search in it.\nThe source data won&#39;t get lost. Instead:\n - in case of a PDF a copy will be saved with an extra layer of the processed text, so that you are able to search in it.\n - in case of a image the result of the OCR processing will be saved in a .txt file next to the image (same folder).\n\n**One big feature is the asynchronous ocr processing brought by the internal php message queueing system (Semaphore functions), which supports workers to handle tasks asynchronous from the rest of nextcloud.**\n\n## Prerequisites, Requirements and Dependencies\nThe OCR app has some prerequisites:\n - **[Nextcloud 10](https://nextcloud.com/)** or higher\n - **Linux** server as environment. (tested with Debian 8, Raspbian and Ubuntu 14.04 (Trusty))\n - **[OCRmyPDF](https://github.com/jbarlow83/OCRmyPDF)** &gt;v2.x (tested with v4.1.3 (v4 is recommended))\n - **[tesseract-ocr](https://github.com/tesseract-ocr/tesseract)** &gt;v3.02.02 with corresponding language files (e.g. tesseract-ocr-eng)\n\nFor further information see the homepage or the appropriate documentation."},"de":{"name":"OCR","summary":"Schrifterkennung für Bilder (mit Text) und PDF Dateien.","description":"# Beschreibung\n\nOCR (Automatische Texterkennung) für Bilder (mit Text) und PDF Dateien mithilfe von tesseract-ocr und OCRmyPDF ermöglicht Ihnen automatische Schrifterkennung direkt in Ihrer Nextcloud 10.\nDie App nutzt Tesseract-ocr, OCRmyPDF und den internen Message Queueing Service von PHP, um so asynchron (im Hintegrund) Bilder (PNG, JPEG, TIFF) und PDFs (aktuell werden nicht alle Typen unterstützt, näheres [hier](https://github.com/jbarlow83/OCRmyPDF)) zu verarbeiten. Das Ergebnis, welches jetzt durchsuchbar, kopierbar und ähnliches ist, wird anschließend im selben Ordner gespeichert, wie die Ursprungsdatei.\nDie Ursuprungsdatei geht dabei nicht verloren:\n - im Falle einer PDF wird eine Kopie mit einer zusätzlichen Textebene gespeichert, damit sie durchsuchbar und kopierbar wird.\n - im Falle eines Bildes wird das Resultat in einer txt-Datei gespeichert.\n\n**Ein großer Vorteil ist, dass das Ausführen und Verarbeiten asynchron im Hintergrund stattfindet. Dies geschieht mithilfe der PHP internernen Unterstützung einer Message Queue (Semaphore Funktionen). Die Aufgaben werden somit getrennt von der Nextcloud in einem eigenen Arbeits-Prozess (Worker) abgearbeitet.**\n\n## Anforderungen und Abhängigkeiten\nFür die OCR App müssen folgende Anforderungen erfüllt sein:\n - **[Nextcloud 10](https://nextcloud.com/)** oder höher\n - **Linux** server als Betriebssystem. (getestet mit Debian 8, Raspbian und Ubuntu 14.04 (Trusty))\n - **[OCRmyPDF](https://github.com/jbarlow83/OCRmyPDF)** &gt;v2.x (getestet mit v4.1.3 (v4 empfohlen))\n - **[tesseract-ocr](https://github.com/tesseract-ocr/tesseract)** &gt;v3.02.02 mit den dazugehörigen Übersetzungs- und Sprachdateien (z. B. tesseract-ocr-deu)\n\nFür weiter Informationen besuchen Sie die Homepage oder lesen Sie die zutreffende Dokumentation."}},"isFeatured":false,"authors":[{"name":"Janis Koehr","mail":"","homepage":""}],"ratingRecent":0.5,"ratingOverall":0.5,"ratingNumRecent":0,"ratingNumOverall":0,"certificate":"-----BEGIN CERTIFICATE-----\nMIID/jCCAuYCAhAKMA0GCSqGSIb3DQEBCwUAMHsxCzAJBgNVBAYTAkRFMRswGQYD\nVQQIDBJCYWRlbi1XdWVydHRlbWJlcmcxFzAVBgNVBAoMDk5leHRjbG91ZCBHbWJI\nMTYwNAYDVQQDDC1OZXh0Y2xvdWQgQ29kZSBTaWduaW5nIEludGVybWVkaWF0ZSBB\ndXRob3JpdHkwHhcNMTYwOTE5MTEzNTAxWhcNMjYxMjI2MTEzNTAxWjAOMQwwCgYD\nVQQDDANvY3IwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDDpXiwec4f\nXAT//7YBPSb4z6ZsBJSMfBq0VTL/HagjJnQ7BL+WagzWlS69IStNDqlIlenamYRX\n4B40heJIUinzYKjTRbr5UAw6MX29HibZccm/qgrk36o1XTgIsoRhmvSxbXDVIo1k\nbDOJN8gc2Gvswa8X+uOe9pfcDgAdqGxOvFnoKW89GnB01pCNT+xakNErGAFqVLsr\n2AeademAZnbxJ1cB54tQn2Bygb/7DKKY8EmFfIq6/27n9Jbph1FG9HIlWRT4/M2H\nU2pG3cCScWMEBPsW7kpfpnzLk7Q30Oj6k/rEYjJgmNYgg6oVnn0D9uRmhBYBnGyx\nMab1ilsK53lyuzQY0pmU8V5ULqpnNFAK6DVFfofEamDUhBPO+TZXEA5cZmuULRpf\nQQXmGpUQSyV6pS9WirMIqXFp9wmQ4vtjMdhu/6CP7cmtYZdq9uOhWEHbQM0mZUkb\n8hMjeItPx9XITI7Cge1JUOI8ZIwiB3USnQXcMd3v82l++/VgqHB7s5OaKPhygsWI\nM6RCoBcGiuQB5/fEUOg5ACOpGVyJiBda0Mi57AdoxdJmfnr7Bxcf2tAWIJL9Y7T3\nE1+V2BMxJOWwvVz26Cq83F41yXK2hJS+SbfQTqNUR8Cfh50CS9POvgRxNrJK9yvI\nkKle3ITRtGVM1XU0njWjnsdGg3D3O2mmjQIDAQABMA0GCSqGSIb3DQEBCwUAA4IB\nAQAbFddMbgfPI1szT57V1FKZrOrdYqQ7qjewlIQOzshGydbMtqS/9XL5hYocJCMt\nY6w+C/i6iEzO2Jx8D/k4rcZMXoVR6y3ZvO0Ke0gzSRsU+5eYj2FK1VV+cNIQW5Iu\nCYYIVa7pVPVHdeQH2Bba680bLV0HMF6b1fI9IwkfdCAinvCYZLjyEXZlmB7YjyA8\nHR7qPCNz4uG2Va7mlUHE3UYUYnlv8JFOV3YdbVL0nxhWwIdzSri5sxFIhdlabpzY\nyA1z/MCBEyTRo80jxFmL+MpwbsdbUJi7Qxlnd56zb6HHDGrLHXZTh9LXgyVbnhWL\nkxomWjIXQh4aMHQL4QF7U4EK\n-----END CERTIFICATE-----"},{"id":"spreedme","categories":["tools"],"userDocs":"https://github.com/strukturag/nextcloud-spreedme/blob/master/README.md","adminDocs":"https://github.com/strukturag/nextcloud-spreedme/blob/master/README.md","developerDocs":"","issueTracker":"https://github.com/strukturag/nextcloud-spreedme/issues","website":"","created":"2016-09-27T08:43:07.835196Z","lastModified":"2016-11-21T16:51:23.703819Z","releases":[{"version":"0.3.4","phpExtensions":[],"databases":[],"shellCommands":[],"phpVersionSpec":"*","platformVersionSpec":">=9.0.0 <12.0.0","minIntSize":32,"download":"https://apps.owncloud.com/CONTENT/content-files/174436-spreedme.tar.gz","created":"2016-11-21T16:51:23.689599Z","licenses":["agpl"],"lastModified":"2016-11-21T16:51:23.826509Z","isNightly":false,"rawPhpVersionSpec":"*","rawPlatformVersionSpec":">=9 <=11","signature":"Mhy3hXeGWlIujx1Op39MMRdqHYOo360BCwr4FPWoTNNggH3aS0gWlh48DAfGYK9W\netNiOqIuRyA0NrVlsqR2vDILgFtODJSbKPyHd3PQn3hcGsjogjQ+dkKciLNLinw7\nOhbv6aDdRFLBeRHpX/7wOnWL5W3ko/gyn0Awvi88M9+nC5aARtqncQqPy2SxDGzH\nKlOZHSNDnEQCGMhA8hNWWKdVwNUJHod/wmBWpW5QVNSJq5DqrKZcNwpGM2UUJoql\nEqUMwDXk5uVH5r5k62Tr9kguDWoUEG1OqQSyeMY24AmA64tq/HSlAdZ+CX32bc4E\nZvm+n8poJBrdSVmWEaa4ZfYaLFdOc6Kcuid1B1Sv9kPhD9WD6T1sicdzjDzcorBK\n/MLReCuSb2E8aPTnFWRoAZ4xCUGs1IXzX5fmxI8VdzwR42R6RhGJ/rqMuZRFenZF\nbOks45K5gE1da4QpkYOUQa3GVMNPqPiT3CqjmJ8tjxq7bGpb6v+YoCLACjjPpPZL\n2Y28qLxwHVaINDFUUxD75WWdrlulRbqHwiSw8jolP9qrpXhDuLAqYam9tRwV5K5R\n8uNawnFwWkicBEYkN/WtBTouWzehOPn38tHXov6SyEyD6lkuxUBZrsGQ2ru+t33U\nk0kKCbV0GFw43I+3Ji5DiB4TUVNZYVoPG1B7Qve+UfA=","translations":{}},{"version":"0.3.3","phpExtensions":[],"databases":[],"shellCommands":[],"phpVersionSpec":"*","platformVersionSpec":">=9.0.0 <11.0.0","minIntSize":32,"download":"https://apps.owncloud.com/CONTENT/content-files/174436-spreedme.tar.gz","created":"2016-10-20T09:09:26.520692Z","licenses":["agpl"],"lastModified":"2016-10-20T09:09:26.666738Z","isNightly":false,"rawPhpVersionSpec":"*","rawPlatformVersionSpec":">=9 <=10","signature":"D62Ck7JUnrYbrfFlX7xXVaYUMZIh2acmykIKapqfemD/tuX5Bvb08GYGTeFG61MA\nQzsqcIylDfGnC1UJbf8yWEX7PbyJD5w/R4WlbFv34njDvM8rBs4HpzSjkqQoykOF\nZpYAjH2ydfKqtZadgoIRm7et5B8X2AeoGg11ec52DId5t1wAEBcDIv824CDBUt8t\n0pVY8Z8n1MUYwU7DCjCbPy23br2+EBODFCHp+cFfMBLg3F0BJI5nY3Q8ku+0tqMR\n0NDxQcscNZ2Ck/wpVDWylfhpS+ICIxSMiyq7urP593mRrK3399SUyaMqDfgl/pxo\nqTzdBxHLaAqcnKZYglbqp+Gxbyj4teqCod8TiSMlp90VaxhC72ACuVQQRWQKuTNI\nZeW3YweWB5d7VErqBNmQR1tGnX5YFFHiKo41fVDQFsrOqHx4zP6AeU3nkl2ol/r/\n3pg553so1MOxMkyLEhGYGMfrdQqVEtajNWHUdj3B73LS+M3jcjBFIdOD+AGXPtDX\njCRymt07c1znhkL+aT8yY5SHMVbKBZj9mExL49hcLjAYYc4U++60uq9MFH5r9g4T\ndph+yT6VVEM/UH2HjvKsHv2wm937sNgG3EXQdh79JU8nCXIz7cVrJ8f5/9r6n1VP\nBbjtfDAPEjmfVCXX2gmgLuZHV+GMhLBS9bTh+61AhhE=","translations":{}},{"version":"0.3.2","phpExtensions":[],"databases":[],"shellCommands":[],"phpVersionSpec":"*","platformVersionSpec":">=9.0.0 <11.0.0","minIntSize":32,"download":"https://apps.owncloud.com/CONTENT/content-files/174436-spreedme.tar.gz","created":"2016-10-06T08:14:05.212553Z","licenses":["agpl"],"lastModified":"2016-10-06T08:14:05.278533Z","isNightly":false,"rawPhpVersionSpec":"*","rawPlatformVersionSpec":">=9 <=10","signature":"X9zXDyMBPoXPMpZ+XXWK3MLufjY2MG8lJ+93LiW3rv0iq9yd8PafK4IvP9czO6o9\nf/vNilq+1mfl6mjTvL6QF5+sySlzbRGbT3uTBwYXyYL07HVYgl1ZLrwe0kxvxqaW\nxTvPem7+HzwClI3VnWc7ylQfzGrcYIaSIg7nNq1GOHocsgZVNyj/nVW/eQx24MjZ\nuLzZs9SJqYoBGq+mo63vRswhqv5OzGebo+G6dHm0hvRSOw9qsWCDWBugiSRU8zU4\nD9PQ0e8WbyrIrQhBoUvvkuijO3zCySx606S1HUyaHmbJzMc4Fbpwz6ggmi6IRBbT\nFBKB1DWJDwN/7mY4fhS4KhircVnAHDqiBVCTu5i3pSfMPrwFymcmbn9OBuFHAFuZ\nd9PZvWQg4v32w+Q/NNvZVW5lRi+l0w5DEqNREaj79hljk2reZMaB65lvtV9NCYw+\nHmwWqsGqZ1SgGZuhYkOzEIkCfJ2fF/VpyavJ4X6bHP9yYdkt1pxnSSoZ2HC8mkG4\nBnPf28mEXRcY8EJv0rEePqKSBIhAt8yfEW+joH/8nupe1qOdfPvP08ifLad5m76s\nt23UzlSljzq9kVO+d16z2uagKomN9USZaNnJcUDVblfjvCPpdiHLfRPEJnRsDZCm\nNffFWEMcz+TWmwBboZgTRO9v0bPDEuwfCCEW0zy8rT0=","translations":{}}],"screenshots":[{"url":"https://raw.githubusercontent.com/strukturag/nextcloud-spreedme/master/screenshots/appstore/conference.gif"},{"url":"https://raw.githubusercontent.com/strukturag/nextcloud-spreedme/master/screenshots/appstore/presentation.png"},{"url":"https://raw.githubusercontent.com/strukturag/nextcloud-spreedme/master/screenshots/appstore/import.png"},{"url":"https://raw.githubusercontent.com/strukturag/nextcloud-spreedme/master/screenshots/appstore/users.png"}],"translations":{"en":{"name":"Spreed.ME","summary":"Audio-, video- and text chat for your Nextcloud","description":"Securely communicate with your friends and family using rich audio-, video- and text chat, and much more right from your Nextcloud – in your browser"}},"isFeatured":false,"authors":[{"name":"struktur AG","mail":"","homepage":""}],"ratingRecent":0.5,"ratingOverall":0.5,"ratingNumRecent":0,"ratingNumOverall":0,"certificate":"-----BEGIN CERTIFICATE-----\r\nMIIEAzCCAusCAhANMA0GCSqGSIb3DQEBCwUAMHsxCzAJBgNVBAYTAkRFMRswGQYD\r\nVQQIDBJCYWRlbi1XdWVydHRlbWJlcmcxFzAVBgNVBAoMDk5leHRjbG91ZCBHbWJI\r\nMTYwNAYDVQQDDC1OZXh0Y2xvdWQgQ29kZSBTaWduaW5nIEludGVybWVkaWF0ZSBB\r\ndXRob3JpdHkwHhcNMTYwOTI2MTYxNzMzWhcNMjcwMTAyMTYxNzMzWjATMREwDwYD\r\nVQQDEwhzcHJlZWRtZTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAKLx\r\n2dCPBLIgX948BnOdLij0YyI2+FKD6uZOvzxMaoi3rlxNf8MJgraNMzTBWEXtxT5b\r\n7ZISNp89WEXhaQ1dwwCocodd/xow4Ek63m5nUvTZXsm+YSbMgrFbxzsBhYU7KuIE\r\nT/jhKdzYgemzErwwN/gtwkLMfPo3jkgg6c8NPPohYv6k7V4VnsqtJ0JS0kX19FqM\r\nMiNz9XkcncBHy9x0BSxy4+YnwbFcgIx/MtYKlBL8NkPuuJaB/6C1O+IPYhdEdnpX\r\n+RaIue71nSStOYOqT4YDqHAIw7EmqgA1my09mmK+0Pn92GJVEAEN7JGBSQ+F32RI\r\ndB3ivGAOVtUtVvJlepWdbHxj1xqeP+LCjWzHMLQjm0TyH8VqU4Cg/wxwAEFnBATH\r\naOaWwrggzY2d9KBo1mp0k71NArLbBdlHykFU4bgiSDWrXXMz0fZzLQVwGI0Eqcxc\r\nouf6t0kvrK8oKjrnso+FjBoT7lHV/H6ny4ufxIEDAJ/FEBV/gMizt5fDZ+DvmMw4\r\nq+a088/lXoiI/vWPoGfOa77H5BQOt3y70Pmwv2uVYp46dtU8oat+ZvyW9iMmgP1h\r\nJSEHj1WGGGlp45d10l4OghwfTB0OSuPUYwWR+lZnV8sukGvQzC9iRV1DGl/rREMC\r\ncQ5ajRAtO5NPnThvN5/Zuh4n8JoDc0GK4jEZsIivAgMBAAEwDQYJKoZIhvcNAQEL\r\nBQADggEBAGHMRbPV0WTI9r1w6m2iJRrMbZtbBb+mQr8NtOoXQwvSXWT1lXMP2N8u\r\nLQ1a8U5UaUjeg7TnoUWTEOqU05HpwA8GZtdWZqPPQpe691kMNvfqF64g0le2kzOL\r\nhuMP9kpDGzSD8pEKf1ihxvEWNUBmwewrZTC3+b4gM+MJ3BBCfb5SCzMURLirfFST\r\naxCNzc7veb2M98hS73w5ZE6vO+C/wz0GTsxuK0AoLitApT5naQnjvxSvSsjFPEGD\r\nsUNUEU2Decyp0jxLVnrrpz6Y5UupfBR0V8yAv1t5Od/mCKLc5DxHsDWiKOpsob9U\r\nJN+bdzJil2NNftihD4Dm7Ha7OS3O8W0=\r\n-----END CERTIFICATE-----"},{"id":"nextant","categories":["files","tools"],"userDocs":"","adminDocs":"https://github.com/nextcloud/nextant/wiki","developerDocs":"","issueTracker":"https://github.com/nextcloud/nextant/issues","website":"https://github.com/nextcloud/nextant/wiki","created":"2016-09-14T14:34:35.977699Z","lastModified":"2016-11-22T16:02:57.758477Z","releases":[{"version":"0.6.6","phpExtensions":[],"databases":[],"shellCommands":[],"phpVersionSpec":"*","platformVersionSpec":">=9.0.0 <12.0.0","minIntSize":32,"download":"https://github.com/nextcloud/nextant/releases/download/v0.6.6/nextant-0.6.6.tar.gz","created":"2016-11-16T15:11:14.344704Z","licenses":["agpl"],"lastModified":"2016-11-16T20:39:59.030384Z","isNightly":false,"rawPhpVersionSpec":"*","rawPlatformVersionSpec":">=9 <=11","signature":"aOZeEeThyZ0V/vXBcn6c+Z0vyCsZcN6nfSJ8oWEea4zXh4g705Si+MFZESqix3M2\nOPCnA/U8eASwdRTAEwQJrW5ECmu1THXSIsrzQzc9kFycvyOGzCgAWtuu0ayzZD2/\nU5aDWlzpLHC1Czg9QJ5UnfZR0AfChWQ402N1YzGqMShdJv6AHXFrVE+uYnIyxuYI\noPJQBUYbQwthVUjpYwFwSxw50YU17gmx5RZ0Y0OPz3i/EiuEUrxopXtfDVYAuCML\npDw37LOTRQ2JqxSU3teALh8LcrwJbTeOP0n4bTeV+vU3jvtiaEoRrwfVrK41F701\nQymGXy1/EFG0kxPGS2dRNPBAXYLZfeoWlROl3D5BWlbsCcXKU1S+22yn0TEdS7x1\nY44x8jRKnBddDE7qkn+QoQYHNNcxOREsFFLmIoyCUpdNOdDX2PvTFUYkIqdnXaJy\noAKv2GkvWPQ0aiiBtA1i4oXuzvHW/M2wOrK7v7DCpNfILrD/sjxpljxcX082nRCd\n9P3iPd2hQ6yOM9fG21LVN74b6wggI81BzFf/xJPd4ZqYLjfeG/yqd0zaiMOzMm1W\nse+kc/a4iB3BoCNX3E942pBBzew4ya8LkCXdCHUUsuelDf1va1ikTh/G7D84ll9/\n2avNqQnUh3hgOnxFCLI/5VrbqxfSTVdO6O/LTuAmwgw=","translations":{}},{"version":"0.6.5","phpExtensions":[],"databases":[],"shellCommands":[],"phpVersionSpec":"*","platformVersionSpec":">=9.0.0 <12.0.0","minIntSize":32,"download":"https://github.com/nextcloud/nextant/releases/download/v0.6.5/nextant-0.6.5.tar.gz","created":"2016-11-09T16:58:06.856332Z","licenses":["agpl"],"lastModified":"2016-11-09T16:58:07.139404Z","isNightly":false,"rawPhpVersionSpec":"*","rawPlatformVersionSpec":">=9 <=11","signature":"DVOIbLEVggiLkNkuPW+pXqu8WYT15unUsMoqHSw81NiU6HF0Nuf3XiwnHJJDDqo5\nyX+QyHADO4ZiQpvXhGigvwD2eS1jVLatAztyxE0tEQv5eBU/7R0jQYxI8YCnC/jE\nZDa0qs+TI58EkDek0LBzueVQqrLubKgGU9P+E9H8gbWi1JHvl/2LdY7CplPqaJ+J\nMRokobPntzgx9m4DZC1RsCoXzSON7o2gp2cmunPJiXVHPhMUfIfolGEbNGJ1/xdp\nra7Y7XkPnDx4po98a38UpUh1x/2m5goOV54em35bWbh4ShNDykiE5ttz6tOywlYN\ngxceSsStTKyqscVaOV2Xu6Ive0pY9CInvrSfRnRktIWBYDyWdbK9sJuqs/s69kqn\nKQ/SjzE2smw0zwOUMnSaz0Jzr1vdPFgNu2xDYAVQO5G03V+wQ5AhxuhBz5Xp5Fll\nLaOhymZLCC7lq0DUqkeTeQ2QCfiG23hvG2VUPsIqW7xFe2YzKHZVXi9JuH//Gwym\nDmJmcyZDMvNwNiObx3ZRKsZNH2XwbldFZ9nTpb9AafyoSR/qbwd473NewaDLRTiY\nLrOP5Wx1xx6DOkRmDF2l2iT1bSJ6eoAoWQU2I0aYRH9NAr2Ugd4f2Um4o61EJaL+\nRHT9cERRySEloU/NdgmZEOi+CG0rEu+9LC5G/jGlHE8=","translations":{}},{"version":"0.6.4","phpExtensions":[],"databases":[],"shellCommands":[],"phpVersionSpec":"*","platformVersionSpec":">=9.0.0 <12.0.0","minIntSize":32,"download":"https://github.com/nextcloud/nextant/releases/download/v0.6.4/nextant-0.6.4.tar.gz","created":"2016-11-05T18:17:47.622023Z","licenses":["agpl"],"lastModified":"2016-11-05T18:17:47.678445Z","isNightly":false,"rawPhpVersionSpec":"*","rawPlatformVersionSpec":">=9 <=11","signature":"RdkvnhNjw+kAnT6Or3+N9FzAv9DjJ9BAlmgANMwZZcaqo1gZRFewsGD2Rx1KEb9X\numSC28tl2B5/3r/+dprVJmOnYJny/7+kDmI/d+vigKfnaQJOUZ0ya5+f72pFgow7\nth8fw9rX/3+zIBs2IeEN66cis8ioFq97BJDsnDMBDr7wl7CnFJjYe6eviWuiFTnC\n4sBXlYjHoaIRRu561nwAooV+WXmWsparYPVhj2cXdyP/CnWo5HSF5jA51WCsz7Up\n7a0URXdh85xmxEbZtnjUymTW2BIegdxj9Erbfiuy/m3ApgnP+DiEQRcM13J7pXqg\n4cgFOBSzKDZgim599WBW2uNO1ztnDYOzz47GXDfJhcdvKiZZoQpUF9W4LMRtheMz\nxD9YArO3j3d+VOInSYU2Rpvhugwo1LExhwnRdT4+cOZfEeq0VojiM7yBZLDdEjIb\nGdYUJtNWSU0F6cPab2Au8FgZymLrHL9EpGvxuA1oAwtRxHAgMElJG2O6Jp89gGl9\nh/AptypeTvzNEc9/Kg24ueBKqmSUd5a45pZ3gM2pNATJhUK7fzLb/K6cq/kEzZtj\nOPra1ZfP0/20u8VP32Rgw1cFmIjqt8DFzUmOMpMfyoJkdldtTwQtGk+yIvtN1zp6\nT2zDknAKA2N/rZ/0SJl8KxVVNLhQWtYBJ+rFAdapuxI=","translations":{}},{"version":"0.6.3","phpExtensions":[],"databases":[],"shellCommands":[],"phpVersionSpec":"*","platformVersionSpec":">=9.0.0 <12.0.0","minIntSize":32,"download":"https://github.com/nextcloud/nextant/releases/download/v0.6.3/nextant-0.6.3.tar.gz","created":"2016-11-03T21:51:27.654342Z","licenses":["agpl"],"lastModified":"2016-11-04T18:25:35.697130Z","isNightly":false,"rawPhpVersionSpec":"*","rawPlatformVersionSpec":">=9 <=11","signature":"Hf5GB4xd+rVXzWvVpGbbF5tqmnI+DGHlNHdLYPImFLS/Z4K5wKeNp80E5sd/RkAi\nhyuEsdWHlGDVMT6s7oeCmH/ClyWqLNSz9VH4KYqyFgD4+usHZp9PrEeEKbvPDPKv\nD3eB7Ats34cWcpf4E1oR5wsPicgmdgIgb2uMXzc/1G9xUBRWzocwCstzjEEAB/VJ\nvJuHvhDTGG294P4gOb82MxKCQ8LZ4i1QXzOf/mLETOubiUbZtJgTReYvpdAo2Wct\nbdfDFw13LYZkCf71r9jIQ3PSPlIpD+0BwAlE1fi0Br9dP2JjIfiKN6CGVaki6O0v\nKR42jtcE9xXiAop0Ym1FYMWJvQUy5PFLMwYDfEd6CvfEFJl+fi+RjXNDNZcTyw00\nHa48sACoGzxwts2JknWMU57mwvi0Z4uwpE0cFp/PRzBsXmSlCzWHjJhu7+2qambE\nAabdP9nH2NvqJHUJyPsxtDSrSWCBY4CoL3wYu36UrIA4NepyudMPNe9fhKTEU0bg\n8DLclw6hYdj5p9Zj3OUuwOZLz6r85KwnooTsUjOYkBXvdUuHWkgONqqZlPMApS4i\nChRQ7ysHAinPyyzsvr0PR9g6J52CSCO/7qwSJy6yqSzuSWrbZUa4FVTcKIwWJJPu\nJ2XzB4rWVG1wWjzMM6MIvFbO2HY9upzh651OdOwsYvk=","translations":{}},{"version":"0.6.2","phpExtensions":[],"databases":[],"shellCommands":[],"phpVersionSpec":"*","platformVersionSpec":">=9.0.0 <12.0.0","minIntSize":32,"download":"https://github.com/nextcloud/nextant/releases/download/v0.6.2/nextant-0.6.2.tar.gz","created":"2016-11-01T11:24:58.054892Z","licenses":["agpl"],"lastModified":"2016-11-01T11:24:58.151609Z","isNightly":false,"rawPhpVersionSpec":"*","rawPlatformVersionSpec":">=9 <=11","signature":"h8KgwMh2RGGIp7q/II23VSfE5Ibkha7p/C1kvIfG6QIIc2Zu/Mm3Oekynnysh5ZJ\nZuMTaeWbejbBAmlnxW+AwBWa/s2PoMhv7foVvdtg76l9/qr+9jGvUM7D1LbbBvAy\n/XW6JSrhhBZHOohdU7kwV5Xnwsn/NC/zUe0G4eZ+9fc9uSntkob9wnWvUs2daAeD\nY6Mi7Xt/XAIX65OIVTKfC6ah1SlbXgtJ2i2j4G32I9jRhmbkpt/UJEangn90fHnY\nQXNJ85OyV0aNMafNHoMSL3uLscdvjp0Hy8w4iBeavsRlCs0GiUoG1+YdwTwmC9EM\n4CjbMfRJ0DYK7u697TOmS8MQzk8O7f5THtjeokZlrom2YnV9t6gLvjnxl/+gXPdJ\nmgLixnA8P6tPsff9pquHKQZsvxjv6vVa2DVJc8VpcqJRih7yj/3V7rxesEP7MUnP\nznIOcwzTsKXHuAnvujpCwyQj3QtpQK2XJPQ5WkKgwbTdvriVJfnzPironhcHo1vC\nbuUDOdhL59aySChw2cZGD9lCWaxYR7I1BDDzWKNl9Qg0AZ2auyGUGTv8P2vi5qUB\n0CmnkzkZurR5ju6Nb9/2lcZvda7QJdIdMtm2Wnn+Ak/Z3Y4IehB5PPDP5/MMAhQY\nXE8Jqe0mGtiU/O2346L5IThkS58JlRmep4kYv+II9zE=","translations":{}},{"version":"0.6.1","phpExtensions":[],"databases":[],"shellCommands":[],"phpVersionSpec":"*","platformVersionSpec":">=9.0.0 <12.0.0","minIntSize":32,"download":"https://github.com/nextcloud/nextant/releases/download/v0.6.1/nextant-0.6.1.tar.gz","created":"2016-10-27T21:16:47.066097Z","licenses":["agpl"],"lastModified":"2016-10-27T21:16:47.125641Z","isNightly":false,"rawPhpVersionSpec":"*","rawPlatformVersionSpec":">=9 <=11","signature":"axSX4Kz2P4PbKU676DibjPZsxk8hCIG3lLOmeMXoiBhp3ka4wJ8u5tNwTzgY8/MV\n3mjXe5DNttD66SqmiRNSPKbotYHVFFW3wFK+Dgh/++n/KTomGYUeIwt88Z9ecbuG\nNT6U46jFrfZBYzRHWzbgiJ4c7MCoid9cfmoB7HDuQSyw+E0S2vbLL8+jzMcIzF+5\nTh/sJEterXCyrWSciw/9x98F+4svNbskdEIvrOox3+K6UIhpsojqJR2+bQhG3rsM\nPerOb6J+bzHdLV1ZL/4nWEz1F30T7B08QxY/4pHD68JFQcdtzmHMIhXfCoRvWhN2\nVRnizx3IXBALY4F49Ql6bjsnr6BCp+LroM5RSQ3eupDcqejDJLbjPz8xfOMOwlx7\nz84Xd0MUyqaEkxg1ihsWLbPlYACUZ2aoDkSQUIbfZTTiov7eqTM8UBc/UqVID/LU\nyEW4gjFZzQy6kX76XRAGq1vebKFjCU63asCnVyJhF/YQVTu1hPGbFslkRKnYuh8W\ne4MeaNfbdjcSEX+7oTcPJz6V09pOPvukXL0M1m7lS9PhTisI6oGj8c33GPYp/DSK\n6SGk+ukbt1mwFuFKdTvAMxo1lk96D+pKUv4MX/ralaaoIAmwPTGsSQ04RyL454ae\nU6q8PApwrVyPHYwMBPtXGoQMyb2ZV9rylazYbKCQ8I0=","translations":{}},{"version":"0.6.0","phpExtensions":[],"databases":[],"shellCommands":[],"phpVersionSpec":"*","platformVersionSpec":">=9.0.0 <12.0.0","minIntSize":32,"download":"https://github.com/nextcloud/nextant/releases/download/v0.6.0/nextant-0.6.0.tar.gz","created":"2016-10-26T01:46:48.419025Z","licenses":["agpl"],"lastModified":"2016-10-26T01:46:48.521063Z","isNightly":false,"rawPhpVersionSpec":"*","rawPlatformVersionSpec":">=9 <=11","signature":"W2TmbX/NbbfPPjIJLalO0kCDhhQF1pEohH/CxO9bY+yR+a5NKiTbpAhG2McqpTSj\nmgC4J8/thmwGlWGC+VW+KlpXzzjc7wCgMGMKViOpGD3pIy8p8U5MXTqVgjjrEb9g\nKgr9uErXzxJ5oDfkx8Uh1bUeBJTsAAivGJqMlhBYFGxw8BSB09sfOZytNxo4wbwZ\nNAcYP1qvkUQ8CVR0nInSTRfLvAp5+e/8xxyYZwJIWrdNgpoP0CxiwzKP/VSjBk/U\nsPU4R72UQnVZB0InRCeh/KNTwu1YiPkUKm+mNmt2hCfN7Fm6bY2rUMH7oa8KTkqn\nh52FhbaYRSAR1OPdC5RnHiQWlPh71gq+4Xqgp19Eawnl/QiVteVifSjNQZ+Ban8M\nRyw/PxHnzIWg/OAjx81Jx9mXjUIHSeUxMTJTKTp+lEqIAzjku0iHeU5UPGCfE+VM\nwmopZfnlfk2nLkUwjQXLCIcnZD1ME1m0h/H4Ad0Q/qXpBScUp47npkxg2b8zPIhk\n3aXUmNPLgwyXPWvAuaBK/WwpNefUnqWFns8t2Alpzg/EpC2PrZqciCNDcRFEycoa\nX+JsFyD7eYA7Dc9iIf09gXZX+tZ+Jinb+iPDwYrl1u/7IIBoBlUGCgo+cF7/dL9S\nc3vYeWw6MCH8Sv+ckgS2g726BfdN5EjB/8cb071b4lE=","translations":{}},{"version":"0.5.1","phpExtensions":[],"databases":[],"shellCommands":[],"phpVersionSpec":"*","platformVersionSpec":">=9.0.0 <12.0.0","minIntSize":32,"download":"https://github.com/daita/nextant/releases/download/0.5.1/nextant-0.5.1.tar.gz","created":"2016-10-17T15:23:04.515057Z","licenses":["agpl"],"lastModified":"2016-10-17T15:23:04.576640Z","isNightly":false,"rawPhpVersionSpec":"*","rawPlatformVersionSpec":">=9 <=11","signature":"Pp3rC/9RmAYURneGpGit4HZ2t1qH9A9nwsUnGDgRuJ0akIii7CtJC+n8l1b9k73/\nhxMYnp2JOBu2HWKgFp9a3yeo1xphI5hOUdVQ1UZAWxIQyDI1FZVYDr81l7GCdkqm\n2lMxgviFADSYURCgEnAsj9Nt0NZ6LDcJZiJg3iPAjkDI0U+KnEBjtx/XRFqGUnfp\nCUZ/XLHh/hvoEitSHepTBDCMKkTNjbDEwBYfA2rAoz4zbMR5zKLU+1r1DIUgWSRe\nbk2i8TaTDVL4cbb6MhkGKwkujb+Atikvkpi45o7+fyQMs84c6fjjh/TZJaC+dMyG\n1GCikMPwwtEPjXtnLzynERAxJOd5mP4Ee4sD8ZrnzNUehpyFR88pwWU6r+dmiebb\nnsYlGkhIu2aIO2O4HZ4sUTsO5sfjZ9me7jsafhgJl6iG4IBeHa/L1MsSbhsh6mvH\nYsz4Xsluwr0QcFLmSDDQQYynyogKfJZG2xQsadM0GETWgXE44dVeRvMUsILfB4uZ\nmfKgd23SgaOhYC8m4bg5Hxnkl+xHJnyGZ6jhqg7bhuKwsoLymc18Vmjmb7a45HGV\nXbL5CTmw9yaPOBS3v7v91TnlB+0lhlzbKzZ0xIhY55qsTC76uScbTLwndPqNGaF7\n2koxRbJ3jcmf/Z2MLymdRi2BTZbZkPkxgVrSf9plaR0=","translations":{}},{"version":"0.5.0","phpExtensions":[],"databases":[],"shellCommands":[],"phpVersionSpec":"*","platformVersionSpec":">=9.0.0 <12.0.0","minIntSize":32,"download":"https://github.com/daita/nextant/releases/download/0.5.0/nextant-0.5.0.tar.gz","created":"2016-10-11T11:47:46.191539Z","licenses":["agpl"],"lastModified":"2016-10-11T11:55:40.393000Z","isNightly":false,"rawPhpVersionSpec":"*","rawPlatformVersionSpec":">=9 <=11","signature":"qzQJSLK8nkrQedwwxUdhxL8bq3aXyppAlWJo+n3GqSvqA8uNTzl3Wsci0LsnBV0E\nDvDNW8K0enhl563F/bywQrDhgKl8jTX/CA5KCxqO9P+tvE80zAfMqiRnQayVcWuY\nSWX6RqfI/kqiWyN1SsFp2EDlas6eb+xfIoiJamlfsN0qzHYOFt5W77wmw2Bn9dB5\n9nwHHyC0z60Pf2pPduc/KuZ/971WrDFaIapL7Gm+z9XoaKSwUT575VtS+RNJkOKy\niBrwnHdc8x/62HPFOXsUYjCt2aEmLzPCQN8Ke5pd3596hm5wbAVzTHuxf2H35tb3\nljfGqAZ5AJX2Xd13d4aHXFdSEILwv6IFq2fx0hO3vkvFEoKF5oQ2t3hi++Mw/h8R\n15OKZCOC1bFH3gTwdshmnHSTSr3LxDeTF60aH16wpXcehQuJHagpb/aG8mPD1w+v\n759/mekqa4LYlqT9TLWTqX3UPeQXYIwcPijG84IvW1BDK1M4Mj2Vqsld4jXwG6CP\nORIL8xoQbA52dQI1Y19JXcU9zxIb6GaHYgpV0wejatsZRfhPv2Yd0CBShF4HY7aw\nnfcm88pqzOKNvjnLZjTFQwuJ0AUUSOsWhgZzYt8tATJ2KDZ+lxz+WAMGXJAC/ciY\ntrrglY7YxwJNLbYp+arE0sowZx+IOVaSZBvmUGHiEBY=","translations":{}},{"version":"0.4.2","phpExtensions":[],"databases":[],"shellCommands":[],"phpVersionSpec":"*","platformVersionSpec":">=9.0.0 <12.0.0","minIntSize":32,"download":"https://github.com/daita/nextant/releases/download/0.4.2/nextant-0.4.2.tar.gz","created":"2016-10-06T10:31:12.482416Z","licenses":["agpl"],"lastModified":"2016-10-06T10:31:12.551117Z","isNightly":false,"rawPhpVersionSpec":"*","rawPlatformVersionSpec":">=9 <=11","signature":"QHJhYcBMi5HyPofshZ7EdcXsOfRrl7o48Y3BBBq8CkmYtFDbekghdJqjFbwwZa5u\n8FtgMVwssql/RSDNP6M2Zc/MpQ3K9gDm+DyxE5KRmtMEpzHB+oD+1DxP7kAoyW8/\nnBr5iiQSdLCelddMcTwbdxskLFUXIs3cFuLGhMvr8pdQOAgfxte5lolrj4/8EsJ0\n0yUImgIYG4NlgmvCygGApdpVaOcK7XVtv4oH+x43JmX9YZ3Ce0DQPYPUbFTCf4ZS\nS075j1vcnPx2cRFGxc+YpKzYVVYoy7ZdB75Hq+kaei/atxrTyV5+gcCrVPnH1RkX\n6G8rgu5l8FoGJYopi8/9dd8LsGLFx53CHMdEVob3tFR0WeK4TJAGJa403zE6S3hM\nxr86WCedmjuti0uOhSQr5AEVAoXZ/JUWQMMsPAUMuKEYVjKfmve6TlcNMC2oM5XT\nXcOf4OP3pcQq4ViN53o4Pj6NGSci6IzD6xLeAxKZUoTX37ArVKH6RHS5Najc193H\nRhYRnfE7D5YOr1u10HaZCFCVJif2MgMP0/uH2759NoRjXFowrh7Z6dW7JQG5lbHN\ne0jjJH1Y8m8H1peGGcmM0YxFiOVZ0ER7P+AxT4Cbau/cVhaS8vnPF2a2a6YFRiFS\nVH4aqazvvXrtifDr3lfvlyPCrP/570nwvOJgZGk+K/Y=","translations":{}},{"version":"0.10.0-alpha","phpExtensions":[],"databases":[],"shellCommands":[],"phpVersionSpec":"*","platformVersionSpec":">=9.0.0 <12.0.0","minIntSize":32,"download":"https://github.com/nextcloud/nextant/releases/download/0.10.0/nextant-master-0.10.0.tar.gz","created":"2016-11-22T16:02:57.740378Z","licenses":["agpl"],"lastModified":"2016-11-22T16:02:57.900805Z","isNightly":false,"rawPhpVersionSpec":"*","rawPlatformVersionSpec":">=9 <=11","signature":"kDO3xbPpoUdl2qo362tXfJIqKeiKE12M8FkMXbdKiRNzuQyvDOehQq3dErALZDOr\nLG47Tpez/Kn9Fsx1y4dQDx0w9SD3pyoqvjj1O6KkTYN6srpitQcj9EzEItCY+MZd\ngRSc7Px9MzxpFpgwtuThGVlSt5kLMd0vjWFLVcv7k07rZfWEsTwXd24INIDtlr1A\nC7hyLB777nEOGa7oAzx8nr+FJcIbmu9opVZk8AL40FOFDNBgfAy2AS9hGZreUmRV\ndV9Zh7UAR+RsEeO51xcU/CKqC8Jb0jL1gkYyUaQy16oe1HF9bRs1PWuNL5mYwsmy\nZNn0ay/a7mb7hxJbza1F3lbgBtodvbgUm7+So/QvaR29CSAqqoUXeQy6FfSBVWhZ\nYlTxdQfKcBcUPFO14BBk/O5p5iQaG8JCLJ/EZGDPDIVDMn7crGQ4oLZJv80eqTeB\n7ueDmWaD3gQ9j2XKsMk1uLSyY4unt9AaTofBylsKD1SjLhyxofGZym4jc2+M1GnQ\nyLcoEMSexnKuextu4nzrA0y5k3z9tvO07R29lwT1GFp6oGAakMLob/6XrGsm3YQY\nRQXgfXKFw8XmXBumqG8ayEIyvQ/O8nO6r4R1H8a7ooj6oWa3PhPsen+gLE0SpJPZ\nz3e2TLliwC4VtZp69H7u3px5Qn1Fc6RMDTh571edCr8=","translations":{}}],"screenshots":[{"url":"https://raw.githubusercontent.com/nextcloud/nextant/master/screenshots/displayResult.jpg"},{"url":"https://raw.githubusercontent.com/nextcloud/nextant/master/screenshots/admin.jpg"}],"translations":{"en":{"name":"Nextant","summary":"Navigate through your cloud using Solr","description":"\n\t Navigate through your cloud using Solr\n\n\n**Nextant** performs fast and concise _Full-Text Search_ within:\n\n- your own files,\n- shared files,\n- external storage,\n- bookmarks\n\n\n### Recognized file format:\n- plain text,\n- rtf,\n- pdf,\n- html,\n- openoffice,\n- microsoft office,\n- image JPEG and TIFF (will requiert Tesseract installed)\n- pdf with no text layer (will also requiert Tesseract) _[work in progress]_\n\n\n\n## Installation\n\n- [You first need to install a Solr servlet](https://github.com/nextcloud/nextant/wiki)\n- Download the .zip from the appstore, unzip and place this app in **nextcloud/apps/** (or clone the github and build the app yourself)\n- Enable the app in the app list,\n- Edit the settings in the administration page.\n- Extract the current files from your cloud using the **./occ nextant:index** commands\n- Have a look to this [explanation on how Nextant works](https://github.com/nextcloud/nextant/wiki/Extracting,-Live-Update)\n- _(Optional)_ [Installing Tesseract](https://github.com/tesseract-ocr/tesseract/wiki) ([Optical Character Recognition](https://en.wikipedia.org/wiki/Optical_character_recognition) (OCR) Engine) will allow Nextant to extract text from images and pdfs without text layer.\n\n\n\t"}},"isFeatured":false,"authors":[{"name":"Maxence Lange","mail":"","homepage":""}],"ratingRecent":0.5,"ratingOverall":0.5,"ratingNumRecent":0,"ratingNumOverall":0,"certificate":"-----BEGIN CERTIFICATE-----\nMIIEAjCCAuoCAhAFMA0GCSqGSIb3DQEBCwUAMHsxCzAJBgNVBAYTAkRFMRswGQYD\nVQQIDBJCYWRlbi1XdWVydHRlbWJlcmcxFzAVBgNVBAoMDk5leHRjbG91ZCBHbWJI\nMTYwNAYDVQQDDC1OZXh0Y2xvdWQgQ29kZSBTaWduaW5nIEludGVybWVkaWF0ZSBB\ndXRob3JpdHkwHhcNMTYwOTE0MTI1NDQwWhcNMjYxMjIxMTI1NDQwWjASMRAwDgYD\nVQQDDAduZXh0YW50MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAsbnQ\n+9acjKHfcrUj4yqBpD++GmQ5z2Sp8C8uOz4ZbLyM9bUXEYHo4a4u3CdC49kGUkb3\np5MkEAEzslTWDi1eh5MZgPWpbPgItsDsXY1o55O3jtxNkzSG5/yYcPQcuKtIOm9S\n7DY0K+UQt3nK+RrXEZfARMNrzFbEzpE3b7w901Yl5n+m/B8rhW4pqg8uSfx3u04J\nwduV1fHwoHUB0Ox5HyWib4Pq1XppNh7xdc2Fg93JxshwuCPJyOOzrFTnxC7s1yzQ\nUvaqkjPW5QeQRunQjZ2XtpYH8f8v01W18bNEiHwqtFwuDEyCVx1rvEMgUDVXdPkP\ngZrlB5TzGmz0U3HzYvf6205WuzfHxz7kPj502wP51PoZBKpniggKzmuXkx6BpsZC\nZX45VpDHdiATLwRj1t2bMs3C01nzpIWO5ZwFtkepH3Y+mvwX5lDh/XDsqJC2Yo8o\nWMmniWNW7dspufYOsBUqqYGP7rkailgVT4oYk6D1j6oFZ5SSpfPF5lsyYedDSM6y\nbIGVkSF+sjLK6R9BenBijKceAKsS//WwRYCBPC+JHlsYpXKW12bL+C47Kj2/N6d4\nrYryzV6ofVSF6pwIq0oEjoyfBfNpYavf3xrRkSSmIIlPSnMY7DT1xkGD5retxSm6\n+WIfkWKRZpv2S6PhMHGLspYc4H5Dj8c48rG5Co8CAwEAATANBgkqhkiG9w0BAQsF\nAAOCAQEAOZUwyPaUi+1BOUgQJMWqYRoTVZUyBshTXSC7jSwa97b7qADV9ooA6TYF\nzgsPcE41k7jRkUbnjcY45RGtL3vqsgZbx5TjPa5fGMxlqJ6eYBOY61Q6VIHEVm3u\nxnPEO9dsMoDBijvo5D7KtE+Ccs907Rq70kCsbrdgPHkyb5tDSnCKogN1LiQrg1EP\nmy7Z1C7jG9/h57vx0+QBMDCYnTmqLsvMKqo27uHskzAiB7VXLEdSZ2FtMGHkLUQO\n0bfhnvTZ2VhMmK83t7ovo71An4ycmsolGD/MA0vNI78VrVISrdI8rRh2WntUnCBU\nEJL3BaQAQaASSsvFrcozYxrQG4VzEg==\n-----END CERTIFICATE-----"}]
EOD;
public static $expectedResponse = [
- 'data' =>
- [
- 0 =>
- [
+ 'data'
+ => [
+ 0
+ => [
'id' => 'direct_menu',
- 'categories' =>
- [
+ 'categories'
+ => [
0 => 'customization',
],
'userDocs' => '',
@@ -61,27 +62,27 @@ EOD;
'website' => '',
'created' => '2016-10-01T09:16:06.030994Z',
'lastModified' => '2016-10-06T14:01:05.584192Z',
- 'releases' =>
- [
- 0 =>
- [
+ 'releases'
+ => [
+ 0
+ => [
'version' => '0.9.2',
- 'phpExtensions' =>
- [
+ 'phpExtensions'
+ => [
],
- 'databases' =>
- [
+ 'databases'
+ => [
],
- 'shellCommands' =>
- [
+ 'shellCommands'
+ => [
],
'phpVersionSpec' => '*',
'platformVersionSpec' => '>=9.0.0 <12.0.0',
'minIntSize' => 32,
'download' => 'https://github.com/juliushaertl/direct_menu/releases/download/v0.9.2/direct_menu.tar.gz',
'created' => '2016-10-06T14:01:05.578297Z',
- 'licenses' =>
- [
+ 'licenses'
+ => [
0 => 'agpl',
],
'lastModified' => '2016-10-06T14:01:05.643813Z',
@@ -99,32 +100,32 @@ u2SqRhwybS8j4YvfjAL9RPdRfPLwf6X2gx/Y6QFrKHH0QMI/9J/ZFyoUQcqKbsHV
bkR1DTBCyDjdpNBidpa3/26675dz5IT5Zedp4BBBREQzX08cIhJx5mgqDdX3CU09
uWtzoaLi71/1BWTFAN+Y9VyfZ8/Z3Pg3vKedRJ565mztIj0geL3riEsC5YnPS0+C
+a3B9sDiiOa101EORzX3lrPqL7reEPdCxrIwN+hKFBQ=',
- 'translations' =>
- [
+ 'translations'
+ => [
],
],
],
- 'screenshots' =>
- [
- 0 =>
- [
+ 'screenshots'
+ => [
+ 0
+ => [
'url' => 'https://bitgrid.net/~jus/direct_menu_nc.png',
],
],
- 'translations' =>
- [
- 'en' =>
- [
+ 'translations'
+ => [
+ 'en'
+ => [
'name' => 'Direct Menu',
'summary' => 'Provide easy access to all apps in the header.',
'description' => 'Provide easy access to all apps in the header.',
],
],
'isFeatured' => false,
- 'authors' =>
- [
- 0 =>
- [
+ 'authors'
+ => [
+ 0
+ => [
'name' => 'Julius Härtl',
'mail' => '',
'homepage' => '',
@@ -159,11 +160,11 @@ G2dF9Gtu4GiQ5fuaJknaxlgXHovfqeZwZJX9o4M+Ug81AqiY7XjdiaCPdh0Tthcx
2OmWZo7UBREWenjKyFZZ/iKoqH5sdenBtpo=
-----END CERTIFICATE-----',
],
- 1 =>
- [
+ 1
+ => [
'id' => 'apporder',
- 'categories' =>
- [
+ 'categories'
+ => [
0 => 'customization',
],
'userDocs' => '',
@@ -173,27 +174,27 @@ G2dF9Gtu4GiQ5fuaJknaxlgXHovfqeZwZJX9o4M+Ug81AqiY7XjdiaCPdh0Tthcx
'website' => '',
'created' => '2016-10-01T09:16:47.111889Z',
'lastModified' => '2016-10-12T19:50:16.038821Z',
- 'releases' =>
- [
- 0 =>
- [
+ 'releases'
+ => [
+ 0
+ => [
'version' => '0.3.3',
- 'phpExtensions' =>
- [
+ 'phpExtensions'
+ => [
],
- 'databases' =>
- [
+ 'databases'
+ => [
],
- 'shellCommands' =>
- [
+ 'shellCommands'
+ => [
],
'phpVersionSpec' => '*',
'platformVersionSpec' => '>=9.0.0 <12.0.0',
'minIntSize' => 32,
'download' => 'https://github.com/juliushaertl/apporder/releases/download/0.3.3/apporder.tar.gz',
'created' => '2016-10-12T19:14:10.802359Z',
- 'licenses' =>
- [
+ 'licenses'
+ => [
0 => 'agpl',
],
'lastModified' => '2016-10-12T19:50:16.104357Z',
@@ -201,22 +202,22 @@ G2dF9Gtu4GiQ5fuaJknaxlgXHovfqeZwZJX9o4M+Ug81AqiY7XjdiaCPdh0Tthcx
'rawPhpVersionSpec' => '*',
'rawPlatformVersionSpec' => '>=9 <=11',
'signature' => 'nhlT9lhrmBxIsqh/e3RLm2NDw/U8ZvvoMyYQTLMM3H19DQmVcPYPYC9QWVTsowUzXblVaOXVGylbpKma9yOlOAqJtF3qyXecLl4+tA/Awb6BBhKPgHFdcLDAL5yy1K7/uei3SgEojMlJoI9vEK5I1C5YTh43yNH+//Im6MAuNYFUTlMXK426zdOe6ogpCI5GlYdXopqYANxcpT+WXWET6DDSM5Ev+MYwMcSAY4r8+tvARRU4ZAenRgjkBT6R5z6cD76emRax14tbV6vkjjwRcO+dQtM0tFPbd+5fsNInbauv50VzIMgjA6RnKTOI17gRsSdGlsV4vZn2aIxEPWauu6T/UohMvAE9HMn13vtbpPBSFwJAktj6yHASYGzupNQLprA0+OdyALoLZPpQAKNEXA42a4EVISBKu0EmduHJlUPeqhnIGkkGgVNWS8AWqzP2nFoPdXBgUWateiMcBTHxgEKDac5YmNc9lsXpzf1OxBaXHBhGYKuXPwIfyH3jTWb1OdwixJEuRe9dl63T9qOTRre8QWns/bMqKLibGfMtFhVB21ARJayBuX70eVvabG/2N7Y5t1zUlFygIKu51tvo3AVCRDdRrFWDvkAjxzIz5FIdALVZ+DReFYu/r4WF/w3V9rInFuEDSwb/OH4r8sQycs07tSlMyA74Y3FpjKTBxso=',
- 'translations' =>
- [
+ 'translations'
+ => [
],
],
],
- 'screenshots' =>
- [
- 0 =>
- [
+ 'screenshots'
+ => [
+ 0
+ => [
'url' => 'https://bitgrid.net/~jus/apporder-nc.gif',
],
],
- 'translations' =>
- [
- 'en' =>
- [
+ 'translations'
+ => [
+ 'en'
+ => [
'name' => 'AppOrder',
'summary' => 'Sort apps in the menu with drag and drop',
'description' => '
@@ -242,10 +243,10 @@ first app of the user order.
],
],
'isFeatured' => false,
- 'authors' =>
- [
- 0 =>
- [
+ 'authors'
+ => [
+ 0
+ => [
'name' => 'Julius Härtl',
'mail' => 'jus@bitgrid.net',
'homepage' => '',
@@ -280,11 +281,11 @@ Tu+WGOL2Ee5U4k4XFdzeSLODWby08iU+Gx3bXTR6WIvXCYeIVsCPKK/luvfGkiSR
CpW1GUIA1cyulT4uyHf9g6BMdYVOsFQ=
-----END CERTIFICATE-----',
],
- 2 =>
- [
+ 2
+ => [
'id' => 'twofactor_totp',
- 'categories' =>
- [
+ 'categories'
+ => [
0 => 'tools',
],
'userDocs' => '',
@@ -294,27 +295,27 @@ CpW1GUIA1cyulT4uyHf9g6BMdYVOsFQ=
'website' => '',
'created' => '2016-10-08T14:13:54.356716Z',
'lastModified' => '2016-10-12T14:38:56.186269Z',
- 'releases' =>
- [
- 0 =>
- [
+ 'releases'
+ => [
+ 0
+ => [
'version' => '0.4.1',
- 'phpExtensions' =>
- [
+ 'phpExtensions'
+ => [
],
- 'databases' =>
- [
+ 'databases'
+ => [
],
- 'shellCommands' =>
- [
+ 'shellCommands'
+ => [
],
'phpVersionSpec' => '>=5.4.0 <7.1.0',
'platformVersionSpec' => '>=10.0.0 <12.0.0',
'minIntSize' => 32,
'download' => 'https://github.com/ChristophWurst/twofactor_totp/releases/download/0.4.1/twofactor_totp.tar.gz',
'created' => '2016-10-12T14:38:56.174612Z',
- 'licenses' =>
- [
+ 'licenses'
+ => [
0 => 'agpl',
],
'lastModified' => '2016-10-12T14:38:56.248223Z',
@@ -332,28 +333,28 @@ h7ro5ls+d3OQ8i3i4vdZm821Ytxdu/DQBHiVoOBarvFWwWAv2zd2VAvpTmk6J5yv
3y+csRqpEJYd9fcVMPsTu7WBRRrpBsAqdAHJcZEwak2kz1kdOgSf8FIzP1z6Q71d
Ml2RKcPeutMHHSLiGIN/h7fM5aSs49wGgGZmfz28fHVd7/U0HFSMYmkT/GMq5tMP
Iyc+QZAN4qbX8G0k/QSTkK/L4lOT2hQiQqiSqmWItMk=',
- 'translations' =>
- [
+ 'translations'
+ => [
],
],
],
- 'screenshots' =>
- [
+ 'screenshots'
+ => [
],
- 'translations' =>
- [
- 'en' =>
- [
+ 'translations'
+ => [
+ 'en'
+ => [
'name' => 'Two Factor TOTP Provider',
'summary' => 'A Two-Factor-Auth Provider for TOTP (e.g. Google Authenticator)',
'description' => 'A Two-Factor-Auth Provider for TOTP (e.g. Google Authenticator)',
],
],
'isFeatured' => true,
- 'authors' =>
- [
- 0 =>
- [
+ 'authors'
+ => [
+ 0
+ => [
'name' => 'Christoph Wurst',
'mail' => '',
'homepage' => '',
@@ -388,11 +389,11 @@ VMgQ6yUWNuzOQMZpMIV7RMOUZHvxiX/ZWUFzXNYX0GYub6p4O2uh3LJE+xXyDf77
RBO7PLY3m4TXCeKesxZlkoGke+lnq7B8tkADdPI=
-----END CERTIFICATE-----',
],
- 3 =>
- [
+ 3
+ => [
'id' => 'contacts',
- 'categories' =>
- [
+ 'categories'
+ => [
0 => 'office',
1 => 'organization',
2 => 'social',
@@ -404,27 +405,27 @@ RBO7PLY3m4TXCeKesxZlkoGke+lnq7B8tkADdPI=
'website' => 'https://github.com/nextcloud/contacts#readme',
'created' => '2016-10-30T14:00:58.922766Z',
'lastModified' => '2016-11-22T22:08:01.904319Z',
- 'releases' =>
- [
- 0 =>
- [
+ 'releases'
+ => [
+ 0
+ => [
'version' => '1.5.0',
- 'phpExtensions' =>
- [
+ 'phpExtensions'
+ => [
],
- 'databases' =>
- [
+ 'databases'
+ => [
],
- 'shellCommands' =>
- [
+ 'shellCommands'
+ => [
],
'phpVersionSpec' => '*',
'platformVersionSpec' => '>=9.0.0 <12.0.0',
'minIntSize' => 32,
'download' => 'https://github.com/nextcloud/contacts/releases/download/v1.5.0/contacts.tar.gz',
'created' => '2016-11-22T22:08:01.861942Z',
- 'licenses' =>
- [
+ 'licenses'
+ => [
0 => 'agpl',
],
'lastModified' => '2016-11-22T22:08:02.306939Z',
@@ -442,44 +443,44 @@ Me1EZcde8SLEpTbCWYIfIw/O9Fkp5cWD/dAqoiO6g+gNxSZ/gGp57qoGfFxn7d/x
H3aH8GljatAFjrwItw1JzR0THt0ukkOK+bw/pfCslk10sjHMitmz/GXa4qMS91DZ
BKLUd0dSfQUQzkfwcojImbzJRvca4/DYe3mfG7+RCH0tDL6t72dKL9joB++u5R1u
VZPgkToexlXcKWpiDB8H2/SEShKr4udAOjR5de9CYWM=',
- 'translations' =>
- [
+ 'translations'
+ => [
],
],
],
- 'screenshots' =>
- [
- 0 =>
- [
+ 'screenshots'
+ => [
+ 0
+ => [
'url' => 'https://raw.githubusercontent.com/nextcloud/screenshots/master/apps/Contacts/contacts.png',
],
],
- 'translations' =>
- [
- 'en' =>
- [
+ 'translations'
+ => [
+ 'en'
+ => [
'name' => 'Contacts',
'summary' => 'The new and improved app for your Contacts.',
'description' => 'The new and improved app for your Contacts.',
],
],
'isFeatured' => true,
- 'authors' =>
- [
- 0 =>
- [
+ 'authors'
+ => [
+ 0
+ => [
'name' => 'Alexander Weidinger',
'mail' => '',
'homepage' => '',
],
- 1 =>
- [
+ 1
+ => [
'name' => 'Jan-Christoph Borchardt',
'mail' => '',
'homepage' => '',
],
- 2 =>
- [
+ 2
+ => [
'name' => 'Hendrik Leppelsack',
'mail' => '',
'homepage' => '',
@@ -514,11 +515,11 @@ Gld7yCP47xNPaAZEC66odcClvNtJ2Clgp8739jD6uJJCqcKDejeef0VU1PG7AXId
52bVrGMxJwOuL1393vKxGH0PHDzcB1M=
-----END CERTIFICATE-----',
],
- 4 =>
- [
+ 4
+ => [
'id' => 'mail',
- 'categories' =>
- [
+ 'categories'
+ => [
0 => 'tools',
],
'userDocs' => '',
@@ -528,27 +529,27 @@ Gld7yCP47xNPaAZEC66odcClvNtJ2Clgp8739jD6uJJCqcKDejeef0VU1PG7AXId
'website' => '',
'created' => '2016-10-19T19:41:41.710285Z',
'lastModified' => '2016-10-19T19:57:33.689238Z',
- 'releases' =>
- [
- 0 =>
- [
+ 'releases'
+ => [
+ 0
+ => [
'version' => '0.6.0',
- 'phpExtensions' =>
- [
+ 'phpExtensions'
+ => [
],
- 'databases' =>
- [
+ 'databases'
+ => [
],
- 'shellCommands' =>
- [
+ 'shellCommands'
+ => [
],
'phpVersionSpec' => '>=5.4.0 <7.1.0',
'platformVersionSpec' => '>=10.0.0 <12.0.0',
'minIntSize' => 32,
'download' => 'https://github.com/nextcloud/mail/releases/download/v0.6.0/mail.tar.gz',
'created' => '2016-10-19T19:57:33.676730Z',
- 'licenses' =>
- [
+ 'licenses'
+ => [
0 => 'agpl',
],
'lastModified' => '2016-10-19T19:57:33.834580Z',
@@ -566,10 +567,10 @@ sP8OrkQFooL4E7S4BWfdSiN/a8jUITJQkuXp/OVrVGeCupLWJh7qegUw6DvoqyGy
D4c6b+qYn68kx3CLaPPiz+tFAZQZQdj7+Kx/lohso8yTnVSiGYrMj4IvvCbpsQjg
WF3WSqF/K/tTnPYTWb9NUPSihTbVNv6AXOfTsPEp/ba2YSS5DjvjVjkr5vhR9eg1
ikQ3Cw6lW3vaA4LVCC+hFkMRnI4N0bo5qQavP3PnZPc=',
- 'translations' =>
- [
- 'en' =>
- [
+ 'translations'
+ => [
+ 'en'
+ => [
'changelog' => '### Added
- Alias support
[#1523](https://github.com/owncloud/mail/pull/1523) @tahaalibra
@@ -607,23 +608,23 @@ ikQ3Cw6lW3vaA4LVCC+hFkMRnI4N0bo5qQavP3PnZPc=',
],
],
],
- 'screenshots' =>
- [
+ 'screenshots'
+ => [
],
- 'translations' =>
- [
- 'en' =>
- [
+ 'translations'
+ => [
+ 'en'
+ => [
'name' => 'Mail',
'summary' => 'Easy to use email client which connects to your mail server via IMAP and SMTP.',
'description' => 'Easy to use email client which connects to your mail server via IMAP and SMTP.',
],
],
'isFeatured' => false,
- 'authors' =>
- [
- 0 =>
- [
+ 'authors'
+ => [
+ 0
+ => [
'name' => 'Christoph Wurst, Thomas Müller, Jan-Christoph Borchardt, Steffen Lindner & many more …',
'mail' => '',
'homepage' => '',
@@ -658,11 +659,11 @@ xRS4JXbapjolkxyGSpP+iYSgItVnYzl6o9KZResR4yDsBv7G/8fpV4GQU9IS3zLD
PiZOosVHWJdpUKCw9V4P1prGTQ==
-----END CERTIFICATE-----',
],
- 5 =>
- [
+ 5
+ => [
'id' => 'audioplayer',
- 'categories' =>
- [
+ 'categories'
+ => [
0 => 'multimedia',
],
'userDocs' => 'https://github.com/rello/audioplayer/wiki#user-documentation',
@@ -672,27 +673,27 @@ PiZOosVHWJdpUKCw9V4P1prGTQ==
'website' => 'https://github.com/rello/audioplayer',
'created' => '2016-09-16T05:44:24.857567Z',
'lastModified' => '2016-11-17T22:34:34.637028Z',
- 'releases' =>
- [
- 0 =>
- [
+ 'releases'
+ => [
+ 0
+ => [
'version' => '1.3.1',
- 'phpExtensions' =>
- [
+ 'phpExtensions'
+ => [
],
- 'databases' =>
- [
+ 'databases'
+ => [
],
- 'shellCommands' =>
- [
+ 'shellCommands'
+ => [
],
'phpVersionSpec' => '>=5.4.0',
'platformVersionSpec' => '>=9.0.0 <12.0.0',
'minIntSize' => 32,
'download' => 'https://github.com/Rello/audioplayer/releases/download/1.3.1/audioplayer-1.3.1.tar.gz',
'created' => '2016-11-17T22:34:34.215350Z',
- 'licenses' =>
- [
+ 'licenses'
+ => [
0 => 'agpl',
],
'lastModified' => '2016-11-17T22:34:34.867778Z',
@@ -700,10 +701,10 @@ PiZOosVHWJdpUKCw9V4P1prGTQ==
'rawPhpVersionSpec' => '>=5.4',
'rawPlatformVersionSpec' => '>=9 <=11',
'signature' => 'p6Zz0IEFrxvw6y/3jHgGWWCxR6qpMzvU2HKfxcIVsK6sJnoRUhWLeAXwZ432fH2a S2llj+IGS9OvW+5VQElrXgPtEjDK1BT00DRJnp5RFCRlUv0LNoedJMzx6B6AHqPP JBufk3cG1O/CO0M0L1ITGSmSOzfKvWTRo3lxVGF792NyBaP/SyZCkH1N1TzBQzUi Ywl3+HiglPcXbHjtJm/arnKorbJWVKoaN93xFuaBapd2ozQSpi0fE0uGRsici+U7 HNa1M5WFE1rzUJoufE0E9246At07rFY1e+TdNEq8IlLgCXg5vGCKkEyuWpWno6aX LfRaIiT9x39UTAwNvuDKS0c+n4uWDYPsGfKhDx9N7CXpUrthfXVEWRzZEXG7as10 6ANvrRPJemSZH8FUSrdJhD7k12qa9R825y7mIG68Li8P71V92EOxFfo9tNXqXwBt VuDGxBqByFVPqSCj5I8hrzJzQl2Xt40g8+8ZcSF96RMg/pM+bwRMTv+mz0V+vQQ4 DWjqnWVPalaJ1PPD5/QFFErtXuNRbyxKZ6BMWxfJlLM9Kz66P75K+8fYaSwz+2KG NxY7I3svzS2K9LGH3fBLUy1t3Hl+c3zGFq/ll1MJrf9NswV4yxt2WmISfM/KDww8 yELkGs2cRzbw2tCvnmYlJJhIqRLkyFAbDzWRH/XdVx4=',
- 'translations' =>
- [
- 'en' =>
- [
+ 'translations'
+ => [
+ 'en'
+ => [
'changelog' => '2016-11-17
- fix: one-click-play for wav not working
- fix: wrong sql statement for PostgreSQL [#90](https://github.com/rello/audioplayer/issues/90)',
@@ -711,35 +712,35 @@ PiZOosVHWJdpUKCw9V4P1prGTQ==
],
],
],
- 'screenshots' =>
- [
- 0 =>
- [
+ 'screenshots'
+ => [
+ 0
+ => [
'url' => 'https://github.com/rello/screenshots/raw/master/audioplayer_main.png',
],
- 1 =>
- [
+ 1
+ => [
'url' => 'https://github.com/rello/screenshots/raw/master/audioplayer_lists.png',
],
- 2 =>
- [
+ 2
+ => [
'url' => 'https://github.com/rello/screenshots/raw/master/audioplayer_share.png',
],
],
- 'translations' =>
- [
- 'en' =>
- [
+ 'translations'
+ => [
+ 'en'
+ => [
'name' => 'Audio Player',
'summary' => 'Audio Player for ownCloud and Nextcloud',
'description' => 'Audio Player for MP3, MP4, Ogg, and Wave with a lot of flexibility for all your needs.',
],
],
'isFeatured' => false,
- 'authors' =>
- [
- 0 =>
- [
+ 'authors'
+ => [
+ 0
+ => [
'name' => 'Marcel Scherello',
'mail' => '',
'homepage' => '',
@@ -774,11 +775,11 @@ FNvGFVBn4r5qCiChEoq+rCXHRjPi/eCfbW21XeLFDiLxapcZyc85JIcA7znUYoFe
P7Y/ekMscwWhLbF91OaQlcWpRtEMyde/DaI=
-----END CERTIFICATE-----',
],
- 6 =>
- [
+ 6
+ => [
'id' => 'calendar',
- 'categories' =>
- [
+ 'categories'
+ => [
0 => 'organization',
],
'userDocs' => 'https://docs.nextcloud.com/server/10/user_manual/pim/calendar.html',
@@ -788,27 +789,27 @@ P7Y/ekMscwWhLbF91OaQlcWpRtEMyde/DaI=
'website' => 'https://github.com/nextcloud/calendar/',
'created' => '2016-10-01T12:40:39.060903Z',
'lastModified' => '2016-11-22T20:31:13.029921Z',
- 'releases' =>
- [
- 0 =>
- [
+ 'releases'
+ => [
+ 0
+ => [
'version' => '1.4.1',
- 'phpExtensions' =>
- [
+ 'phpExtensions'
+ => [
],
- 'databases' =>
- [
+ 'databases'
+ => [
],
- 'shellCommands' =>
- [
+ 'shellCommands'
+ => [
],
'phpVersionSpec' => '*',
'platformVersionSpec' => '>=9.0.0 <12.0.0',
'minIntSize' => 32,
'download' => 'https://github.com/nextcloud/calendar/releases/download/v1.4.1/calendar.tar.gz',
'created' => '2016-11-22T20:31:13.020268Z',
- 'licenses' =>
- [
+ 'licenses'
+ => [
0 => 'agpl',
],
'lastModified' => '2016-11-22T20:31:13.087340Z',
@@ -826,34 +827,34 @@ hh1FBfA5pvCJbkJ6nr5bU4bKaffwDX1nr5h77FS5zzn0Pyd7ZIExmVmNtaeJfnfV
eFLKrUg3EvnTjvknbBxMB55h9jNJr0SAlkrmyEVm6+CE3BwRWpKB+cJMBuGiwPwv
r/ASRiJrkDThbNWAUtX70rUmCqDV6/MujLXViqOc/Q2OHvcXd1oGDccJSQT92/1z
7nonnedyYQIDqUt7u68WL8JRxp7pFsEqKLVuWSgxW3c=',
- 'translations' =>
- [
+ 'translations'
+ => [
],
],
],
- 'screenshots' =>
- [
- 0 =>
- [
+ 'screenshots'
+ => [
+ 0
+ => [
'url' => 'https://raw.githubusercontent.com/nextcloud/calendar/master/screenshots/1.png',
],
- 1 =>
- [
+ 1
+ => [
'url' => 'https://raw.githubusercontent.com/nextcloud/calendar/master/screenshots/2.png',
],
- 2 =>
- [
+ 2
+ => [
'url' => 'https://raw.githubusercontent.com/nextcloud/calendar/master/screenshots/3.png',
],
- 3 =>
- [
+ 3
+ => [
'url' => 'https://raw.githubusercontent.com/nextcloud/calendar/master/screenshots/4.png',
],
],
- 'translations' =>
- [
- 'en' =>
- [
+ 'translations'
+ => [
+ 'en'
+ => [
'name' => 'Calendar',
'summary' => 'Calendar GUI for Nextcloud\'s CalDAV server',
'description' => 'The Nextcloud calendar app is a user interface for Nextcloud\'s CalDAV server.
@@ -862,22 +863,22 @@ It integrates with other apps, allows you to manage calendars and events, displa
],
],
'isFeatured' => true,
- 'authors' =>
- [
- 0 =>
- [
+ 'authors'
+ => [
+ 0
+ => [
'name' => 'Georg Ehrke',
'mail' => '',
'homepage' => 'https://georg.coffee',
],
- 1 =>
- [
+ 1
+ => [
'name' => 'Raghu Nayyar',
'mail' => '',
'homepage' => 'http://raghunayyar.com',
],
- 2 =>
- [
+ 2
+ => [
'name' => 'Thomas Citharel',
'mail' => '',
'homepage' => 'https://tcit.fr',
@@ -912,11 +913,11 @@ Q0Bl/QinETk72afGR46Qvc7tC1t9JjQQD3AUbEGuJdGvXjJJ9GREYu01XoODmPdT
jXXOI8XIOK6kxXhPHUc3iWu9b4KqGm0=
-----END CERTIFICATE-----',
],
- 8 =>
- [
+ 8
+ => [
'id' => 'ownpad',
- 'categories' =>
- [
+ 'categories'
+ => [
0 => 'tools',
],
'userDocs' => 'https://github.com/otetard/ownpad/blob/master/README.md#mimetype-detection',
@@ -926,27 +927,27 @@ jXXOI8XIOK6kxXhPHUc3iWu9b4KqGm0=
'website' => '',
'created' => '2016-09-29T15:58:52.814912Z',
'lastModified' => '2016-11-19T17:37:52.278497Z',
- 'releases' =>
- [
- 0 =>
- [
+ 'releases'
+ => [
+ 0
+ => [
'version' => '0.5.6',
- 'phpExtensions' =>
- [
+ 'phpExtensions'
+ => [
],
- 'databases' =>
- [
+ 'databases'
+ => [
],
- 'shellCommands' =>
- [
+ 'shellCommands'
+ => [
],
'phpVersionSpec' => '*',
'platformVersionSpec' => '>=9.0.0 <12.0.0',
'minIntSize' => 32,
'download' => 'https://github.com/otetard/ownpad/releases/download/v0.5.6/ownpad.tar.gz',
'created' => '2016-11-19T17:37:52.234684Z',
- 'licenses' =>
- [
+ 'licenses'
+ => [
0 => 'agpl',
],
'lastModified' => '2016-11-19T17:37:52.423930Z',
@@ -964,18 +965,18 @@ qEC5WBgJucsFxSvkHh52v43M8jgPYBfHWEL/M/+377z3+mbuIh+BcQ+vcDdiqxTF
o3n0+gw3QYIhLEe75sUhxG6ynVUdW25AKKju1kVj3KJnZTBH1R8t8/zy4DnJG8d4
uRGqyU4BXpZjEC3nVlsC7vCncWWhxl0WZQ/MWKqsfjVAU4I88E518D6NioqMnPEJ
iCZ2x+69UCDEQyfCSKajgAYT17r3OhZei8F9KSCH8Vw=',
- 'translations' =>
- [
+ 'translations'
+ => [
],
],
],
- 'screenshots' =>
- [
+ 'screenshots'
+ => [
],
- 'translations' =>
- [
- 'en' =>
- [
+ 'translations'
+ => [
+ 'en'
+ => [
'name' => 'Ownpad',
'summary' => '
Create and open Etherpad and Ethercalc documents.
@@ -990,10 +991,10 @@ iCZ2x+69UCDEQyfCSKajgAYT17r3OhZei8F9KSCH8Vw=',
],
],
'isFeatured' => false,
- 'authors' =>
- [
- 0 =>
- [
+ 'authors'
+ => [
+ 0
+ => [
'name' => 'Olivier Tétard',
'mail' => 'olivier.tetard@miskin.fr',
'homepage' => '',
@@ -1028,11 +1029,11 @@ EUa2uYht/z475k4+vf0YhV98iQH07GnmlfD2TDZgmOCQGKlNfJh1v88OZyLLa3dz
gRHzGwKbAiJ8T8bbpZ3e2ozXxADr
-----END CERTIFICATE-----',
],
- 9 =>
- [
+ 9
+ => [
'id' => 'announcementcenter',
- 'categories' =>
- [
+ 'categories'
+ => [
0 => 'organization',
],
'userDocs' => '',
@@ -1042,27 +1043,27 @@ gRHzGwKbAiJ8T8bbpZ3e2ozXxADr
'website' => 'https://github.com/nextcloud/announcementcenter',
'created' => '2016-09-14T10:38:53.939634Z',
'lastModified' => '2016-11-24T11:21:50.324839Z',
- 'releases' =>
- [
- 0 =>
- [
+ 'releases'
+ => [
+ 0
+ => [
'version' => '2.0.0',
- 'phpExtensions' =>
- [
+ 'phpExtensions'
+ => [
],
- 'databases' =>
- [
+ 'databases'
+ => [
],
- 'shellCommands' =>
- [
+ 'shellCommands'
+ => [
],
'phpVersionSpec' => '*',
'platformVersionSpec' => '>=10.0.0 <12.0.0',
'minIntSize' => 32,
'download' => 'https://github.com/nextcloud/announcementcenter/releases/download/v2.0.0/announcementcenter-2.0.0.tar.gz',
'created' => '2016-10-06T12:41:56.195206Z',
- 'licenses' =>
- [
+ 'licenses'
+ => [
0 => 'agpl',
],
'lastModified' => '2016-10-06T12:41:56.263124Z',
@@ -1075,32 +1076,32 @@ iWUb/Uv/ODj74wVDWqWxAFKaAG/FestCB3InOOZQqQZLzlAV0U9ziYDGNzBjFqof
9rLNxJ2IOqZOA7hhMIKhSrpA0KkSfNhBsVf8CWClYnVkZQiq0LoYkHkHIlXmXUr3
OfQFKEjtsx+bNLa6CkAaocHGHJXAofX3GQZ9cjBsjZqiTfbXfcVk0kRfz7pwL92L
I1McfJYvgMxDQG5bjRpNJw==',
- 'translations' =>
- [
+ 'translations'
+ => [
],
],
],
- 'screenshots' =>
- [
- 0 =>
- [
+ 'screenshots'
+ => [
+ 0
+ => [
'url' => 'https://github.com/nextcloud/announcementcenter/raw/stable10/docs/AnnouncementCenterFrontpage.png',
],
],
- 'translations' =>
- [
- 'en' =>
- [
+ 'translations'
+ => [
+ 'en'
+ => [
'name' => 'Announcement Center',
'summary' => 'An announcement center for Nextcloud',
'description' => 'An announcement center for Nextcloud',
],
],
'isFeatured' => true,
- 'authors' =>
- [
- 0 =>
- [
+ 'authors'
+ => [
+ 0
+ => [
'name' => 'Joas Schilling',
'mail' => '',
'homepage' => '',
@@ -1130,11 +1131,11 @@ JJoU8LQoHwGRtp3wutk0GlFzpEQEvSsn/Lsvvot5IfIe46tnzA6MVj5s64s5G8+Q
phhXFlzXqO/VxquPdbfYjvU=
-----END CERTIFICATE-----',
],
- 11 =>
- [
+ 11
+ => [
'id' => 'rainloop',
- 'categories' =>
- [
+ 'categories'
+ => [
0 => 'social',
1 => 'tools',
],
@@ -1145,27 +1146,27 @@ phhXFlzXqO/VxquPdbfYjvU=
'website' => 'http://www.rainloop.net/',
'created' => '2016-10-20T04:17:37.217555Z',
'lastModified' => '2016-11-18T11:36:04.309739Z',
- 'releases' =>
- [
- 0 =>
- [
+ 'releases'
+ => [
+ 0
+ => [
'version' => '4.26.0',
- 'phpExtensions' =>
- [
+ 'phpExtensions'
+ => [
],
- 'databases' =>
- [
+ 'databases'
+ => [
],
- 'shellCommands' =>
- [
+ 'shellCommands'
+ => [
],
'phpVersionSpec' => '>=5.4.0',
'platformVersionSpec' => '>=10.0.0 <12.0.0',
'minIntSize' => 32,
'download' => 'https://github.com/pierre-alain-b/rainloop-nextcloud/releases/download/v4.26.0/rainloop-4.26.0.tar.gz',
'created' => '2016-10-20T04:28:21.491747Z',
- 'licenses' =>
- [
+ 'licenses'
+ => [
0 => 'agpl',
],
'lastModified' => '2016-11-18T11:36:04.619927Z',
@@ -1183,32 +1184,32 @@ hgFhPrg+7rf7g6UmJFOCp0dC9sBdyQ3KtJkv7bGqPr854r2cdA7xW0QHWQ2in9qQ
LhIczc32ECi3ZVVgyF8zyT4Y/3MRS05oX3FHvHyt88mjni6bVaO78F7ZRSha8gHh
NOAkku7AMXPvUCHaZP2iVCCoAViEso8GeR3O8xh2G42Ai61RLYwx8LB1+23EoJTr
mfFuRYNSg+qAKCokXNnh+lDlwu4AkaQo3vtKGPXvU7A=',
- 'translations' =>
- [
+ 'translations'
+ => [
],
],
],
- 'screenshots' =>
- [
- 0 =>
- [
+ 'screenshots'
+ => [
+ 0
+ => [
'url' => 'https://raw.githubusercontent.com/pierre-alain-b/rainloop-nextcloud/master/screenshots/2016.10.20-screenshot.jpg',
],
],
- 'translations' =>
- [
- 'en' =>
- [
+ 'translations'
+ => [
+ 'en'
+ => [
'name' => 'RainLoop',
'summary' => 'RainLoop Webmail',
'description' => 'Simple, modern and fast web-based email client.',
],
],
'isFeatured' => false,
- 'authors' =>
- [
- 0 =>
- [
+ 'authors'
+ => [
+ 0
+ => [
'name' => 'RainLoop Team',
'mail' => '',
'homepage' => '',
@@ -1243,11 +1244,11 @@ iLYeXQTV0XSRs8xVt+iyGlj7nPkv2DR0oCqRpWUFWeSBI//niDG5WxS3qg8kacSW
fDSYhSN+IjrnIkwNtc8V9t7/GeQB5FE=
-----END CERTIFICATE-----',
],
- 12 =>
- [
+ 12
+ => [
'id' => 'richdocuments',
- 'categories' =>
- [
+ 'categories'
+ => [
0 => 'integration',
1 => 'office',
],
@@ -1258,27 +1259,27 @@ fDSYhSN+IjrnIkwNtc8V9t7/GeQB5FE=
'website' => '',
'created' => '2016-10-31T08:55:45.631429Z',
'lastModified' => '2016-11-24T12:13:53.905352Z',
- 'releases' =>
- [
- 0 =>
- [
+ 'releases'
+ => [
+ 0
+ => [
'version' => '1.1.14',
- 'phpExtensions' =>
- [
+ 'phpExtensions'
+ => [
],
- 'databases' =>
- [
+ 'databases'
+ => [
],
- 'shellCommands' =>
- [
+ 'shellCommands'
+ => [
],
'phpVersionSpec' => '*',
'platformVersionSpec' => '>=9.0.0 <12.0.0',
'minIntSize' => 32,
'download' => 'https://github.com/owncloud/richdocuments/releases/download/1.1.14/richdocuments.tar.gz',
'created' => '2016-11-24T12:10:13.337165Z',
- 'licenses' =>
- [
+ 'licenses'
+ => [
0 => 'agpl',
],
'lastModified' => '2016-11-24T12:13:53.963638Z',
@@ -1291,44 +1292,44 @@ vKu5eNcOkf+WFyFKYi51TbsfWn2+1Wge3WWujKAVcEvqtcOOz+uMWNtqzBptEupk
E1aaRnQfTx488YB8Ubul06LIY0PNCHgGCWPgy817tOVT7JA+V0P0FFonl/PXE0dr
WgtxRJmvGaNiFzYq+kQmdKMfayZTm3kdVgP0W52t5wp878K0i4s2KPg5lANvjTz7
DCT+VV2IGIE52o4RpMUGyQ==',
- 'translations' =>
- [
+ 'translations'
+ => [
],
],
],
- 'screenshots' =>
- [
- 0 =>
- [
+ 'screenshots'
+ => [
+ 0
+ => [
'url' => 'https://nextcloud.com/wp-content/themes/next/assets/img/features/collabora-document.png',
],
- 1 =>
- [
+ 1
+ => [
'url' => 'https://nextcloud.com/wp-content/themes/next/assets/img/features/collabora-app.png',
],
- 2 =>
- [
+ 2
+ => [
'url' => 'https://nextcloud.com/wp-content/themes/next/assets/img/features/collabora-presentation.png',
],
- 3 =>
- [
+ 3
+ => [
'url' => 'https://nextcloud.com/wp-content/themes/next/assets/img/features/collabora-spreadsheet.png',
],
],
- 'translations' =>
- [
- 'en' =>
- [
+ 'translations'
+ => [
+ 'en'
+ => [
'name' => 'Collabora Online',
'summary' => 'Edit office documents directly in your browser.',
'description' => 'Collabora Online allows you to to work with all kinds of office documents directly in your browser. This application requires Collabora Cloudsuite to be installed on one of your servers, please read the documentation to learn more about that.',
],
],
'isFeatured' => false,
- 'authors' =>
- [
- 0 =>
- [
+ 'authors'
+ => [
+ 0
+ => [
'name' => 'Collabora Productivity based on work of Frank Karlitschek, Victor Dubiniuk',
'mail' => '',
'homepage' => '',
@@ -1358,11 +1359,11 @@ myBOrjhrJgLIwvgH26MYZhdiSkFzoE38nMPZdrUmUDxcPCwucWJqgzDPudguFthj
WCVZ3TTG/2z3+tWM
-----END CERTIFICATE-----',
],
- 13 =>
- [
+ 13
+ => [
'id' => 'ocr',
- 'categories' =>
- [
+ 'categories'
+ => [
0 => 'files',
1 => 'tools',
],
@@ -1373,37 +1374,37 @@ WCVZ3TTG/2z3+tWM
'website' => 'https://janis91.github.io/ocr/',
'created' => '2016-09-19T12:07:49.220376Z',
'lastModified' => '2016-11-21T11:22:21.024501Z',
- 'releases' =>
- [
- 0 =>
- [
+ 'releases'
+ => [
+ 0
+ => [
'version' => '1.0.0',
- 'phpExtensions' =>
- [
+ 'phpExtensions'
+ => [
],
- 'databases' =>
- [
- 0 =>
- [
+ 'databases'
+ => [
+ 0
+ => [
'id' => 'pgsql',
'versionSpec' => '*',
'rawVersionSpec' => '*',
],
- 1 =>
- [
+ 1
+ => [
'id' => 'mysql',
'versionSpec' => '*',
'rawVersionSpec' => '*',
],
- 2 =>
- [
+ 2
+ => [
'id' => 'sqlite',
'versionSpec' => '*',
'rawVersionSpec' => '*',
],
],
- 'shellCommands' =>
- [
+ 'shellCommands'
+ => [
0 => 'ocrmypdf',
1 => 'tesseract',
],
@@ -1412,8 +1413,8 @@ WCVZ3TTG/2z3+tWM
'minIntSize' => 32,
'download' => 'https://github.com/janis91/ocr/releases/download/v1.0.0/ocr.tar.gz',
'created' => '2016-10-24T06:50:43.283900Z',
- 'licenses' =>
- [
+ 'licenses'
+ => [
0 => 'agpl',
],
'lastModified' => '2016-11-21T11:22:21.269108Z',
@@ -1431,30 +1432,30 @@ GsrecNftUEhP/ngxA6lMBVkLmmdpiexVisvsavPi64i34OUA6qOuxjgNVBDwg56i
D3tJOF7spnK6I3BhVLviou/zs30AIRVBDTU0Orzx78cbInwy6/vyJib2a1olAaHz
v05SzlQRnBWM4jYBe0mA/2ds9AO6VrXGrT/iLlHemj6JYoGBM185TGewA7OJyX3a
HSlSDqaremmi+aS3onx3AKhXykDxTRkMVarePwTzzFs=',
- 'translations' =>
- [
+ 'translations'
+ => [
],
],
],
- 'screenshots' =>
- [
- 0 =>
- [
+ 'screenshots'
+ => [
+ 0
+ => [
'url' => 'https://raw.githubusercontent.com/janis91/ocr/master/screenshots/sc1.png',
],
- 1 =>
- [
+ 1
+ => [
'url' => 'https://raw.githubusercontent.com/janis91/ocr/master/screenshots/sc2.png',
],
- 2 =>
- [
+ 2
+ => [
'url' => 'https://raw.githubusercontent.com/janis91/ocr/master/screenshots/sc3.png',
],
],
- 'translations' =>
- [
- 'en' =>
- [
+ 'translations'
+ => [
+ 'en'
+ => [
'name' => 'OCR',
'summary' => 'Character recoginition for your images and pdf files.',
'description' => '# Description
@@ -1476,8 +1477,8 @@ The OCR app has some prerequisites:
For further information see the homepage or the appropriate documentation.',
],
- 'de' =>
- [
+ 'de'
+ => [
'name' => 'OCR',
'summary' => 'Schrifterkennung für Bilder (mit Text) und PDF Dateien.',
'description' => '# Beschreibung
@@ -1501,10 +1502,10 @@ Für weiter Informationen besuchen Sie die Homepage oder lesen Sie die zutreffen
],
],
'isFeatured' => false,
- 'authors' =>
- [
- 0 =>
- [
+ 'authors'
+ => [
+ 0
+ => [
'name' => 'Janis Koehr',
'mail' => '',
'homepage' => '',
@@ -1539,11 +1540,11 @@ yA1z/MCBEyTRo80jxFmL+MpwbsdbUJi7Qxlnd56zb6HHDGrLHXZTh9LXgyVbnhWL
kxomWjIXQh4aMHQL4QF7U4EK
-----END CERTIFICATE-----',
],
- 14 =>
- [
+ 14
+ => [
'id' => 'spreedme',
- 'categories' =>
- [
+ 'categories'
+ => [
0 => 'tools',
],
'userDocs' => 'https://github.com/strukturag/nextcloud-spreedme/blob/master/README.md',
@@ -1553,27 +1554,27 @@ kxomWjIXQh4aMHQL4QF7U4EK
'website' => '',
'created' => '2016-09-27T08:43:07.835196Z',
'lastModified' => '2016-11-21T16:51:23.703819Z',
- 'releases' =>
- [
- 0 =>
- [
+ 'releases'
+ => [
+ 0
+ => [
'version' => '0.3.4',
- 'phpExtensions' =>
- [
+ 'phpExtensions'
+ => [
],
- 'databases' =>
- [
+ 'databases'
+ => [
],
- 'shellCommands' =>
- [
+ 'shellCommands'
+ => [
],
'phpVersionSpec' => '*',
'platformVersionSpec' => '>=9.0.0 <12.0.0',
'minIntSize' => 32,
'download' => 'https://apps.owncloud.com/CONTENT/content-files/174436-spreedme.tar.gz',
'created' => '2016-11-21T16:51:23.689599Z',
- 'licenses' =>
- [
+ 'licenses'
+ => [
0 => 'agpl',
],
'lastModified' => '2016-11-21T16:51:23.826509Z',
@@ -1591,44 +1592,44 @@ bOks45K5gE1da4QpkYOUQa3GVMNPqPiT3CqjmJ8tjxq7bGpb6v+YoCLACjjPpPZL
2Y28qLxwHVaINDFUUxD75WWdrlulRbqHwiSw8jolP9qrpXhDuLAqYam9tRwV5K5R
8uNawnFwWkicBEYkN/WtBTouWzehOPn38tHXov6SyEyD6lkuxUBZrsGQ2ru+t33U
k0kKCbV0GFw43I+3Ji5DiB4TUVNZYVoPG1B7Qve+UfA=',
- 'translations' =>
- [
+ 'translations'
+ => [
],
],
],
- 'screenshots' =>
- [
- 0 =>
- [
+ 'screenshots'
+ => [
+ 0
+ => [
'url' => 'https://raw.githubusercontent.com/strukturag/nextcloud-spreedme/master/screenshots/appstore/conference.gif',
],
- 1 =>
- [
+ 1
+ => [
'url' => 'https://raw.githubusercontent.com/strukturag/nextcloud-spreedme/master/screenshots/appstore/presentation.png',
],
- 2 =>
- [
+ 2
+ => [
'url' => 'https://raw.githubusercontent.com/strukturag/nextcloud-spreedme/master/screenshots/appstore/import.png',
],
- 3 =>
- [
+ 3
+ => [
'url' => 'https://raw.githubusercontent.com/strukturag/nextcloud-spreedme/master/screenshots/appstore/users.png',
],
],
- 'translations' =>
- [
- 'en' =>
- [
+ 'translations'
+ => [
+ 'en'
+ => [
'name' => 'Spreed.ME',
'summary' => 'Audio-, video- and text chat for your Nextcloud',
'description' => 'Securely communicate with your friends and family using rich audio-, video- and text chat, and much more right from your Nextcloud – in your browser',
],
],
'isFeatured' => false,
- 'authors' =>
- [
- 0 =>
- [
+ 'authors'
+ => [
+ 0
+ => [
'name' => 'struktur AG',
'mail' => '',
'homepage' => '',
@@ -1663,11 +1664,11 @@ sUNUEU2Decyp0jxLVnrrpz6Y5UupfBR0V8yAv1t5Od/mCKLc5DxHsDWiKOpsob9U
JN+bdzJil2NNftihD4Dm7Ha7OS3O8W0=
-----END CERTIFICATE-----',
],
- 15 =>
- [
+ 15
+ => [
'id' => 'nextant',
- 'categories' =>
- [
+ 'categories'
+ => [
0 => 'files',
1 => 'tools',
],
@@ -1678,27 +1679,27 @@ JN+bdzJil2NNftihD4Dm7Ha7OS3O8W0=
'website' => 'https://github.com/nextcloud/nextant/wiki',
'created' => '2016-09-14T14:34:35.977699Z',
'lastModified' => '2016-11-22T16:02:57.758477Z',
- 'releases' =>
- [
- 0 =>
- [
+ 'releases'
+ => [
+ 0
+ => [
'version' => '0.6.6',
- 'phpExtensions' =>
- [
+ 'phpExtensions'
+ => [
],
- 'databases' =>
- [
+ 'databases'
+ => [
],
- 'shellCommands' =>
- [
+ 'shellCommands'
+ => [
],
'phpVersionSpec' => '*',
'platformVersionSpec' => '>=9.0.0 <12.0.0',
'minIntSize' => 32,
'download' => 'https://github.com/nextcloud/nextant/releases/download/v0.6.6/nextant-0.6.6.tar.gz',
'created' => '2016-11-16T15:11:14.344704Z',
- 'licenses' =>
- [
+ 'licenses'
+ => [
0 => 'agpl',
],
'lastModified' => '2016-11-16T20:39:59.030384Z',
@@ -1716,26 +1717,26 @@ oAKv2GkvWPQ0aiiBtA1i4oXuzvHW/M2wOrK7v7DCpNfILrD/sjxpljxcX082nRCd
9P3iPd2hQ6yOM9fG21LVN74b6wggI81BzFf/xJPd4ZqYLjfeG/yqd0zaiMOzMm1W
se+kc/a4iB3BoCNX3E942pBBzew4ya8LkCXdCHUUsuelDf1va1ikTh/G7D84ll9/
2avNqQnUh3hgOnxFCLI/5VrbqxfSTVdO6O/LTuAmwgw=',
- 'translations' =>
- [
+ 'translations'
+ => [
],
],
],
- 'screenshots' =>
- [
- 0 =>
- [
+ 'screenshots'
+ => [
+ 0
+ => [
'url' => 'https://raw.githubusercontent.com/nextcloud/nextant/master/screenshots/displayResult.jpg',
],
- 1 =>
- [
+ 1
+ => [
'url' => 'https://raw.githubusercontent.com/nextcloud/nextant/master/screenshots/admin.jpg',
],
],
- 'translations' =>
- [
- 'en' =>
- [
+ 'translations'
+ => [
+ 'en'
+ => [
'name' => 'Nextant',
'summary' => 'Navigate through your cloud using Solr',
'description' => '
@@ -1777,10 +1778,10 @@ se+kc/a4iB3BoCNX3E942pBBzew4ya8LkCXdCHUUsuelDf1va1ikTh/G7D84ll9/
],
],
'isFeatured' => false,
- 'authors' =>
- [
- 0 =>
- [
+ 'authors'
+ => [
+ 0
+ => [
'name' => 'Maxence Lange',
'mail' => '',
'homepage' => '',
@@ -1840,7 +1841,7 @@ EJL3BaQAQaASSsvFrcozYxrQG4VzEg==
$this->registry = $this->createMock(IRegistry::class);
$this->fetcher = $this->getMockBuilder(AppFetcher::class)
- ->setMethods(['getChannel'])
+ ->onlyMethods(['getChannel'])
->setConstructorArgs([
$factory,
$this->clientService,
diff --git a/tests/lib/App/AppStore/Fetcher/CategoryFetcherTest.php b/tests/lib/App/AppStore/Fetcher/CategoryFetcherTest.php
index 0beb68bf03a..a703a037653 100644
--- a/tests/lib/App/AppStore/Fetcher/CategoryFetcherTest.php
+++ b/tests/lib/App/AppStore/Fetcher/CategoryFetcherTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
diff --git a/tests/lib/App/AppStore/Fetcher/FetcherBase.php b/tests/lib/App/AppStore/Fetcher/FetcherBase.php
index 95129b3114d..a5a9cc73974 100644
--- a/tests/lib/App/AppStore/Fetcher/FetcherBase.php
+++ b/tests/lib/App/AppStore/Fetcher/FetcherBase.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
diff --git a/tests/lib/App/AppStore/Version/VersionParserTest.php b/tests/lib/App/AppStore/Version/VersionParserTest.php
index 5bd9ee16b39..3ccc68bc076 100644
--- a/tests/lib/App/AppStore/Version/VersionParserTest.php
+++ b/tests/lib/App/AppStore/Version/VersionParserTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
@@ -22,7 +23,7 @@ class VersionParserTest extends TestCase {
/**
* @return array
*/
- public function versionProvider() {
+ public static function versionProvider(): array {
return [
[
'*',
@@ -56,17 +57,17 @@ class VersionParserTest extends TestCase {
}
/**
- * @dataProvider versionProvider
*
* @param string $input
* @param Version $expected
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('versionProvider')]
public function testGetVersion($input,
Version $expected): void {
$this->assertEquals($expected, $this->versionParser->getVersion($input));
}
-
+
public function testGetVersionException(): void {
$this->expectException(\Exception::class);
$this->expectExceptionMessage('Version cannot be parsed: BogusVersion');
@@ -74,7 +75,7 @@ class VersionParserTest extends TestCase {
$this->versionParser->getVersion('BogusVersion');
}
-
+
public function testGetVersionExceptionWithMultiple(): void {
$this->expectException(\Exception::class);
$this->expectExceptionMessage('Version cannot be parsed: >=8.2 <=9.1a');
diff --git a/tests/lib/App/AppStore/Version/VersionTest.php b/tests/lib/App/AppStore/Version/VersionTest.php
index 7fece37cf5f..83be2be69dd 100644
--- a/tests/lib/App/AppStore/Version/VersionTest.php
+++ b/tests/lib/App/AppStore/Version/VersionTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
diff --git a/tests/lib/App/CompareVersionTest.php b/tests/lib/App/CompareVersionTest.php
index 0d020428fed..3c8295f0ed7 100644
--- a/tests/lib/App/CompareVersionTest.php
+++ b/tests/lib/App/CompareVersionTest.php
@@ -23,7 +23,7 @@ class CompareVersionTest extends TestCase {
$this->compare = new CompareVersion();
}
- public function comparisonData() {
+ public static function comparisonData(): array {
return [
// Compatible versions
['13.0.0.3', '13.0.0', '>=', true],
@@ -54,9 +54,7 @@ class CompareVersionTest extends TestCase {
];
}
- /**
- * @dataProvider comparisonData
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('comparisonData')]
public function testComparison(string $actualVersion, string $requiredVersion,
string $comparator, bool $expected): void {
$isCompatible = $this->compare->isCompatible($actualVersion, $requiredVersion,
diff --git a/tests/lib/App/DependencyAnalyzerTest.php b/tests/lib/App/DependencyAnalyzerTest.php
index 31eeb77d7e5..db53d678881 100644
--- a/tests/lib/App/DependencyAnalyzerTest.php
+++ b/tests/lib/App/DependencyAnalyzerTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2023 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2014-2016 ownCloud, Inc.
@@ -67,13 +68,13 @@ class DependencyAnalyzerTest extends TestCase {
}
/**
- * @dataProvider providesPhpVersion
*
* @param string $expectedMissing
* @param string $minVersion
* @param string $maxVersion
* @param string $intSize
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('providesPhpVersion')]
public function testPhpVersion($expectedMissing, $minVersion, $maxVersion, $intSize): void {
$app = [
'dependencies' => [
@@ -96,10 +97,10 @@ class DependencyAnalyzerTest extends TestCase {
}
/**
- * @dataProvider providesDatabases
* @param $expectedMissing
* @param $databases
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('providesDatabases')]
public function testDatabases($expectedMissing, $databases): void {
$app = [
'dependencies' => [
@@ -115,11 +116,11 @@ class DependencyAnalyzerTest extends TestCase {
}
/**
- * @dataProvider providesCommands
*
* @param string $expectedMissing
* @param string|null $commands
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('providesCommands')]
public function testCommand($expectedMissing, $commands): void {
$app = [
'dependencies' => [
@@ -135,10 +136,10 @@ class DependencyAnalyzerTest extends TestCase {
}
/**
- * @dataProvider providesLibs
* @param $expectedMissing
* @param $libs
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('providesLibs')]
public function testLibs($expectedMissing, $libs): void {
$app = [
'dependencies' => [
@@ -155,10 +156,10 @@ class DependencyAnalyzerTest extends TestCase {
}
/**
- * @dataProvider providesOS
* @param $expectedMissing
* @param $oss
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('providesOS')]
public function testOS($expectedMissing, $oss): void {
$app = [
'dependencies' => []
@@ -174,10 +175,10 @@ class DependencyAnalyzerTest extends TestCase {
}
/**
- * @dataProvider providesOC
* @param $expectedMissing
* @param $oc
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('providesOC')]
public function testOC($expectedMissing, $oc): void {
$app = [
'dependencies' => []
@@ -195,7 +196,7 @@ class DependencyAnalyzerTest extends TestCase {
/**
* @return array
*/
- public function providesOC() {
+ public static function providesOC(): array {
return [
// no version -> no missing dependency
[
@@ -423,7 +424,7 @@ class DependencyAnalyzerTest extends TestCase {
/**
* @return array
*/
- public function providesOS() {
+ public static function providesOS(): array {
return [
[[], null],
[[], []],
@@ -435,7 +436,7 @@ class DependencyAnalyzerTest extends TestCase {
/**
* @return array
*/
- public function providesLibs() {
+ public static function providesLibs(): array {
return [
// we expect curl to exist
[[], 'curl'],
@@ -465,7 +466,7 @@ class DependencyAnalyzerTest extends TestCase {
/**
* @return array
*/
- public function providesCommands() {
+ public static function providesCommands(): array {
return [
[[], null],
// grep is known on linux
@@ -483,7 +484,7 @@ class DependencyAnalyzerTest extends TestCase {
/**
* @return array
*/
- public function providesDatabases() {
+ public static function providesDatabases(): array {
return [
// non BC - in case on databases are defined -> all are supported
[[], null],
@@ -496,7 +497,7 @@ class DependencyAnalyzerTest extends TestCase {
/**
* @return array
*/
- public function providesPhpVersion() {
+ public static function providesPhpVersion(): array {
return [
[[], null, null, null],
[[], '5.4', null, null],
diff --git a/tests/lib/App/InfoParserTest.php b/tests/lib/App/InfoParserTest.php
index 1c429ccc405..f7c6a2eb7bd 100644
--- a/tests/lib/App/InfoParserTest.php
+++ b/tests/lib/App/InfoParserTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2023 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2014-2016 ownCloud, Inc.
@@ -12,7 +13,7 @@ use OCP\Cache\CappedMemoryCache;
use Test\TestCase;
class InfoParserTest extends TestCase {
- /** @var OCP\Cache\CappedMemoryCache */
+ /** @var CappedMemoryCache */
private static $cache;
public static function setUpBeforeClass(): void {
@@ -31,21 +32,17 @@ class InfoParserTest extends TestCase {
$this->assertEquals($expectedData, $data);
}
- /**
- * @dataProvider providesInfoXml
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('providesInfoXml')]
public function testParsingValidXmlWithoutCache($expectedJson, $xmlFile): void {
$this->parserTest($expectedJson, $xmlFile);
}
- /**
- * @dataProvider providesInfoXml
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('providesInfoXml')]
public function testParsingValidXmlWithCache($expectedJson, $xmlFile): void {
$this->parserTest($expectedJson, $xmlFile, self::$cache);
}
- public function providesInfoXml(): array {
+ public static function providesInfoXml(): array {
return [
['expected-info.json', 'valid-info.xml'],
[null, 'invalid-info.xml'],
diff --git a/tests/lib/App/PlatformRepositoryTest.php b/tests/lib/App/PlatformRepositoryTest.php
index 921d24159c9..bc0ecb97c5a 100644
--- a/tests/lib/App/PlatformRepositoryTest.php
+++ b/tests/lib/App/PlatformRepositoryTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2020-2023 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2014-2016 ownCloud, Inc.
@@ -6,21 +7,21 @@
*/
namespace Test\App;
-use OC;
+use OC\App\PlatformRepository;
class PlatformRepositoryTest extends \Test\TestCase {
/**
- * @dataProvider providesVersions
* @param $expected
* @param $input
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('providesVersions')]
public function testVersion($input, $expected): void {
- $pr = new OC\App\PlatformRepository();
+ $pr = new PlatformRepository();
$normalizedVersion = $pr->normalizeVersion($input);
$this->assertEquals($expected, $normalizedVersion);
}
- public function providesVersions() {
+ public static function providesVersions(): array {
return [
'none' => ['1.0.0', '1.0.0.0'],
'none/2' => ['1.2.3.4', '1.2.3.4'],
diff --git a/tests/lib/AppConfigTest.php b/tests/lib/AppConfigTest.php
index 518d7909d70..408e4321d4f 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;
/**
@@ -32,13 +33,13 @@ class AppConfigTest extends TestCase {
private array $originalConfig;
/**
- * @var array<string, array<array<string, string, int, bool, bool>>>
- * [appId => [configKey, configValue, valueType, lazy, sensitive]]
+ * @var array<string, array<string, array<string, string, int, bool, bool>>>
+ * [appId => [configKey, configValue, valueType, lazy, sensitive]]
*/
- private array $baseStruct =
- [
+ private static array $baseStruct
+ = [
'testapp' => [
- 'enabled' => ['enabled', 'true'],
+ 'enabled' => ['enabled', 'yes'],
'installed_version' => ['installed_version', '1.2.3'],
'depends_on' => ['depends_on', 'someapp'],
'deletethis' => ['deletethis', 'deletethis'],
@@ -49,11 +50,12 @@ class AppConfigTest extends TestCase {
'otherkey' => ['otherkey', 'othervalue']
],
'123456' => [
- 'enabled' => ['enabled', 'true'],
+ 'enabled' => ['enabled', 'yes'],
'key' => ['key', 'value']
],
'anotherapp' => [
- 'enabled' => ['enabled', 'false'],
+ 'enabled' => ['enabled', 'no'],
+ 'installed_version' => ['installed_version', '3.2.1'],
'key' => ['key', 'value']
],
'non-sensitive-app' => [
@@ -86,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();
@@ -114,14 +116,14 @@ class AppConfigTest extends TestCase {
]
);
- foreach ($this->baseStruct as $appId => $appData) {
+ foreach (self::$baseStruct as $appId => $appData) {
foreach ($appData as $key => $row) {
$value = $row[1];
$type = $row[2] ?? IAppConfig::VALUE_MIXED;
if (($row[4] ?? false) === true) {
$type |= IAppConfig::VALUE_SENSITIVE;
$value = self::invokePrivate(AppConfig::class, 'ENCRYPTION_PREFIX') . $this->crypto->encrypt($value);
- $this->baseStruct[$appId][$key]['encrypted'] = $value;
+ self::$baseStruct[$appId][$key]['encrypted'] = $value;
}
$sql->setParameters(
@@ -175,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,
@@ -197,7 +199,7 @@ class AppConfigTest extends TestCase {
$this->assertSame(true, $status['fastLoaded'], $msg);
$this->assertSame(false, $status['lazyLoaded'], $msg);
- $apps = array_values(array_diff(array_keys($this->baseStruct), ['only-lazy']));
+ $apps = array_values(array_diff(array_keys(self::$baseStruct), ['only-lazy']));
$this->assertEqualsCanonicalizing($apps, array_keys($status['fastCache']), $msg);
$this->assertSame([], array_keys($status['lazyCache']), $msg);
}
@@ -208,7 +210,20 @@ class AppConfigTest extends TestCase {
public function testGetApps(): void {
$config = $this->generateAppConfig(false);
- $this->assertEqualsCanonicalizing(array_keys($this->baseStruct), $config->getApps());
+ $this->assertEqualsCanonicalizing(array_keys(self::$baseStruct), $config->getApps());
+ }
+
+ public function testGetAppInstalledVersions(): void {
+ $config = $this->generateAppConfig(false);
+
+ $this->assertEquals(
+ ['testapp' => '1.2.3', 'anotherapp' => '3.2.1'],
+ $config->getAppInstalledVersions(false)
+ );
+ $this->assertEquals(
+ ['testapp' => '1.2.3'],
+ $config->getAppInstalledVersions(true)
+ );
}
/**
@@ -217,9 +232,9 @@ class AppConfigTest extends TestCase {
* @return array<string, string[]> ['appId' => ['key1', 'key2', ]]
* @see testGetKeys
*/
- public function providerGetAppKeys(): array {
+ public static function providerGetAppKeys(): array {
$appKeys = [];
- foreach ($this->baseStruct as $appId => $appData) {
+ foreach (self::$baseStruct as $appId => $appData) {
$keys = [];
foreach ($appData as $row) {
$keys[] = $row[0];
@@ -238,9 +253,9 @@ class AppConfigTest extends TestCase {
* @see testIsLazy
* @see testGetKeys
*/
- public function providerGetKeys(): array {
+ public static function providerGetKeys(): array {
$appKeys = [];
- foreach ($this->baseStruct as $appId => $appData) {
+ foreach (self::$baseStruct as $appId => $appData) {
foreach ($appData as $row) {
$appKeys[] = [
(string)$appId, $row[0], $row[1], $row[2] ?? IAppConfig::VALUE_MIXED, $row[3] ?? false,
@@ -253,11 +268,11 @@ class AppConfigTest extends TestCase {
}
/**
- * @dataProvider providerGetAppKeys
*
* @param string $appId
* @param array $expectedKeys
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('providerGetAppKeys')]
public function testGetKeys(string $appId, array $expectedKeys): void {
$config = $this->generateAppConfig();
$this->assertEqualsCanonicalizing($expectedKeys, $config->getKeys($appId));
@@ -269,13 +284,13 @@ class AppConfigTest extends TestCase {
}
/**
- * @dataProvider providerGetKeys
*
* @param string $appId
* @param string $configKey
* @param string $value
* @param bool $lazy
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('providerGetKeys')]
public function testHasKey(string $appId, string $configKey, string $value, int $type, bool $lazy): void {
$config = $this->generateAppConfig();
$this->assertEquals(true, $config->hasKey($appId, $configKey, $lazy));
@@ -283,7 +298,7 @@ class AppConfigTest extends TestCase {
public function testHasKeyOnNonExistentKeyReturnsFalse(): void {
$config = $this->generateAppConfig();
- $this->assertEquals(false, $config->hasKey(array_keys($this->baseStruct)[0], 'inexistant-key'));
+ $this->assertEquals(false, $config->hasKey(array_keys(self::$baseStruct)[0], 'inexistant-key'));
}
public function testHasKeyOnUnknownAppReturnsFalse(): void {
@@ -306,9 +321,7 @@ class AppConfigTest extends TestCase {
$this->assertSame(true, $config->hasKey('non-sensitive-app', 'lazy-key', null));
}
- /**
- * @dataProvider providerGetKeys
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('providerGetKeys')]
public function testIsSensitive(
string $appId, string $configKey, string $configValue, int $type, bool $lazy, bool $sensitive,
): void {
@@ -319,7 +332,7 @@ class AppConfigTest extends TestCase {
public function testIsSensitiveOnNonExistentKeyThrowsException(): void {
$config = $this->generateAppConfig();
$this->expectException(AppConfigUnknownKeyException::class);
- $config->isSensitive(array_keys($this->baseStruct)[0], 'inexistant-key');
+ $config->isSensitive(array_keys(self::$baseStruct)[0], 'inexistant-key');
}
public function testIsSensitiveOnUnknownAppThrowsException(): void {
@@ -350,9 +363,7 @@ class AppConfigTest extends TestCase {
$config->isSensitive('non-sensitive-app', 'lazy-key', false);
}
- /**
- * @dataProvider providerGetKeys
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('providerGetKeys')]
public function testIsLazy(string $appId, string $configKey, string $configValue, int $type, bool $lazy,
): void {
$config = $this->generateAppConfig();
@@ -362,7 +373,7 @@ class AppConfigTest extends TestCase {
public function testIsLazyOnNonExistentKeyThrowsException(): void {
$config = $this->generateAppConfig();
$this->expectException(AppConfigUnknownKeyException::class);
- $config->isLazy(array_keys($this->baseStruct)[0], 'inexistant-key');
+ $config->isLazy(array_keys(self::$baseStruct)[0], 'inexistant-key');
}
public function testIsLazyOnUnknownAppThrowsException(): void {
@@ -393,11 +404,11 @@ class AppConfigTest extends TestCase {
}
/**
- * @dataProvider providerGetAppKeys
*
* @param string $appId
* @param array $keys
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('providerGetAppKeys')]
public function testGetAllValuesWithEmptyKey(string $appId, array $keys): void {
$config = $this->generateAppConfig();
$this->assertEqualsCanonicalizing($keys, array_keys($config->getAllValues($appId, '')));
@@ -410,7 +421,7 @@ class AppConfigTest extends TestCase {
public function testSearchValues(): void {
$config = $this->generateAppConfig();
- $this->assertEqualsCanonicalizing(['testapp' => 'true', '123456' => 'true', 'anotherapp' => 'false'], $config->searchValues('enabled'));
+ $this->assertEqualsCanonicalizing(['testapp' => 'yes', '123456' => 'yes', 'anotherapp' => 'no'], $config->searchValues('enabled'));
}
public function testGetValueString(): void {
@@ -530,7 +541,7 @@ class AppConfigTest extends TestCase {
*
* @see testGetValueMixed
*/
- public function providerGetValueMixed(): array {
+ public static function providerGetValueMixed(): array {
return [
// key, value, type
['mixed', 'mix', IAppConfig::VALUE_MIXED],
@@ -543,23 +554,23 @@ class AppConfigTest extends TestCase {
}
/**
- * @dataProvider providerGetValueMixed
*
* @param string $key
* @param string $value
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('providerGetValueMixed')]
public function testGetValueMixed(string $key, string $value): void {
$config = $this->generateAppConfig();
$this->assertSame($value, $config->getValueMixed('typed', $key));
}
/**
- * @dataProvider providerGetValueMixed
*
* @param string $key
* @param string $value
* @param int $type
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('providerGetValueMixed')]
public function testGetValueType(string $key, string $value, int $type): void {
$config = $this->generateAppConfig();
$this->assertSame($type, $config->getValueType('typed', $key));
@@ -1322,7 +1333,7 @@ class AppConfigTest extends TestCase {
$config = $this->generateAppConfig();
$config->deleteKey('anotherapp', 'key');
$status = $config->statusCache();
- $this->assertEqualsCanonicalizing(['enabled' => 'false'], $status['fastCache']['anotherapp']);
+ $this->assertEqualsCanonicalizing(['enabled' => 'no', 'installed_version' => '3.2.1'], $status['fastCache']['anotherapp']);
}
public function testDeleteKeyDatabase(): void {
diff --git a/tests/lib/AppFramework/AppTest.php b/tests/lib/AppFramework/AppTest.php
index 3c535a4bf7a..c43cd8e3c54 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';
@@ -62,11 +63,11 @@ class AppTest extends \Test\TestCase {
$infoXmlPath = $this->appPath . '/appinfo/info.xml';
mkdir($this->appPath . '/appinfo', 0777, true);
- $xml = '<?xml version="1.0" encoding="UTF-8"?>' .
- '<info>' .
- '<id>namespacetestapp</id>' .
- '<namespace>NameSpaceTestApp</namespace>' .
- '</info>';
+ $xml = '<?xml version="1.0" encoding="UTF-8"?>'
+ . '<info>'
+ . '<id>namespacetestapp</id>'
+ . '<namespace>NameSpaceTestApp</namespace>'
+ . '</info>';
file_put_contents($infoXmlPath, $xml);
}
@@ -124,16 +125,14 @@ class AppTest extends \Test\TestCase {
App::main($this->controllerName, $this->controllerMethod, $this->container, []);
}
- public function dataNoOutput() {
+ public static function dataNoOutput(): array {
return [
['HTTP/2.0 204 No content'],
['HTTP/2.0 304 Not modified'],
];
}
- /**
- * @dataProvider dataNoOutput
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataNoOutput')]
public function testNoOutput(string $statusCode): void {
$return = [$statusCode, [], [], $this->output, new Response()];
$this->dispatcher->expects($this->once())
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/Bootstrap/RegistrationContextTest.php b/tests/lib/AppFramework/Bootstrap/RegistrationContextTest.php
index 1e0b13b5755..c0095713370 100644
--- a/tests/lib/AppFramework/Bootstrap/RegistrationContextTest.php
+++ b/tests/lib/AppFramework/Bootstrap/RegistrationContextTest.php
@@ -68,9 +68,7 @@ class RegistrationContextTest extends TestCase {
$this->context->delegateEventListenerRegistrations($dispatcher);
}
- /**
- * @dataProvider dataProvider_TrueFalse
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataProvider_TrueFalse')]
public function testRegisterService(bool $shared): void {
$app = $this->createMock(App::class);
$service = 'abc';
@@ -156,7 +154,7 @@ class RegistrationContextTest extends TestCase {
);
}
- public function dataProvider_TrueFalse() {
+ public static function dataProvider_TrueFalse(): array {
return[
[true],
[false]
diff --git a/tests/lib/AppFramework/Controller/AuthPublicShareControllerTest.php b/tests/lib/AppFramework/Controller/AuthPublicShareControllerTest.php
index d6e0321023e..4efcac2dccf 100644
--- a/tests/lib/AppFramework/Controller/AuthPublicShareControllerTest.php
+++ b/tests/lib/AppFramework/Controller/AuthPublicShareControllerTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2018 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
@@ -38,7 +39,7 @@ class AuthPublicShareControllerTest extends \Test\TestCase {
$this->request,
$this->session,
$this->urlGenerator
- ])->setMethods([
+ ])->onlyMethods([
'authFailed',
'getPasswordHash',
'isAuthenticated',
@@ -64,7 +65,9 @@ class AuthPublicShareControllerTest extends \Test\TestCase {
$this->controller->setToken('myToken');
$this->session->method('get')
- ->willReturnMap(['public_link_authenticate_redirect', ['foo' => 'bar']]);
+ ->willReturnMap([
+ ['public_link_authenticate_redirect', json_encode(['foo' => 'bar'])],
+ ]);
$this->urlGenerator->method('linkToRoute')
->willReturn('myLink!');
@@ -107,7 +110,9 @@ class AuthPublicShareControllerTest extends \Test\TestCase {
$this->session->expects($this->once())
->method('regenerateId');
$this->session->method('get')
- ->willReturnMap(['public_link_authenticate_redirect', ['foo' => 'bar']]);
+ ->willReturnMap([
+ ['public_link_authenticate_redirect', json_encode(['foo' => 'bar'])],
+ ]);
$tokenSet = false;
$hashSet = false;
diff --git a/tests/lib/AppFramework/Controller/ControllerTest.php b/tests/lib/AppFramework/Controller/ControllerTest.php
index 7c466e3a5b7..aa016872847 100644
--- a/tests/lib/AppFramework/Controller/ControllerTest.php
+++ b/tests/lib/AppFramework/Controller/ControllerTest.php
@@ -66,7 +66,7 @@ class ControllerTest extends \Test\TestCase {
);
$this->app = $this->getMockBuilder(DIContainer::class)
- ->setMethods(['getAppName'])
+ ->onlyMethods(['getAppName'])
->setConstructorArgs(['test'])
->getMock();
$this->app->expects($this->any())
diff --git a/tests/lib/AppFramework/Controller/OCSControllerTest.php b/tests/lib/AppFramework/Controller/OCSControllerTest.php
index 027881074c9..4ab45ad6b06 100644
--- a/tests/lib/AppFramework/Controller/OCSControllerTest.php
+++ b/tests/lib/AppFramework/Controller/OCSControllerTest.php
@@ -53,19 +53,19 @@ class OCSControllerTest extends \Test\TestCase {
));
$controller->setOCSVersion(1);
- $expected = "<?xml version=\"1.0\"?>\n" .
- "<ocs>\n" .
- " <meta>\n" .
- " <status>ok</status>\n" .
- " <statuscode>100</statuscode>\n" .
- " <message>OK</message>\n" .
- " <totalitems></totalitems>\n" .
- " <itemsperpage></itemsperpage>\n" .
- " </meta>\n" .
- " <data>\n" .
- " <test>hi</test>\n" .
- " </data>\n" .
- "</ocs>\n";
+ $expected = "<?xml version=\"1.0\"?>\n"
+ . "<ocs>\n"
+ . " <meta>\n"
+ . " <status>ok</status>\n"
+ . " <statuscode>100</statuscode>\n"
+ . " <message>OK</message>\n"
+ . " <totalitems></totalitems>\n"
+ . " <itemsperpage></itemsperpage>\n"
+ . " </meta>\n"
+ . " <data>\n"
+ . " <test>hi</test>\n"
+ . " </data>\n"
+ . "</ocs>\n";
$params = new DataResponse(['test' => 'hi']);
@@ -81,8 +81,8 @@ class OCSControllerTest extends \Test\TestCase {
$this->createMock(IConfig::class)
));
$controller->setOCSVersion(1);
- $expected = '{"ocs":{"meta":{"status":"ok","statuscode":100,"message":"OK",' .
- '"totalitems":"","itemsperpage":""},"data":{"test":"hi"}}}';
+ $expected = '{"ocs":{"meta":{"status":"ok","statuscode":100,"message":"OK",'
+ . '"totalitems":"","itemsperpage":""},"data":{"test":"hi"}}}';
$params = new DataResponse(['test' => 'hi']);
$response = $controller->buildResponse($params, 'json');
@@ -99,17 +99,17 @@ class OCSControllerTest extends \Test\TestCase {
));
$controller->setOCSVersion(2);
- $expected = "<?xml version=\"1.0\"?>\n" .
- "<ocs>\n" .
- " <meta>\n" .
- " <status>ok</status>\n" .
- " <statuscode>200</statuscode>\n" .
- " <message>OK</message>\n" .
- " </meta>\n" .
- " <data>\n" .
- " <test>hi</test>\n" .
- " </data>\n" .
- "</ocs>\n";
+ $expected = "<?xml version=\"1.0\"?>\n"
+ . "<ocs>\n"
+ . " <meta>\n"
+ . " <status>ok</status>\n"
+ . " <statuscode>200</statuscode>\n"
+ . " <message>OK</message>\n"
+ . " </meta>\n"
+ . " <data>\n"
+ . " <test>hi</test>\n"
+ . " </data>\n"
+ . "</ocs>\n";
$params = new DataResponse(['test' => 'hi']);
diff --git a/tests/lib/AppFramework/Controller/PublicShareControllerTest.php b/tests/lib/AppFramework/Controller/PublicShareControllerTest.php
index f8430d42ef1..e676b8a0d7e 100644
--- a/tests/lib/AppFramework/Controller/PublicShareControllerTest.php
+++ b/tests/lib/AppFramework/Controller/PublicShareControllerTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2018 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
@@ -11,17 +12,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 {
@@ -57,7 +55,7 @@ class PublicShareControllerTest extends \Test\TestCase {
$this->assertEquals('test', $controller->getToken());
}
- public function dataIsAuthenticated() {
+ public static function dataIsAuthenticated(): array {
return [
[false, 'token1', 'token1', 'hash1', 'hash1', true],
[false, 'token1', 'token1', 'hash1', 'hash2', true],
@@ -70,9 +68,7 @@ class PublicShareControllerTest extends \Test\TestCase {
];
}
- /**
- * @dataProvider dataIsAuthenticated
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataIsAuthenticated')]
public function testIsAuthenticatedNotPasswordProtected(bool $protected, string $token1, string $token2, string $hash1, string $hash2, bool $expected): void {
$controller = new TestController('app', $this->request, $this->session, $hash2, $protected);
diff --git a/tests/lib/AppFramework/Db/EntityTest.php b/tests/lib/AppFramework/Db/EntityTest.php
index 3c844780b07..eab081e6ac6 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 {
@@ -211,7 +210,7 @@ class EntityTest extends \Test\TestCase {
}
- public function dataSetterCasts(): array {
+ public static function dataSetterCasts(): array {
return [
['Id', '3', 3],
['smallInt', '3', 3],
@@ -226,9 +225,7 @@ class EntityTest extends \Test\TestCase {
}
- /**
- * @dataProvider dataSetterCasts
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataSetterCasts')]
public function testSetterCasts(string $field, mixed $in, mixed $out): void {
$entity = new TestEntity();
$entity->{'set' . $field}($in);
diff --git a/tests/lib/AppFramework/Db/QBMapperDBTest.php b/tests/lib/AppFramework/Db/QBMapperDBTest.php
index 72bc2d956d6..614f1099644 100644
--- a/tests/lib/AppFramework/Db/QBMapperDBTest.php
+++ b/tests/lib/AppFramework/Db/QBMapperDBTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
@@ -63,14 +64,14 @@ class QBDBTestMapper extends QBMapper {
* @group DB
*/
class QBMapperDBTest extends TestCase {
- /** @var \Doctrine\DBAL\Connection|\OCP\IDBConnection */
+ /** @var \Doctrine\DBAL\Connection|IDBConnection */
protected $connection;
protected $schemaSetup = false;
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 3cf32e56f12..0f18ef3f204 100644
--- a/tests/lib/AppFramework/Db/QBMapperTest.php
+++ b/tests/lib/AppFramework/Db/QBMapperTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2019 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
@@ -99,7 +100,7 @@ class QBMapperTest extends \Test\TestCase {
$this->mapper = new QBTestMapper($this->db);
}
-
+
public function testInsertEntityParameterTypeMapping(): void {
$datetime = new \DateTimeImmutable();
$entity = new QBTestEntity();
@@ -117,31 +118,40 @@ class QBMapperTest extends \Test\TestCase {
$booleanParam = $this->qb->createNamedParameter('boolean_prop', IQueryBuilder::PARAM_BOOL);
$datetimeParam = $this->qb->createNamedParameter('datetime_prop', IQueryBuilder::PARAM_DATETIME_IMMUTABLE);
+ $createNamedParameterCalls = [
+ [123, IQueryBuilder::PARAM_INT, null],
+ [true, IQueryBuilder::PARAM_BOOL, null],
+ ['string', IQueryBuilder::PARAM_STR, null],
+ [456, IQueryBuilder::PARAM_INT, null],
+ [false, IQueryBuilder::PARAM_BOOL, null],
+ [$datetime, IQueryBuilder::PARAM_DATETIME_IMMUTABLE, null],
+ ];
$this->qb->expects($this->exactly(6))
->method('createNamedParameter')
- ->withConsecutive(
- [$this->equalTo(123), $this->equalTo(IQueryBuilder::PARAM_INT)],
- [$this->equalTo(true), $this->equalTo(IQueryBuilder::PARAM_BOOL)],
- [$this->equalTo('string'), $this->equalTo(IQueryBuilder::PARAM_STR)],
- [$this->equalTo(456), $this->equalTo(IQueryBuilder::PARAM_INT)],
- [$this->equalTo(false), $this->equalTo(IQueryBuilder::PARAM_BOOL)],
- [$this->equalTo($datetime), $this->equalTo(IQueryBuilder::PARAM_DATETIME_IMMUTABLE)],
- );
+ ->willReturnCallback(function () use (&$createNamedParameterCalls): void {
+ $expected = array_shift($createNamedParameterCalls);
+ $this->assertEquals($expected, func_get_args());
+ });
+
+ $setValueCalls = [
+ ['int_prop', $intParam],
+ ['bool_prop', $boolParam],
+ ['string_prop', $stringParam],
+ ['integer_prop', $integerParam],
+ ['boolean_prop', $booleanParam],
+ ['datetime_prop', $datetimeParam],
+ ];
$this->qb->expects($this->exactly(6))
->method('setValue')
- ->withConsecutive(
- [$this->equalTo('int_prop'), $this->equalTo($intParam)],
- [$this->equalTo('bool_prop'), $this->equalTo($boolParam)],
- [$this->equalTo('string_prop'), $this->equalTo($stringParam)],
- [$this->equalTo('integer_prop'), $this->equalTo($integerParam)],
- [$this->equalTo('boolean_prop'), $this->equalTo($booleanParam)],
- [$this->equalTo('datetime_prop'), $this->equalTo($datetimeParam)],
- );
+ ->willReturnCallback(function () use (&$setValueCalls): void {
+ $expected = array_shift($setValueCalls);
+ $this->assertEquals($expected, func_get_args());
+ });
$this->mapper->insert($entity);
}
-
+
public function testUpdateEntityParameterTypeMapping(): void {
$datetime = new \DateTimeImmutable();
$entity = new QBTestEntity();
@@ -163,30 +173,38 @@ class QBMapperTest extends \Test\TestCase {
$jsonParam = $this->qb->createNamedParameter('json_prop', IQueryBuilder::PARAM_JSON);
$datetimeParam = $this->qb->createNamedParameter('datetime_prop', IQueryBuilder::PARAM_DATETIME_IMMUTABLE);
+ $createNamedParameterCalls = [
+ [123, IQueryBuilder::PARAM_INT, null],
+ [true, IQueryBuilder::PARAM_BOOL, null],
+ ['string', IQueryBuilder::PARAM_STR, null],
+ [456, IQueryBuilder::PARAM_INT, null],
+ [false, IQueryBuilder::PARAM_BOOL, null],
+ [['hello' => 'world'], IQueryBuilder::PARAM_JSON, null],
+ [$datetime, IQueryBuilder::PARAM_DATETIME_IMMUTABLE, null],
+ [789, IQueryBuilder::PARAM_INT, null],
+ ];
$this->qb->expects($this->exactly(8))
->method('createNamedParameter')
- ->withConsecutive(
- [$this->equalTo(123), $this->equalTo(IQueryBuilder::PARAM_INT)],
- [$this->equalTo(true), $this->equalTo(IQueryBuilder::PARAM_BOOL)],
- [$this->equalTo('string'), $this->equalTo(IQueryBuilder::PARAM_STR)],
- [$this->equalTo(456), $this->equalTo(IQueryBuilder::PARAM_INT)],
- [$this->equalTo(false), $this->equalTo(IQueryBuilder::PARAM_BOOL)],
- [$this->equalTo(['hello' => 'world']), $this->equalTo(IQueryBuilder::PARAM_JSON)],
- [$this->equalTo($datetime), $this->equalTo(IQueryBuilder::PARAM_DATETIME_IMMUTABLE)],
- [$this->equalTo(789), $this->equalTo(IQueryBuilder::PARAM_INT)],
- );
-
+ ->willReturnCallback(function () use (&$createNamedParameterCalls): void {
+ $expected = array_shift($createNamedParameterCalls);
+ $this->assertEquals($expected, func_get_args());
+ });
+
+ $setCalls = [
+ ['int_prop', $intParam],
+ ['bool_prop', $boolParam],
+ ['string_prop', $stringParam],
+ ['integer_prop', $integerParam],
+ ['boolean_prop', $booleanParam],
+ ['json_prop', $datetimeParam],
+ ['datetime_prop', $datetimeParam],
+ ];
$this->qb->expects($this->exactly(7))
->method('set')
- ->withConsecutive(
- [$this->equalTo('int_prop'), $this->equalTo($intParam)],
- [$this->equalTo('bool_prop'), $this->equalTo($boolParam)],
- [$this->equalTo('string_prop'), $this->equalTo($stringParam)],
- [$this->equalTo('integer_prop'), $this->equalTo($integerParam)],
- [$this->equalTo('boolean_prop'), $this->equalTo($booleanParam)],
- [$this->equalTo('json_prop'), $this->equalTo($jsonParam)],
- [$this->equalTo('datetime_prop'), $this->equalTo($datetimeParam)],
- );
+ ->willReturnCallback(function () use (&$setCalls): void {
+ $expected = array_shift($setCalls);
+ $this->assertEquals($expected, func_get_args());
+ });
$this->expr->expects($this->once())
->method('eq')
@@ -196,7 +214,7 @@ class QBMapperTest extends \Test\TestCase {
$this->mapper->update($entity);
}
-
+
public function testGetParameterTypeForProperty(): void {
$entity = new QBTestEntity();
diff --git a/tests/lib/AppFramework/Db/TransactionalTest.php b/tests/lib/AppFramework/Db/TransactionalTest.php
index a60c4386fea..72a3d9ae59f 100644
--- a/tests/lib/AppFramework/Db/TransactionalTest.php
+++ b/tests/lib/AppFramework/Db/TransactionalTest.php
@@ -28,14 +28,13 @@ class TransactionalTest extends TestCase {
$test = new class($this->db) {
use TTransactional;
- private IDBConnection $db;
-
- public function __construct(IDBConnection $db) {
- $this->db = $db;
+ public function __construct(
+ private IDBConnection $db,
+ ) {
}
public function fail(): void {
- $this->atomic(function () {
+ $this->atomic(function (): void {
throw new RuntimeException('nope');
}, $this->db);
}
@@ -55,10 +54,9 @@ class TransactionalTest extends TestCase {
$test = new class($this->db) {
use TTransactional;
- private IDBConnection $db;
-
- public function __construct(IDBConnection $db) {
- $this->db = $db;
+ public function __construct(
+ private IDBConnection $db,
+ ) {
}
public function succeed(): int {
diff --git a/tests/lib/AppFramework/DependencyInjection/DIContainerTest.php b/tests/lib/AppFramework/DependencyInjection/DIContainerTest.php
index f3d2cff1ffd..e84b44db9a0 100644
--- a/tests/lib/AppFramework/DependencyInjection/DIContainerTest.php
+++ b/tests/lib/AppFramework/DependencyInjection/DIContainerTest.php
@@ -29,7 +29,7 @@ class DIContainerTest extends \Test\TestCase {
protected function setUp(): void {
parent::setUp();
$this->container = $this->getMockBuilder(DIContainer::class)
- ->setMethods(['isAdminUser'])
+ ->onlyMethods(['isAdminUser'])
->setConstructorArgs(['name'])
->getMock();
}
diff --git a/tests/lib/AppFramework/DependencyInjection/DIIntergrationTests.php b/tests/lib/AppFramework/DependencyInjection/DIIntergrationTests.php
index 54c691d2392..219fd5134ae 100644
--- a/tests/lib/AppFramework/DependencyInjection/DIIntergrationTests.php
+++ b/tests/lib/AppFramework/DependencyInjection/DIIntergrationTests.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2017 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
@@ -21,16 +22,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/ContentSecurityPolicyTest.php b/tests/lib/AppFramework/Http/ContentSecurityPolicyTest.php
index aa2b29418e4..75527e7eaf8 100644
--- a/tests/lib/AppFramework/Http/ContentSecurityPolicyTest.php
+++ b/tests/lib/AppFramework/Http/ContentSecurityPolicyTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
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 7415ecd9486..86c78e840e0 100644
--- a/tests/lib/AppFramework/Http/DispatcherTest.php
+++ b/tests/lib/AppFramework/Http/DispatcherTest.php
@@ -8,6 +8,7 @@
namespace Test\AppFramework\Http;
+use OC\AppFramework\DependencyInjection\DIContainer;
use OC\AppFramework\Http\Dispatcher;
use OC\AppFramework\Http\Request;
use OC\AppFramework\Middleware\MiddlewareDispatcher;
@@ -20,8 +21,10 @@ use OCP\AppFramework\Http\ParameterOutOfRangeException;
use OCP\AppFramework\Http\Response;
use OCP\Diagnostics\IEventLogger;
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;
@@ -29,7 +32,7 @@ use Psr\Log\LoggerInterface;
class TestController extends Controller {
/**
* @param string $appName
- * @param \OCP\IRequest $request
+ * @param IRequest $request
*/
public function __construct($appName, $request) {
parent::__construct($appName, $request);
@@ -63,6 +66,10 @@ class TestController extends Controller {
'text' => [$int, $bool, $test, $test2]
]);
}
+
+ public function test(): Response {
+ return new DataResponse();
+ }
}
/**
@@ -104,33 +111,17 @@ class DispatcherTest extends \Test\TestCase {
$this->logger = $this->createMock(LoggerInterface::class);
$this->eventLogger = $this->createMock(IEventLogger::class);
$this->container = $this->createMock(ContainerInterface::class);
- $app = $this->getMockBuilder(
- 'OC\AppFramework\DependencyInjection\DIContainer')
- ->disableOriginalConstructor()
- ->getMock();
- $request = $this->getMockBuilder(
- '\OC\AppFramework\Http\Request')
- ->disableOriginalConstructor()
- ->getMock();
- $this->http = $this->getMockBuilder(
- \OC\AppFramework\Http::class)
- ->disableOriginalConstructor()
- ->getMock();
+ $app = $this->createMock(DIContainer::class);
+ $request = $this->createMock(Request::class);
+ $this->http = $this->createMock(\OC\AppFramework\Http::class);
- $this->middlewareDispatcher = $this->getMockBuilder(
- '\OC\AppFramework\Middleware\MiddlewareDispatcher')
- ->disableOriginalConstructor()
- ->getMock();
- $this->controller = $this->getMockBuilder(
- '\OCP\AppFramework\Controller')
- ->setMethods([$this->controllerMethod])
+ $this->middlewareDispatcher = $this->createMock(MiddlewareDispatcher::class);
+ $this->controller = $this->getMockBuilder(TestController::class)
+ ->onlyMethods([$this->controllerMethod])
->setConstructorArgs([$app, $request])
->getMock();
- $this->request = $this->getMockBuilder(
- '\OC\AppFramework\Http\Request')
- ->disableOriginalConstructor()
- ->getMock();
+ $this->request = $this->createMock(Request::class);
$this->reflector = new ControllerMethodReflector();
@@ -140,7 +131,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,
@@ -166,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')
@@ -317,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
@@ -350,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
@@ -386,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
@@ -421,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
@@ -457,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
@@ -492,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
@@ -530,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
@@ -545,7 +536,7 @@ class DispatcherTest extends \Test\TestCase {
}
- public function rangeDataProvider(): array {
+ public static function rangeDataProvider(): array {
return [
[PHP_INT_MIN, PHP_INT_MAX, 42, false],
[0, 12, -5, true],
@@ -556,9 +547,7 @@ class DispatcherTest extends \Test\TestCase {
];
}
- /**
- * @dataProvider rangeDataProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('rangeDataProvider')]
public function testEnsureParameterValueSatisfiesRange(int $min, int $max, int $input, bool $throw): void {
$this->reflector = $this->createMock(ControllerMethodReflector::class);
$this->reflector->expects($this->any())
@@ -574,7 +563,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/DownloadResponseTest.php b/tests/lib/AppFramework/Http/DownloadResponseTest.php
index ee89e8e55d1..b2f60edd999 100644
--- a/tests/lib/AppFramework/Http/DownloadResponseTest.php
+++ b/tests/lib/AppFramework/Http/DownloadResponseTest.php
@@ -27,9 +27,7 @@ class DownloadResponseTest extends \Test\TestCase {
$this->assertEquals('content', $headers['Content-Type']);
}
- /**
- * @dataProvider filenameEncodingProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('filenameEncodingProvider')]
public function testFilenameEncoding(string $input, string $expected): void {
$response = new ChildDownloadResponse($input, 'content');
$headers = $response->getHeaders();
@@ -37,7 +35,7 @@ class DownloadResponseTest extends \Test\TestCase {
$this->assertEquals('attachment; filename="' . $expected . '"', $headers['Content-Disposition']);
}
- public function filenameEncodingProvider() : array {
+ public static function filenameEncodingProvider() : array {
return [
['TestName.txt', 'TestName.txt'],
['A "Quoted" Filename.txt', 'A \\"Quoted\\" Filename.txt'],
diff --git a/tests/lib/AppFramework/Http/EmptyContentSecurityPolicyTest.php b/tests/lib/AppFramework/Http/EmptyContentSecurityPolicyTest.php
index 3110f632fa7..66abce43cc4 100644
--- a/tests/lib/AppFramework/Http/EmptyContentSecurityPolicyTest.php
+++ b/tests/lib/AppFramework/Http/EmptyContentSecurityPolicyTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
diff --git a/tests/lib/AppFramework/Http/FileDisplayResponseTest.php b/tests/lib/AppFramework/Http/FileDisplayResponseTest.php
index 5f602b2e1c6..029ddaad712 100644
--- a/tests/lib/AppFramework/Http/FileDisplayResponseTest.php
+++ b/tests/lib/AppFramework/Http/FileDisplayResponseTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
diff --git a/tests/lib/AppFramework/Http/JSONResponseTest.php b/tests/lib/AppFramework/Http/JSONResponseTest.php
index 175ed852c7b..56f67b23f0d 100644
--- a/tests/lib/AppFramework/Http/JSONResponseTest.php
+++ b/tests/lib/AppFramework/Http/JSONResponseTest.php
@@ -46,10 +46,7 @@ class JSONResponseTest extends \Test\TestCase {
$this->assertEquals($expected, $this->json->render());
}
- /**
- * @return array
- */
- public function renderDataProvider() {
+ public static function renderDataProvider(): array {
return [
[
['test' => 'hi'], '{"test":"hi"}',
@@ -61,10 +58,10 @@ class JSONResponseTest extends \Test\TestCase {
}
/**
- * @dataProvider renderDataProvider
* @param array $input
* @param string $expected
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('renderDataProvider')]
public function testRender(array $input, $expected): void {
$this->json->setData($input);
$this->assertEquals($expected, $this->json->render());
diff --git a/tests/lib/AppFramework/Http/OutputTest.php b/tests/lib/AppFramework/Http/OutputTest.php
index 58b17c08141..2ba93833dd1 100644
--- a/tests/lib/AppFramework/Http/OutputTest.php
+++ b/tests/lib/AppFramework/Http/OutputTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
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/RequestStream.php b/tests/lib/AppFramework/Http/RequestStream.php
index 91259b26c9f..7340391b2d5 100644
--- a/tests/lib/AppFramework/Http/RequestStream.php
+++ b/tests/lib/AppFramework/Http/RequestStream.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
diff --git a/tests/lib/AppFramework/Http/RequestTest.php b/tests/lib/AppFramework/Http/RequestTest.php
index 781cca256ec..a7ff123fc25 100644
--- a/tests/lib/AppFramework/Http/RequestTest.php
+++ b/tests/lib/AppFramework/Http/RequestTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -259,9 +260,7 @@ class RequestTest extends \Test\TestCase {
];
}
- /**
- * @dataProvider dataNotJsonData
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataNotJsonData')]
public function testNotJsonPost(string $testData): void {
global $data;
$data = $testData;
@@ -708,9 +707,7 @@ class RequestTest extends \Test\TestCase {
];
}
- /**
- * @dataProvider dataGetRemoteAddress
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataGetRemoteAddress')]
public function testGetRemoteAddress(array $headers, array $trustedProxies, array $forwardedForHeaders, string $expected): void {
$this->config
->method('getSystemValue')
@@ -759,11 +756,11 @@ class RequestTest extends \Test\TestCase {
}
/**
- * @dataProvider dataHttpProtocol
*
* @param mixed $input
* @param string $expected
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataHttpProtocol')]
public function testGetHttpProtocol($input, $expected): void {
$request = new Request(
[
@@ -949,11 +946,11 @@ class RequestTest extends \Test\TestCase {
}
/**
- * @dataProvider dataUserAgent
* @param string $testAgent
* @param array $userAgent
* @param bool $matches
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataUserAgent')]
public function testUserAgent($testAgent, $userAgent, $matches): void {
$request = new Request(
[
@@ -971,11 +968,11 @@ class RequestTest extends \Test\TestCase {
}
/**
- * @dataProvider dataUserAgent
* @param string $testAgent
* @param array $userAgent
* @param bool $matches
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataUserAgent')]
public function testUndefinedUserAgent($testAgent, $userAgent, $matches): void {
$request = new Request(
[],
@@ -1153,11 +1150,11 @@ class RequestTest extends \Test\TestCase {
}
/**
- * @dataProvider dataMatchClientVersion
* @param string $testAgent
* @param string $userAgent
* @param string $version
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataMatchClientVersion')]
public function testMatchClientVersion(string $testAgent, string $userAgent, string $version): void {
preg_match($userAgent, $testAgent, $matches);
@@ -1372,9 +1369,7 @@ class RequestTest extends \Test\TestCase {
];
}
- /**
- * @dataProvider dataGetServerHostTrustedDomain
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataGetServerHostTrustedDomain')]
public function testGetServerHostTrustedDomain(string $expected, $trustedDomain): void {
$this->config
->method('getSystemValue')
@@ -1484,11 +1479,11 @@ class RequestTest extends \Test\TestCase {
}
/**
- * @dataProvider dataGenericPathInfo
* @param string $requestUri
* @param string $scriptName
* @param string $expected
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataGenericPathInfo')]
public function testGetPathInfoWithoutSetEnvGeneric($requestUri, $scriptName, $expected): void {
$request = new Request(
[
@@ -1507,11 +1502,11 @@ class RequestTest extends \Test\TestCase {
}
/**
- * @dataProvider dataGenericPathInfo
* @param string $requestUri
* @param string $scriptName
* @param string $expected
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataGenericPathInfo')]
public function testGetRawPathInfoWithoutSetEnvGeneric($requestUri, $scriptName, $expected): void {
$request = new Request(
[
@@ -1530,11 +1525,11 @@ class RequestTest extends \Test\TestCase {
}
/**
- * @dataProvider dataRawPathInfo
* @param string $requestUri
* @param string $scriptName
* @param string $expected
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataRawPathInfo')]
public function testGetRawPathInfoWithoutSetEnv($requestUri, $scriptName, $expected): void {
$request = new Request(
[
@@ -1553,11 +1548,11 @@ class RequestTest extends \Test\TestCase {
}
/**
- * @dataProvider dataPathInfo
* @param string $requestUri
* @param string $scriptName
* @param string $expected
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataPathInfo')]
public function testGetPathInfoWithoutSetEnv($requestUri, $scriptName, $expected): void {
$request = new Request(
[
@@ -1628,9 +1623,7 @@ class RequestTest extends \Test\TestCase {
];
}
- /**
- * @dataProvider dataGetRequestUriWithOverwrite
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataGetRequestUriWithOverwrite')]
public function testGetRequestUriWithOverwrite($expectedUri, $overwriteWebRoot, $overwriteCondAddr, $remoteAddr = ''): void {
$this->config
->expects($this->exactly(2))
@@ -2183,9 +2176,7 @@ class RequestTest extends \Test\TestCase {
];
}
- /**
- * @dataProvider dataInvalidToken
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataInvalidToken')]
public function testPassesCSRFCheckWithInvalidToken(string $invalidToken): void {
/** @var Request $request */
$request = $this->getMockBuilder(Request::class)
diff --git a/tests/lib/AppFramework/Http/ResponseTest.php b/tests/lib/AppFramework/Http/ResponseTest.php
index 28614b14b40..4c76695f6e4 100644
--- a/tests/lib/AppFramework/Http/ResponseTest.php
+++ b/tests/lib/AppFramework/Http/ResponseTest.php
@@ -9,12 +9,14 @@
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;
class ResponseTest extends \Test\TestCase {
/**
- * @var \OCP\AppFramework\Http\Response
+ * @var Response
*/
private $childResponse;
@@ -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 {
@@ -229,7 +231,7 @@ class ResponseTest extends \Test\TestCase {
$headers = $this->childResponse->getHeaders();
$this->assertEquals('private, max-age=33, must-revalidate', $headers['Cache-Control']);
- $this->assertEquals('Thu, 15 Jan 1970 06:56:40 +0000', $headers['Expires']);
+ $this->assertEquals('Thu, 15 Jan 1970 06:56:40 GMT', $headers['Expires']);
}
@@ -239,7 +241,7 @@ class ResponseTest extends \Test\TestCase {
$lastModified->setTimestamp(1);
$this->childResponse->setLastModified($lastModified);
$headers = $this->childResponse->getHeaders();
- $this->assertEquals('Thu, 01 Jan 1970 00:00:01 +0000', $headers['Last-Modified']);
+ $this->assertEquals('Thu, 01 Jan 1970 00:00:01 GMT', $headers['Last-Modified']);
}
public function testChainability(): void {
@@ -257,7 +259,7 @@ class ResponseTest extends \Test\TestCase {
$this->assertEquals('world', $headers['hello']);
$this->assertEquals(Http::STATUS_NOT_FOUND, $this->childResponse->getStatus());
$this->assertEquals('hi', $this->childResponse->getEtag());
- $this->assertEquals('Thu, 01 Jan 1970 00:00:01 +0000', $headers['Last-Modified']);
+ $this->assertEquals('Thu, 01 Jan 1970 00:00:01 GMT', $headers['Last-Modified']);
$this->assertEquals('private, max-age=33, must-revalidate',
$headers['Cache-Control']);
}
diff --git a/tests/lib/AppFramework/Http/TemplateResponseTest.php b/tests/lib/AppFramework/Http/TemplateResponseTest.php
index ad0fe808b76..28f952e35e3 100644
--- a/tests/lib/AppFramework/Http/TemplateResponseTest.php
+++ b/tests/lib/AppFramework/Http/TemplateResponseTest.php
@@ -13,7 +13,7 @@ use OCP\AppFramework\Http\TemplateResponse;
class TemplateResponseTest extends \Test\TestCase {
/**
- * @var \OCP\AppFramework\Http\TemplateResponse
+ * @var TemplateResponse
*/
private $tpl;
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 fae5f5d9f1c..aae1c53456b 100644
--- a/tests/lib/AppFramework/Middleware/MiddlewareDispatcherTest.php
+++ b/tests/lib/AppFramework/Middleware/MiddlewareDispatcherTest.php
@@ -10,6 +10,7 @@ namespace Test\AppFramework\Middleware;
use OC\AppFramework\Http\Request;
use OC\AppFramework\Middleware\MiddlewareDispatcher;
+use OCP\AppFramework\Controller;
use OCP\AppFramework\Http\Response;
use OCP\AppFramework\Middleware;
use OCP\IConfig;
@@ -33,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) {
@@ -84,6 +84,10 @@ class TestMiddleware extends Middleware {
}
}
+class TestController extends Controller {
+ public function method(): void {
+ }
+}
class MiddlewareDispatcherTest extends \Test\TestCase {
public $exception;
@@ -110,8 +114,8 @@ class MiddlewareDispatcherTest extends \Test\TestCase {
private function getControllerMock() {
- return $this->getMockBuilder('OCP\AppFramework\Controller')
- ->setMethods(['method'])
+ return $this->getMockBuilder(TestController::class)
+ ->onlyMethods(['method'])
->setConstructorArgs(['app',
new Request(
['method' => 'GET'],
@@ -131,14 +135,14 @@ class MiddlewareDispatcherTest extends \Test\TestCase {
public function testAfterExceptionShouldReturnResponseOfMiddleware(): void {
$response = new Response();
- $m1 = $this->getMockBuilder('\OCP\AppFramework\Middleware')
- ->setMethods(['afterException', 'beforeController'])
+ $m1 = $this->getMockBuilder(Middleware::class)
+ ->onlyMethods(['afterException', 'beforeController'])
->getMock();
$m1->expects($this->never())
->method('afterException');
- $m2 = $this->getMockBuilder('OCP\AppFramework\Middleware')
- ->setMethods(['afterException', 'beforeController'])
+ $m2 = $this->getMockBuilder(Middleware::class)
+ ->onlyMethods(['afterException', 'beforeController'])
->getMock();
$m2->expects($this->once())
->method('afterException')
diff --git a/tests/lib/AppFramework/Middleware/MiddlewareTest.php b/tests/lib/AppFramework/Middleware/MiddlewareTest.php
index c1e5c44c4db..addd9683122 100644
--- a/tests/lib/AppFramework/Middleware/MiddlewareTest.php
+++ b/tests/lib/AppFramework/Middleware/MiddlewareTest.php
@@ -36,12 +36,9 @@ class MiddlewareTest extends \Test\TestCase {
$this->middleware = new ChildMiddleware();
- $this->api = $this->getMockBuilder(DIContainer::class)
- ->disableOriginalConstructor()
- ->getMock();
+ $this->api = $this->createMock(DIContainer::class);
$this->controller = $this->getMockBuilder(Controller::class)
- ->setMethods([])
->setConstructorArgs([
$this->api,
new Request(
@@ -51,7 +48,7 @@ class MiddlewareTest extends \Test\TestCase {
)
])->getMock();
$this->exception = new \Exception();
- $this->response = $this->getMockBuilder(Response::class)->getMock();
+ $this->response = $this->createMock(Response::class);
}
diff --git a/tests/lib/AppFramework/Middleware/NotModifiedMiddlewareTest.php b/tests/lib/AppFramework/Middleware/NotModifiedMiddlewareTest.php
index 58ae6b13aed..7dcb28a2af4 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 {
@@ -32,7 +33,7 @@ class NotModifiedMiddlewareTest extends \Test\TestCase {
$this->controller = $this->createMock(Controller::class);
}
- public function dataModified(): array {
+ public static function dataModified(): array {
$now = new \DateTime();
return [
@@ -43,19 +44,17 @@ class NotModifiedMiddlewareTest extends \Test\TestCase {
[null, '"etag"', null, '', false],
['etag', '"etag"', null, '', true],
- [null, '', $now, $now->format(\DateTimeInterface::RFC2822), true],
+ [null, '', $now, $now->format(\DateTimeInterface::RFC7231), true],
[null, '', $now, $now->format(\DateTimeInterface::ATOM), false],
- [null, '', null, $now->format(\DateTimeInterface::RFC2822), false],
+ [null, '', null, $now->format(\DateTimeInterface::RFC7231), false],
[null, '', $now, '', false],
['etag', '"etag"', $now, $now->format(\DateTimeInterface::ATOM), true],
- ['etag', '"etag"', $now, $now->format(\DateTimeInterface::RFC2822), true],
+ ['etag', '"etag"', $now, $now->format(\DateTimeInterface::RFC7231), true],
];
}
- /**
- * @dataProvider dataModified
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataModified')]
public function testMiddleware(?string $etag, string $etagHeader, ?\DateTime $lastModified, string $lastModifiedHeader, bool $notModifiedSet): void {
$this->request->method('getHeader')
->willReturnCallback(function (string $name) use ($etagHeader, $lastModifiedHeader) {
@@ -68,7 +67,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 6724f841c5e..e5c6a417a4b 100644
--- a/tests/lib/AppFramework/Middleware/OCSMiddlewareTest.php
+++ b/tests/lib/AppFramework/Middleware/OCSMiddlewareTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
@@ -12,6 +13,8 @@ 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;
use OCP\AppFramework\OCS\OCSForbiddenException;
@@ -32,49 +35,35 @@ class OCSMiddlewareTest extends \Test\TestCase {
->getMock();
}
- public function dataAfterException() {
- $OCSController = $this->getMockBuilder(OCSController::class)
- ->disableOriginalConstructor()
- ->getMock();
- $controller = $this->getMockBuilder(Controller::class)
- ->disableOriginalConstructor()
- ->getMock();
-
+ public static function dataAfterException(): array {
return [
- [$OCSController, new \Exception(), true],
- [$OCSController, new OCSException(), false, '', Http::STATUS_INTERNAL_SERVER_ERROR],
- [$OCSController, new OCSException('foo'), false, 'foo', Http::STATUS_INTERNAL_SERVER_ERROR],
- [$OCSController, new OCSException('foo', Http::STATUS_IM_A_TEAPOT), false, 'foo', Http::STATUS_IM_A_TEAPOT],
- [$OCSController, new OCSBadRequestException(), false, '', Http::STATUS_BAD_REQUEST],
- [$OCSController, new OCSBadRequestException('foo'), false, 'foo', Http::STATUS_BAD_REQUEST],
- [$OCSController, new OCSForbiddenException(), false, '', Http::STATUS_FORBIDDEN],
- [$OCSController, new OCSForbiddenException('foo'), false, 'foo', Http::STATUS_FORBIDDEN],
- [$OCSController, new OCSNotFoundException(), false, '', Http::STATUS_NOT_FOUND],
- [$OCSController, new OCSNotFoundException('foo'), false, 'foo', Http::STATUS_NOT_FOUND],
-
- [$controller, new \Exception(), true],
- [$controller, new OCSException(), true],
- [$controller, new OCSException('foo'), true],
- [$controller, new OCSException('foo', Http::STATUS_IM_A_TEAPOT), true],
- [$controller, new OCSBadRequestException(), true],
- [$controller, new OCSBadRequestException('foo'), true],
- [$controller, new OCSForbiddenException(), true],
- [$controller, new OCSForbiddenException('foo'), true],
- [$controller, new OCSNotFoundException(), true],
- [$controller, new OCSNotFoundException('foo'), true],
+ [OCSController::class, new \Exception(), true],
+ [OCSController::class, new OCSException(), false, '', Http::STATUS_INTERNAL_SERVER_ERROR],
+ [OCSController::class, new OCSException('foo'), false, 'foo', Http::STATUS_INTERNAL_SERVER_ERROR],
+ [OCSController::class, new OCSException('foo', Http::STATUS_IM_A_TEAPOT), false, 'foo', Http::STATUS_IM_A_TEAPOT],
+ [OCSController::class, new OCSBadRequestException(), false, '', Http::STATUS_BAD_REQUEST],
+ [OCSController::class, new OCSBadRequestException('foo'), false, 'foo', Http::STATUS_BAD_REQUEST],
+ [OCSController::class, new OCSForbiddenException(), false, '', Http::STATUS_FORBIDDEN],
+ [OCSController::class, new OCSForbiddenException('foo'), false, 'foo', Http::STATUS_FORBIDDEN],
+ [OCSController::class, new OCSNotFoundException(), false, '', Http::STATUS_NOT_FOUND],
+ [OCSController::class, new OCSNotFoundException('foo'), false, 'foo', Http::STATUS_NOT_FOUND],
+
+ [Controller::class, new \Exception(), true],
+ [Controller::class, new OCSException(), true],
+ [Controller::class, new OCSException('foo'), true],
+ [Controller::class, new OCSException('foo', Http::STATUS_IM_A_TEAPOT), true],
+ [Controller::class, new OCSBadRequestException(), true],
+ [Controller::class, new OCSBadRequestException('foo'), true],
+ [Controller::class, new OCSForbiddenException(), true],
+ [Controller::class, new OCSForbiddenException('foo'), true],
+ [Controller::class, new OCSNotFoundException(), true],
+ [Controller::class, new OCSNotFoundException('foo'), true],
];
}
- /**
- * @dataProvider dataAfterException
- *
- * @param Controller $controller
- * @param \Exception $exception
- * @param bool $forward
- * @param string $message
- * @param int $code
- */
- public function testAfterExceptionOCSv1($controller, $exception, $forward, $message = '', $code = 0): void {
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataAfterException')]
+ public function testAfterExceptionOCSv1(string $controller, \Exception $exception, bool $forward, string $message = '', int $code = 0): void {
+ $controller = $this->createMock($controller);
$this->request
->method('getScriptName')
->willReturn('/ocs/v1.php');
@@ -93,7 +82,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());
}
@@ -101,16 +90,9 @@ class OCSMiddlewareTest extends \Test\TestCase {
$this->assertSame(Http::STATUS_OK, $result->getStatus());
}
- /**
- * @dataProvider dataAfterException
- *
- * @param Controller $controller
- * @param \Exception $exception
- * @param bool $forward
- * @param string $message
- * @param int $code
- */
- public function testAfterExceptionOCSv2($controller, $exception, $forward, $message = '', $code = 0): void {
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataAfterException')]
+ public function testAfterExceptionOCSv2(string $controller, \Exception $exception, bool $forward, string $message = '', int $code = 0): void {
+ $controller = $this->createMock($controller);
$this->request
->method('getScriptName')
->willReturn('/ocs/v2.php');
@@ -128,23 +110,16 @@ 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());
}
$this->assertSame($code, $result->getStatus());
}
- /**
- * @dataProvider dataAfterException
- *
- * @param Controller $controller
- * @param \Exception $exception
- * @param bool $forward
- * @param string $message
- * @param int $code
- */
- public function testAfterExceptionOCSv2SubFolder($controller, $exception, $forward, $message = '', $code = 0): void {
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataAfterException')]
+ public function testAfterExceptionOCSv2SubFolder(string $controller, \Exception $exception, bool $forward, string $message = '', int $code = 0): void {
+ $controller = $this->createMock($controller);
$this->request
->method('getScriptName')
->willReturn('/mysubfolder/ocs/v2.php');
@@ -152,7 +127,7 @@ class OCSMiddlewareTest extends \Test\TestCase {
$OCSMiddleware->beforeController($controller, 'method');
if ($forward) {
- $this->expectException(get_class($exception));
+ $this->expectException($exception::class);
$this->expectExceptionMessage($exception->getMessage());
}
@@ -162,46 +137,33 @@ 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());
}
$this->assertSame($code, $result->getStatus());
}
- public function dataAfterController() {
- $OCSController = $this->getMockBuilder(OCSController::class)
- ->disableOriginalConstructor()
- ->getMock();
- $controller = $this->getMockBuilder(Controller::class)
- ->disableOriginalConstructor()
- ->getMock();
-
+ public static function dataAfterController(): array {
return [
- [$OCSController, new Http\Response(), false],
- [$OCSController, new Http\JSONResponse(), false],
- [$OCSController, new Http\JSONResponse(['message' => 'foo']), false],
- [$OCSController, new Http\JSONResponse(['message' => 'foo'], Http::STATUS_UNAUTHORIZED), true, OCSController::RESPOND_UNAUTHORISED],
- [$OCSController, new Http\JSONResponse(['message' => 'foo'], Http::STATUS_FORBIDDEN), true],
-
- [$controller, new Http\Response(), false],
- [$controller, new Http\JSONResponse(), false],
- [$controller, new Http\JSONResponse(['message' => 'foo']), false],
- [$controller, new Http\JSONResponse(['message' => 'foo'], Http::STATUS_UNAUTHORIZED), false],
- [$controller, new Http\JSONResponse(['message' => 'foo'], Http::STATUS_FORBIDDEN), false],
+ [OCSController::class, new Response(), false],
+ [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 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],
];
}
- /**
- * @dataProvider dataAfterController
- *
- * @param Controller $controller
- * @param Http\Response $response
- * @param bool $converted
- * @param int $convertedOCSStatus
- */
- public function testAfterController($controller, $response, $converted, $convertedOCSStatus = 0): void {
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataAfterController')]
+ public function testAfterController(string $controller, Response $response, bool $converted, int $convertedOCSStatus = 0): void {
+ $controller = $this->createMock($controller);
$OCSMiddleware = new OCSMiddleware($this->request);
$newResponse = $OCSMiddleware->afterController($controller, 'foo', $response);
diff --git a/tests/lib/AppFramework/Middleware/PublicShare/PublicShareMiddlewareTest.php b/tests/lib/AppFramework/Middleware/PublicShare/PublicShareMiddlewareTest.php
index 8433aa93f4a..e87ee7fd565 100644
--- a/tests/lib/AppFramework/Middleware/PublicShare/PublicShareMiddlewareTest.php
+++ b/tests/lib/AppFramework/Middleware/PublicShare/PublicShareMiddlewareTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2018 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
@@ -58,7 +59,7 @@ class PublicShareMiddlewareTest extends \Test\TestCase {
$this->assertTrue(true);
}
- public function dataShareApi() {
+ public static function dataShareApi(): array {
return [
['no', 'no',],
['no', 'yes',],
@@ -66,9 +67,7 @@ class PublicShareMiddlewareTest extends \Test\TestCase {
];
}
- /**
- * @dataProvider dataShareApi
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataShareApi')]
public function testBeforeControllerShareApiDisabled(string $shareApi, string $shareLinks): void {
$controller = $this->createMock(PublicShareController::class);
diff --git a/tests/lib/AppFramework/Middleware/Security/BruteForceMiddlewareTest.php b/tests/lib/AppFramework/Middleware/Security/BruteForceMiddlewareTest.php
index a224ebae949..3fd2cb38a33 100644
--- a/tests/lib/AppFramework/Middleware/Security/BruteForceMiddlewareTest.php
+++ b/tests/lib/AppFramework/Middleware/Security/BruteForceMiddlewareTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2017 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
@@ -98,13 +99,19 @@ class BruteForceMiddlewareTest extends TestCase {
->expects($this->once())
->method('getRemoteAddress')
->willReturn('::1');
+
+ $calls = [
+ ['::1', 'first'],
+ ['::1', 'second'],
+ ];
$this->throttler
->expects($this->exactly(2))
->method('sleepDelayOrThrowOnMax')
- ->withConsecutive(
- ['::1', 'first'],
- ['::1', 'second'],
- );
+ ->willReturnCallback(function () use (&$calls) {
+ $expected = array_shift($calls);
+ $this->assertEquals($expected, func_get_args());
+ return 0;
+ });
$controller = new TestController('test', $this->request);
$this->reflector->reflect($controller, 'multipleAttributes');
@@ -221,20 +228,31 @@ class BruteForceMiddlewareTest extends TestCase {
->expects($this->once())
->method('getRemoteAddress')
->willReturn('::1');
+
+ $sleepCalls = [
+ ['::1', 'first'],
+ ['::1', 'second'],
+ ];
$this->throttler
->expects($this->exactly(2))
->method('sleepDelayOrThrowOnMax')
- ->withConsecutive(
- ['::1', 'first'],
- ['::1', 'second'],
- );
+ ->willReturnCallback(function () use (&$sleepCalls) {
+ $expected = array_shift($sleepCalls);
+ $this->assertEquals($expected, func_get_args());
+ return 0;
+ });
+
+ $attemptCalls = [
+ ['first', '::1', []],
+ ['second', '::1', []],
+ ];
$this->throttler
->expects($this->exactly(2))
->method('registerAttempt')
- ->withConsecutive(
- ['first', '::1'],
- ['second', '::1'],
- );
+ ->willReturnCallback(function () use (&$attemptCalls): void {
+ $expected = array_shift($attemptCalls);
+ $this->assertEquals($expected, func_get_args());
+ });
$controller = new TestController('test', $this->request);
$this->reflector->reflect($controller, 'multipleAttributes');
diff --git a/tests/lib/AppFramework/Middleware/Security/CORSMiddlewareTest.php b/tests/lib/AppFramework/Middleware/Security/CORSMiddlewareTest.php
index b703b10c554..c325ae638fb 100644
--- a/tests/lib/AppFramework/Middleware/Security/CORSMiddlewareTest.php
+++ b/tests/lib/AppFramework/Middleware/Security/CORSMiddlewareTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2023 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2014-2016 ownCloud, Inc.
@@ -10,6 +11,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;
@@ -44,16 +46,14 @@ class CORSMiddlewareTest extends \Test\TestCase {
);
}
- public function dataSetCORSAPIHeader(): array {
+ public static function dataSetCORSAPIHeader(): array {
return [
['testSetCORSAPIHeader'],
['testSetCORSAPIHeaderAttribute'],
];
}
- /**
- * @dataProvider dataSetCORSAPIHeader
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataSetCORSAPIHeader')]
public function testSetCORSAPIHeader(string $method): void {
$request = new Request(
[
@@ -89,16 +89,14 @@ class CORSMiddlewareTest extends \Test\TestCase {
$this->assertFalse(array_key_exists('Access-Control-Allow-Origin', $headers));
}
- public function dataNoOriginHeaderNoCORSHEADER(): array {
+ public static function dataNoOriginHeaderNoCORSHEADER(): array {
return [
['testNoOriginHeaderNoCORSHEADER'],
['testNoOriginHeaderNoCORSHEADERAttribute'],
];
}
- /**
- * @dataProvider dataNoOriginHeaderNoCORSHEADER
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataNoOriginHeaderNoCORSHEADER')]
public function testNoOriginHeaderNoCORSHEADER(string $method): void {
$request = new Request(
[],
@@ -113,18 +111,16 @@ class CORSMiddlewareTest extends \Test\TestCase {
$this->assertFalse(array_key_exists('Access-Control-Allow-Origin', $headers));
}
- public function dataCorsIgnoredIfWithCredentialsHeaderPresent(): array {
+ public static function dataCorsIgnoredIfWithCredentialsHeaderPresent(): array {
return [
['testCorsIgnoredIfWithCredentialsHeaderPresent'],
['testCorsAttributeIgnoredIfWithCredentialsHeaderPresent'],
];
}
- /**
- * @dataProvider dataCorsIgnoredIfWithCredentialsHeaderPresent
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataCorsIgnoredIfWithCredentialsHeaderPresent')]
public function testCorsIgnoredIfWithCredentialsHeaderPresent(string $method): void {
- $this->expectException(\OC\AppFramework\Middleware\Security\Exceptions\SecurityException::class);
+ $this->expectException(SecurityException::class);
$request = new Request(
[
@@ -143,7 +139,7 @@ class CORSMiddlewareTest extends \Test\TestCase {
$middleware->afterController($this->controller, $method, $response);
}
- public function dataNoCORSOnAnonymousPublicPage(): array {
+ public static function dataNoCORSOnAnonymousPublicPage(): array {
return [
['testNoCORSOnAnonymousPublicPage'],
['testNoCORSOnAnonymousPublicPageAttribute'],
@@ -152,9 +148,7 @@ class CORSMiddlewareTest extends \Test\TestCase {
];
}
- /**
- * @dataProvider dataNoCORSOnAnonymousPublicPage
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataNoCORSOnAnonymousPublicPage')]
public function testNoCORSOnAnonymousPublicPage(string $method): void {
$request = new Request(
[],
@@ -177,7 +171,7 @@ class CORSMiddlewareTest extends \Test\TestCase {
$middleware->beforeController($this->controller, $method);
}
- public function dataCORSShouldNeverAllowCookieAuth(): array {
+ public static function dataCORSShouldNeverAllowCookieAuth(): array {
return [
['testCORSShouldNeverAllowCookieAuth'],
['testCORSShouldNeverAllowCookieAuthAttribute'],
@@ -186,9 +180,7 @@ class CORSMiddlewareTest extends \Test\TestCase {
];
}
- /**
- * @dataProvider dataCORSShouldNeverAllowCookieAuth
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataCORSShouldNeverAllowCookieAuth')]
public function testCORSShouldNeverAllowCookieAuth(string $method): void {
$request = new Request(
[],
@@ -211,16 +203,14 @@ class CORSMiddlewareTest extends \Test\TestCase {
$middleware->beforeController($this->controller, $method);
}
- public function dataCORSShouldRelogin(): array {
+ public static function dataCORSShouldRelogin(): array {
return [
['testCORSShouldRelogin'],
['testCORSAttributeShouldRelogin'],
];
}
- /**
- * @dataProvider dataCORSShouldRelogin
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataCORSShouldRelogin')]
public function testCORSShouldRelogin(string $method): void {
$request = new Request(
['server' => [
@@ -242,18 +232,16 @@ class CORSMiddlewareTest extends \Test\TestCase {
$middleware->beforeController($this->controller, $method);
}
- public function dataCORSShouldFailIfPasswordLoginIsForbidden(): array {
+ public static function dataCORSShouldFailIfPasswordLoginIsForbidden(): array {
return [
['testCORSShouldFailIfPasswordLoginIsForbidden'],
['testCORSAttributeShouldFailIfPasswordLoginIsForbidden'],
];
}
- /**
- * @dataProvider dataCORSShouldFailIfPasswordLoginIsForbidden
- */
+ #[\PHPUnit\Framework\Attributes\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,25 +256,23 @@ 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);
$middleware->beforeController($this->controller, $method);
}
- public function dataCORSShouldNotAllowCookieAuth(): array {
+ public static function dataCORSShouldNotAllowCookieAuth(): array {
return [
['testCORSShouldNotAllowCookieAuth'],
['testCORSAttributeShouldNotAllowCookieAuth'],
];
}
- /**
- * @dataProvider dataCORSShouldNotAllowCookieAuth
- */
+ #[\PHPUnit\Framework\Attributes\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/PasswordConfirmationMiddlewareTest.php b/tests/lib/AppFramework/Middleware/Security/PasswordConfirmationMiddlewareTest.php
index 3dec030d438..90e801ca471 100644
--- a/tests/lib/AppFramework/Middleware/Security/PasswordConfirmationMiddlewareTest.php
+++ b/tests/lib/AppFramework/Middleware/Security/PasswordConfirmationMiddlewareTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2018 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
@@ -90,9 +91,7 @@ class PasswordConfirmationMiddlewareTest extends TestCase {
$this->middleware->beforeController($this->controller, __FUNCTION__);
}
- /**
- * @dataProvider dataProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataProvider')]
public function testAnnotation($backend, $lastConfirm, $currentTime, $exception): void {
$this->reflector->reflect($this->controller, __FUNCTION__);
@@ -125,9 +124,7 @@ class PasswordConfirmationMiddlewareTest extends TestCase {
$this->assertSame($exception, $thrown);
}
- /**
- * @dataProvider dataProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataProvider')]
public function testAttribute($backend, $lastConfirm, $currentTime, $exception): void {
$this->reflector->reflect($this->controller, __FUNCTION__);
@@ -162,7 +159,7 @@ class PasswordConfirmationMiddlewareTest extends TestCase {
- public function dataProvider() {
+ public static function dataProvider(): array {
return [
['foo', 2000, 4000, true],
['foo', 2000, 3000, false],
diff --git a/tests/lib/AppFramework/Middleware/Security/SameSiteCookieMiddlewareTest.php b/tests/lib/AppFramework/Middleware/Security/SameSiteCookieMiddlewareTest.php
index 0ca4a455cba..7800371f68f 100644
--- a/tests/lib/AppFramework/Middleware/Security/SameSiteCookieMiddlewareTest.php
+++ b/tests/lib/AppFramework/Middleware/Security/SameSiteCookieMiddlewareTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2017 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
@@ -103,7 +104,7 @@ class SameSiteCookieMiddlewareTest extends TestCase {
$middleware = $this->getMockBuilder(SameSiteCookieMiddleware::class)
->setConstructorArgs([$this->request, $this->reflector])
- ->setMethods(['setSameSiteCookie'])
+ ->onlyMethods(['setSameSiteCookie'])
->getMock();
$middleware->expects($this->once())
diff --git a/tests/lib/AppFramework/Middleware/Security/SecurityMiddlewareTest.php b/tests/lib/AppFramework/Middleware/Security/SecurityMiddlewareTest.php
index 07e368fd1e6..0c6fc21357d 100644
--- a/tests/lib/AppFramework/Middleware/Security/SecurityMiddlewareTest.php
+++ b/tests/lib/AppFramework/Middleware/Security/SecurityMiddlewareTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -125,7 +126,7 @@ class SecurityMiddlewareTest extends \Test\TestCase {
);
}
- public function dataNoCSRFRequiredPublicPage(): array {
+ public static function dataNoCSRFRequiredPublicPage(): array {
return [
['testAnnotationNoCSRFRequiredPublicPage'],
['testAnnotationNoCSRFRequiredAttributePublicPage'],
@@ -134,21 +135,21 @@ class SecurityMiddlewareTest extends \Test\TestCase {
];
}
- public function dataPublicPage(): array {
+ public static function dataPublicPage(): array {
return [
['testAnnotationPublicPage'],
['testAttributePublicPage'],
];
}
- public function dataNoCSRFRequired(): array {
+ public static function dataNoCSRFRequired(): array {
return [
['testAnnotationNoCSRFRequired'],
['testAttributeNoCSRFRequired'],
];
}
- public function dataPublicPageStrictCookieRequired(): array {
+ public static function dataPublicPageStrictCookieRequired(): array {
return [
['testAnnotationPublicPageStrictCookieRequired'],
['testAnnotationStrictCookieRequiredAttributePublicPage'],
@@ -157,28 +158,28 @@ class SecurityMiddlewareTest extends \Test\TestCase {
];
}
- public function dataNoCSRFRequiredPublicPageStrictCookieRequired(): array {
+ public static function dataNoCSRFRequiredPublicPageStrictCookieRequired(): array {
return [
['testAnnotationNoCSRFRequiredPublicPageStrictCookieRequired'],
['testAttributeNoCSRFRequiredPublicPageStrictCookiesRequired'],
];
}
- public function dataNoAdminRequiredNoCSRFRequired(): array {
+ public static function dataNoAdminRequiredNoCSRFRequired(): array {
return [
['testAnnotationNoAdminRequiredNoCSRFRequired'],
['testAttributeNoAdminRequiredNoCSRFRequired'],
];
}
- public function dataNoAdminRequiredNoCSRFRequiredPublicPage(): array {
+ public static function dataNoAdminRequiredNoCSRFRequiredPublicPage(): array {
return [
['testAnnotationNoAdminRequiredNoCSRFRequiredPublicPage'],
['testAttributeNoAdminRequiredNoCSRFRequiredPublicPage'],
];
}
- public function dataNoCSRFRequiredSubAdminRequired(): array {
+ public static function dataNoCSRFRequiredSubAdminRequired(): array {
return [
['testAnnotationNoCSRFRequiredSubAdminRequired'],
['testAnnotationNoCSRFRequiredAttributeSubAdminRequired'],
@@ -194,9 +195,7 @@ class SecurityMiddlewareTest extends \Test\TestCase {
];
}
- /**
- * @dataProvider dataNoCSRFRequiredPublicPage
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataNoCSRFRequiredPublicPage')]
public function testSetNavigationEntry(string $method): void {
$this->navigationManager->expects($this->once())
->method('setActiveEntry')
@@ -244,9 +243,7 @@ class SecurityMiddlewareTest extends \Test\TestCase {
);
}
- /**
- * @dataProvider dataNoCSRFRequired
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataNoCSRFRequired')]
public function testAjaxNotAdminCheck(string $method): void {
$this->ajaxExceptionStatus(
$method,
@@ -255,9 +252,7 @@ class SecurityMiddlewareTest extends \Test\TestCase {
);
}
- /**
- * @dataProvider dataPublicPage
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataPublicPage')]
public function testAjaxStatusCSRFCheck(string $method): void {
$this->ajaxExceptionStatus(
$method,
@@ -266,9 +261,7 @@ class SecurityMiddlewareTest extends \Test\TestCase {
);
}
- /**
- * @dataProvider dataNoCSRFRequiredPublicPage
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataNoCSRFRequiredPublicPage')]
public function testAjaxStatusAllGood(string $method): void {
$this->ajaxExceptionStatus(
$method,
@@ -287,9 +280,7 @@ class SecurityMiddlewareTest extends \Test\TestCase {
);
}
- /**
- * @dataProvider dataNoCSRFRequiredPublicPage
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataNoCSRFRequiredPublicPage')]
public function testNoChecks(string $method): void {
$this->request->expects($this->never())
->method('passesCSRFCheck')
@@ -328,11 +319,9 @@ class SecurityMiddlewareTest extends \Test\TestCase {
}
- /**
- * @dataProvider dataPublicPage
- */
+ #[\PHPUnit\Framework\Attributes\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')
@@ -344,9 +333,7 @@ class SecurityMiddlewareTest extends \Test\TestCase {
$this->middleware->beforeController($this->controller, $method);
}
- /**
- * @dataProvider dataNoCSRFRequiredPublicPage
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataNoCSRFRequiredPublicPage')]
public function testNoCsrfCheck(string $method): void {
$this->request->expects($this->never())
->method('passesCSRFCheck')
@@ -356,9 +343,7 @@ class SecurityMiddlewareTest extends \Test\TestCase {
$this->middleware->beforeController($this->controller, $method);
}
- /**
- * @dataProvider dataPublicPage
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataPublicPage')]
public function testPassesCsrfCheck(string $method): void {
$this->request->expects($this->once())
->method('passesCSRFCheck')
@@ -371,11 +356,9 @@ class SecurityMiddlewareTest extends \Test\TestCase {
$this->middleware->beforeController($this->controller, $method);
}
- /**
- * @dataProvider dataPublicPage
- */
+ #[\PHPUnit\Framework\Attributes\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')
@@ -388,9 +371,7 @@ class SecurityMiddlewareTest extends \Test\TestCase {
$this->middleware->beforeController($this->controller, $method);
}
- /**
- * @dataProvider dataPublicPageStrictCookieRequired
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataPublicPageStrictCookieRequired')]
public function testStrictCookieRequiredCheck(string $method): void {
$this->expectException(\OC\AppFramework\Middleware\Security\Exceptions\StrictCookieMissingException::class);
@@ -404,9 +385,7 @@ class SecurityMiddlewareTest extends \Test\TestCase {
$this->middleware->beforeController($this->controller, $method);
}
- /**
- * @dataProvider dataNoCSRFRequiredPublicPage
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataNoCSRFRequiredPublicPage')]
public function testNoStrictCookieRequiredCheck(string $method): void {
$this->request->expects($this->never())
->method('passesStrictCookieCheck')
@@ -416,9 +395,7 @@ class SecurityMiddlewareTest extends \Test\TestCase {
$this->middleware->beforeController($this->controller, $method);
}
- /**
- * @dataProvider dataNoCSRFRequiredPublicPageStrictCookieRequired
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataNoCSRFRequiredPublicPageStrictCookieRequired')]
public function testPassesStrictCookieRequiredCheck(string $method): void {
$this->request
->expects($this->once())
@@ -429,7 +406,7 @@ class SecurityMiddlewareTest extends \Test\TestCase {
$this->middleware->beforeController($this->controller, $method);
}
- public function dataCsrfOcsController(): array {
+ public static function dataCsrfOcsController(): array {
return [
[NormalController::class, false, false, true],
[NormalController::class, false, true, true],
@@ -444,12 +421,12 @@ class SecurityMiddlewareTest extends \Test\TestCase {
}
/**
- * @dataProvider dataCsrfOcsController
* @param string $controllerClass
* @param bool $hasOcsApiHeader
* @param bool $hasBearerAuth
* @param bool $exception
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataCsrfOcsController')]
public function testCsrfOcsController(string $controllerClass, bool $hasOcsApiHeader, bool $hasBearerAuth, bool $exception): void {
$this->request
->method('getHeader')
@@ -476,30 +453,22 @@ class SecurityMiddlewareTest extends \Test\TestCase {
}
}
- /**
- * @dataProvider dataNoAdminRequiredNoCSRFRequired
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataNoAdminRequiredNoCSRFRequired')]
public function testLoggedInCheck(string $method): void {
$this->securityCheck($method, 'isLoggedIn');
}
- /**
- * @dataProvider dataNoAdminRequiredNoCSRFRequired
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataNoAdminRequiredNoCSRFRequired')]
public function testFailLoggedInCheck(string $method): void {
$this->securityCheck($method, 'isLoggedIn', true);
}
- /**
- * @dataProvider dataNoCSRFRequired
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataNoCSRFRequired')]
public function testIsAdminCheck(string $method): void {
$this->securityCheck($method, 'isAdminUser');
}
- /**
- * @dataProvider dataNoCSRFRequiredSubAdminRequired
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataNoCSRFRequiredSubAdminRequired')]
public function testIsNotSubAdminCheck(string $method): void {
$this->reader->reflect($this->controller, $method);
$sec = $this->getMiddleware(true, false, false);
@@ -508,9 +477,7 @@ class SecurityMiddlewareTest extends \Test\TestCase {
$sec->beforeController($this->controller, $method);
}
- /**
- * @dataProvider dataNoCSRFRequiredSubAdminRequired
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataNoCSRFRequiredSubAdminRequired')]
public function testIsSubAdminCheck(string $method): void {
$this->reader->reflect($this->controller, $method);
$sec = $this->getMiddleware(true, false, true);
@@ -519,9 +486,7 @@ class SecurityMiddlewareTest extends \Test\TestCase {
$this->addToAssertionCount(1);
}
- /**
- * @dataProvider dataNoCSRFRequiredSubAdminRequired
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataNoCSRFRequiredSubAdminRequired')]
public function testIsSubAdminAndAdminCheck(string $method): void {
$this->reader->reflect($this->controller, $method);
$sec = $this->getMiddleware(true, true, true);
@@ -530,16 +495,12 @@ class SecurityMiddlewareTest extends \Test\TestCase {
$this->addToAssertionCount(1);
}
- /**
- * @dataProvider dataNoCSRFRequired
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataNoCSRFRequired')]
public function testFailIsAdminCheck(string $method): void {
$this->securityCheck($method, 'isAdminUser', true);
}
- /**
- * @dataProvider dataNoAdminRequiredNoCSRFRequiredPublicPage
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataNoAdminRequiredNoCSRFRequiredPublicPage')]
public function testRestrictedAppLoggedInPublicPage(string $method): void {
$middleware = $this->getMiddleware(true, false, false);
$this->reader->reflect($this->controller, $method);
@@ -556,9 +517,7 @@ class SecurityMiddlewareTest extends \Test\TestCase {
$this->addToAssertionCount(1);
}
- /**
- * @dataProvider dataNoAdminRequiredNoCSRFRequiredPublicPage
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataNoAdminRequiredNoCSRFRequiredPublicPage')]
public function testRestrictedAppNotLoggedInPublicPage(string $method): void {
$middleware = $this->getMiddleware(false, false, false);
$this->reader->reflect($this->controller, $method);
@@ -575,9 +534,7 @@ class SecurityMiddlewareTest extends \Test\TestCase {
$this->addToAssertionCount(1);
}
- /**
- * @dataProvider dataNoAdminRequiredNoCSRFRequired
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataNoAdminRequiredNoCSRFRequired')]
public function testRestrictedAppLoggedIn(string $method): void {
$middleware = $this->getMiddleware(true, false, false, false);
$this->reader->reflect($this->controller, $method);
@@ -600,8 +557,8 @@ class SecurityMiddlewareTest extends \Test\TestCase {
public function testAfterExceptionReturnsRedirectForNotLoggedInUser(): void {
$this->request = new Request(
[
- 'server' =>
- [
+ 'server'
+ => [
'HTTP_ACCEPT' => 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'REQUEST_URI' => 'nextcloud/index.php/apps/specialapp'
]
@@ -659,7 +616,7 @@ class SecurityMiddlewareTest extends \Test\TestCase {
/**
* @return array
*/
- public function exceptionProvider() {
+ public static function exceptionProvider(): array {
return [
[
new AppNotEnabledException(),
@@ -674,14 +631,14 @@ class SecurityMiddlewareTest extends \Test\TestCase {
}
/**
- * @dataProvider exceptionProvider
* @param SecurityException $exception
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('exceptionProvider')]
public function testAfterExceptionReturnsTemplateResponse(SecurityException $exception): void {
$this->request = new Request(
[
- 'server' =>
- [
+ 'server'
+ => [
'HTTP_ACCEPT' => 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'REQUEST_URI' => 'nextcloud/index.php/apps/specialapp'
]
@@ -710,9 +667,7 @@ class SecurityMiddlewareTest extends \Test\TestCase {
$this->assertTrue($response instanceof JSONResponse);
}
- /**
- * @dataProvider dataExAppRequired
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataExAppRequired')]
public function testExAppRequired(string $method): void {
$middleware = $this->getMiddleware(true, false, false);
$this->reader->reflect($this->controller, $method);
@@ -731,9 +686,7 @@ class SecurityMiddlewareTest extends \Test\TestCase {
$middleware->beforeController($this->controller, $method);
}
- /**
- * @dataProvider dataExAppRequired
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataExAppRequired')]
public function testExAppRequiredError(string $method): void {
$middleware = $this->getMiddleware(true, false, false, false);
$this->reader->reflect($this->controller, $method);
diff --git a/tests/lib/AppFramework/OCS/BaseResponseTest.php b/tests/lib/AppFramework/OCS/BaseResponseTest.php
index 159459a4aec..e04f7856623 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 {
@@ -50,7 +50,7 @@ class BaseResponseTest extends \Test\TestCase {
$writer->outputMemory(true)
);
}
-
+
public function testToXmlJsonSerializable(): void {
/** @var BaseResponse $response */
$response = $this->createMock(BaseResponse::class);
diff --git a/tests/lib/AppFramework/OCS/V2ResponseTest.php b/tests/lib/AppFramework/OCS/V2ResponseTest.php
index 97a227418f3..7a70ad6d633 100644
--- a/tests/lib/AppFramework/OCS/V2ResponseTest.php
+++ b/tests/lib/AppFramework/OCS/V2ResponseTest.php
@@ -15,15 +15,13 @@ use OCP\AppFramework\Http\DataResponse;
use OCP\AppFramework\OCSController;
class V2ResponseTest extends \Test\TestCase {
- /**
- * @dataProvider providesStatusCodes
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('providesStatusCodes')]
public function testStatusCodeMapper(int $expected, int $sc): void {
$response = new V2Response(new DataResponse([], $sc));
$this->assertEquals($expected, $response->getStatus());
}
- public function providesStatusCodes(): array {
+ public static function providesStatusCodes(): array {
return [
[Http::STATUS_OK, 200],
[Http::STATUS_BAD_REQUEST, 104],
diff --git a/tests/lib/AppFramework/Routing/RouteParserTest.php b/tests/lib/AppFramework/Routing/RouteParserTest.php
new file mode 100644
index 00000000000..406c5f1f3a5
--- /dev/null
+++ b/tests/lib/AppFramework/Routing/RouteParserTest.php
@@ -0,0 +1,347 @@
+<?php
+
+declare(strict_types=1);
+
+/**
+ * SPDX-FileCopyrightText: 2025 Nextcloud GmbH and Nextcloud contributors
+ * SPDX-License-Identifier: AGPL-3.0-or-later
+ */
+namespace Test\AppFramework\Routing;
+
+use OC\AppFramework\Routing\RouteParser;
+use Symfony\Component\Routing\Route as RoutingRoute;
+use Symfony\Component\Routing\RouteCollection;
+
+class RouteParserTest extends \Test\TestCase {
+
+ protected RouteParser $parser;
+
+ protected function setUp(): void {
+ $this->parser = new RouteParser();
+ }
+
+ public function testParseRoutes(): void {
+ $routes = ['routes' => [
+ ['name' => 'folders#open', 'url' => '/{folderId}/open', 'verb' => 'GET'],
+ ['name' => 'folders#create', 'url' => '/{folderId}/create', 'verb' => 'POST']
+ ]];
+
+ $collection = $this->parser->parseDefaultRoutes($routes, 'app1');
+ $this->assertArrayHasKey('app1.folders.open', $collection->all());
+ $this->assertSimpleRoute('/apps/app1/{folderId}/open', 'GET', 'FoldersController', 'open', route: $collection->get('app1.folders.open'));
+ $this->assertArrayHasKey('app1.folders.create', $collection->all());
+ $this->assertSimpleRoute('/apps/app1/{folderId}/create', 'POST', 'FoldersController', 'create', route: $collection->get('app1.folders.create'));
+ }
+
+ public function testParseRoutesRootApps(): void {
+ $routes = ['routes' => [
+ ['name' => 'folders#open', 'url' => '/{folderId}/open', 'verb' => 'GET'],
+ ['name' => 'folders#create', 'url' => '/{folderId}/create', 'verb' => 'POST']
+ ]];
+
+ $collection = $this->parser->parseDefaultRoutes($routes, 'core');
+ $this->assertArrayHasKey('core.folders.open', $collection->all());
+ $this->assertSimpleRoute('/{folderId}/open', 'GET', 'FoldersController', 'open', app: 'core', route: $collection->get('core.folders.open'));
+ $this->assertArrayHasKey('core.folders.create', $collection->all());
+ $this->assertSimpleRoute('/{folderId}/create', 'POST', 'FoldersController', 'create', app: 'core', route: $collection->get('core.folders.create'));
+ }
+
+ public function testParseRoutesWithResources(): void {
+ $routes = ['routes' => [
+ ['name' => 'folders#open', 'url' => '/{folderId}/open', 'verb' => 'GET'],
+ ], 'resources' => [
+ 'names' => ['url' => '/names'],
+ 'folder_names' => ['url' => '/folder/names'],
+ ]];
+
+ $collection = $this->parser->parseDefaultRoutes($routes, 'app1');
+ $this->assertArrayHasKey('app1.folders.open', $collection->all());
+ $this->assertSimpleResource('/apps/app1/folder/names', 'folder_names', 'FolderNamesController', 'app1', $collection);
+ $this->assertSimpleResource('/apps/app1/names', 'names', 'NamesController', 'app1', $collection);
+ }
+
+ public function testParseRoutesWithPostfix(): void {
+ $routes = ['routes' => [
+ ['name' => 'folders#update', 'url' => '/{folderId}/update', 'verb' => 'POST'],
+ ['name' => 'folders#update', 'url' => '/{folderId}/update', 'verb' => 'PUT', 'postfix' => '-edit']
+ ]];
+
+ $collection = $this->parser->parseDefaultRoutes($routes, 'app1');
+ $this->assertArrayHasKey('app1.folders.update', $collection->all());
+ $this->assertSimpleRoute('/apps/app1/{folderId}/update', 'POST', 'FoldersController', 'update', route: $collection->get('app1.folders.update'));
+ $this->assertArrayHasKey('app1.folders.update-edit', $collection->all());
+ $this->assertSimpleRoute('/apps/app1/{folderId}/update', 'PUT', 'FoldersController', 'update', route: $collection->get('app1.folders.update-edit'));
+ }
+
+ public function testParseRoutesKebabCaseAction(): void {
+ $routes = ['routes' => [
+ ['name' => 'folders#open_folder', 'url' => '/{folderId}/open', 'verb' => 'GET']
+ ]];
+
+ $collection = $this->parser->parseDefaultRoutes($routes, 'app1');
+ $this->assertArrayHasKey('app1.folders.open_folder', $collection->all());
+ $this->assertSimpleRoute('/apps/app1/{folderId}/open', 'GET', 'FoldersController', 'openFolder', route: $collection->get('app1.folders.open_folder'));
+ }
+
+ public function testParseRoutesKebabCaseController(): void {
+ $routes = ['routes' => [
+ ['name' => 'my_folders#open', 'url' => '/{folderId}/open', 'verb' => 'GET']
+ ]];
+
+ $collection = $this->parser->parseDefaultRoutes($routes, 'app1');
+ $this->assertArrayHasKey('app1.my_folders.open', $collection->all());
+ $this->assertSimpleRoute('/apps/app1/{folderId}/open', 'GET', 'MyFoldersController', 'open', route: $collection->get('app1.my_folders.open'));
+ }
+
+ public function testParseRoutesLowercaseVerb(): void {
+ $routes = ['routes' => [
+ ['name' => 'folders#delete', 'url' => '/{folderId}/delete', 'verb' => 'delete']
+ ]];
+
+ $collection = $this->parser->parseDefaultRoutes($routes, 'app1');
+ $this->assertArrayHasKey('app1.folders.delete', $collection->all());
+ $this->assertSimpleRoute('/apps/app1/{folderId}/delete', 'DELETE', 'FoldersController', 'delete', route: $collection->get('app1.folders.delete'));
+ }
+
+ public function testParseRoutesMissingVerb(): void {
+ $routes = ['routes' => [
+ ['name' => 'folders#open', 'url' => '/{folderId}/open']
+ ]];
+
+ $collection = $this->parser->parseDefaultRoutes($routes, 'app1');
+ $this->assertArrayHasKey('app1.folders.open', $collection->all());
+ $this->assertSimpleRoute('/apps/app1/{folderId}/open', 'GET', 'FoldersController', 'open', route: $collection->get('app1.folders.open'));
+ }
+
+ public function testParseRoutesWithRequirements(): void {
+ $routes = ['routes' => [
+ ['name' => 'folders#open', 'url' => '/{folderId}/open', 'verb' => 'GET', 'requirements' => ['folderId' => '\d+']]
+ ]];
+
+ $collection = $this->parser->parseDefaultRoutes($routes, 'app1');
+ $this->assertArrayHasKey('app1.folders.open', $collection->all());
+ $this->assertSimpleRoute('/apps/app1/{folderId}/open', 'GET', 'FoldersController', 'open', requirements: ['folderId' => '\d+'], route: $collection->get('app1.folders.open'));
+ }
+
+ public function testParseRoutesWithDefaults(): void {
+ $routes = ['routes' => [
+ ['name' => 'folders#open', 'url' => '/{folderId}/open', 'verb' => 'GET', 'defaults' => ['hello' => 'world']]
+ ]];
+
+ $collection = $this->parser->parseDefaultRoutes($routes, 'app1');
+ $this->assertArrayHasKey('app1.folders.open', $collection->all());
+ $this->assertSimpleRoute('/apps/app1/{folderId}/open', 'GET', 'FoldersController', 'open', defaults: ['hello' => 'world'], route: $collection->get('app1.folders.open'));
+ }
+
+ public function testParseRoutesInvalidName(): void {
+ $routes = ['routes' => [
+ ['name' => 'folders', 'url' => '/{folderId}/open', 'verb' => 'GET']
+ ]];
+
+ $this->expectException(\UnexpectedValueException::class);
+ $this->parser->parseDefaultRoutes($routes, 'app1');
+ }
+
+ public function testParseRoutesInvalidName2(): void {
+ $routes = ['routes' => [
+ ['name' => 'folders#open#action', 'url' => '/{folderId}/open', 'verb' => 'GET']
+ ]];
+
+ $this->expectException(\UnexpectedValueException::class);
+ $this->parser->parseDefaultRoutes($routes, 'app1');
+ }
+
+ public function testParseRoutesEmpty(): void {
+ $routes = ['routes' => []];
+
+ $collection = $this->parser->parseDefaultRoutes($routes, 'app1');
+ $this->assertEquals(0, $collection->count());
+ }
+
+ // OCS routes
+
+ public function testParseOcsRoutes(): void {
+ $routes = ['ocs' => [
+ ['name' => 'folders#open', 'url' => '/{folderId}/open', 'verb' => 'GET'],
+ ['name' => 'folders#create', 'url' => '/{folderId}/create', 'verb' => 'POST']
+ ]];
+
+ $collection = $this->parser->parseOCSRoutes($routes, 'app1');
+ $this->assertArrayHasKey('ocs.app1.folders.open', $collection->all());
+ $this->assertSimpleRoute('/apps/app1/{folderId}/open', 'GET', 'FoldersController', 'open', route: $collection->get('ocs.app1.folders.open'));
+ $this->assertArrayHasKey('ocs.app1.folders.create', $collection->all());
+ $this->assertSimpleRoute('/apps/app1/{folderId}/create', 'POST', 'FoldersController', 'create', route: $collection->get('ocs.app1.folders.create'));
+ }
+
+ public function testParseOcsRoutesRootApps(): void {
+ $routes = ['ocs' => [
+ ['name' => 'folders#open', 'url' => '/{folderId}/open', 'verb' => 'GET'],
+ ['name' => 'folders#create', 'url' => '/{folderId}/create', 'verb' => 'POST']
+ ]];
+
+ $collection = $this->parser->parseOCSRoutes($routes, 'core');
+ $this->assertArrayHasKey('ocs.core.folders.open', $collection->all());
+ $this->assertSimpleRoute('/{folderId}/open', 'GET', 'FoldersController', 'open', app: 'core', route: $collection->get('ocs.core.folders.open'));
+ $this->assertArrayHasKey('ocs.core.folders.create', $collection->all());
+ $this->assertSimpleRoute('/{folderId}/create', 'POST', 'FoldersController', 'create', app: 'core', route: $collection->get('ocs.core.folders.create'));
+ }
+
+ public function testParseOcsRoutesWithPostfix(): void {
+ $routes = ['ocs' => [
+ ['name' => 'folders#update', 'url' => '/{folderId}/update', 'verb' => 'POST'],
+ ['name' => 'folders#update', 'url' => '/{folderId}/update', 'verb' => 'PUT', 'postfix' => '-edit']
+ ]];
+
+ $collection = $this->parser->parseOCSRoutes($routes, 'app1');
+ $this->assertArrayHasKey('ocs.app1.folders.update', $collection->all());
+ $this->assertSimpleRoute('/apps/app1/{folderId}/update', 'POST', 'FoldersController', 'update', route: $collection->get('ocs.app1.folders.update'));
+ $this->assertArrayHasKey('ocs.app1.folders.update-edit', $collection->all());
+ $this->assertSimpleRoute('/apps/app1/{folderId}/update', 'PUT', 'FoldersController', 'update', route: $collection->get('ocs.app1.folders.update-edit'));
+ }
+
+ public function testParseOcsRoutesKebabCaseAction(): void {
+ $routes = ['ocs' => [
+ ['name' => 'folders#open_folder', 'url' => '/{folderId}/open', 'verb' => 'GET']
+ ]];
+
+ $collection = $this->parser->parseOCSRoutes($routes, 'app1');
+ $this->assertArrayHasKey('ocs.app1.folders.open_folder', $collection->all());
+ $this->assertSimpleRoute('/apps/app1/{folderId}/open', 'GET', 'FoldersController', 'openFolder', route: $collection->get('ocs.app1.folders.open_folder'));
+ }
+
+ public function testParseOcsRoutesKebabCaseController(): void {
+ $routes = ['ocs' => [
+ ['name' => 'my_folders#open', 'url' => '/{folderId}/open', 'verb' => 'GET']
+ ]];
+
+ $collection = $this->parser->parseOCSRoutes($routes, 'app1');
+ $this->assertArrayHasKey('ocs.app1.my_folders.open', $collection->all());
+ $this->assertSimpleRoute('/apps/app1/{folderId}/open', 'GET', 'MyFoldersController', 'open', route: $collection->get('ocs.app1.my_folders.open'));
+ }
+
+ public function testParseOcsRoutesLowercaseVerb(): void {
+ $routes = ['ocs' => [
+ ['name' => 'folders#delete', 'url' => '/{folderId}/delete', 'verb' => 'delete']
+ ]];
+
+ $collection = $this->parser->parseOCSRoutes($routes, 'app1');
+ $this->assertArrayHasKey('ocs.app1.folders.delete', $collection->all());
+ $this->assertSimpleRoute('/apps/app1/{folderId}/delete', 'DELETE', 'FoldersController', 'delete', route: $collection->get('ocs.app1.folders.delete'));
+ }
+
+ public function testParseOcsRoutesMissingVerb(): void {
+ $routes = ['ocs' => [
+ ['name' => 'folders#open', 'url' => '/{folderId}/open']
+ ]];
+
+ $collection = $this->parser->parseOCSRoutes($routes, 'app1');
+ $this->assertArrayHasKey('ocs.app1.folders.open', $collection->all());
+ $this->assertSimpleRoute('/apps/app1/{folderId}/open', 'GET', 'FoldersController', 'open', route: $collection->get('ocs.app1.folders.open'));
+ }
+
+ public function testParseOcsRoutesWithRequirements(): void {
+ $routes = ['ocs' => [
+ ['name' => 'folders#open', 'url' => '/{folderId}/open', 'verb' => 'GET', 'requirements' => ['folderId' => '\d+']]
+ ]];
+
+ $collection = $this->parser->parseOCSRoutes($routes, 'app1');
+ $this->assertArrayHasKey('ocs.app1.folders.open', $collection->all());
+ $this->assertSimpleRoute('/apps/app1/{folderId}/open', 'GET', 'FoldersController', 'open', requirements: ['folderId' => '\d+'], route: $collection->get('ocs.app1.folders.open'));
+ }
+
+ public function testParseOcsRoutesWithDefaults(): void {
+ $routes = ['ocs' => [
+ ['name' => 'folders#open', 'url' => '/{folderId}/open', 'verb' => 'GET', 'defaults' => ['hello' => 'world']]
+ ]];
+
+ $collection = $this->parser->parseOCSRoutes($routes, 'app1');
+ $this->assertArrayHasKey('ocs.app1.folders.open', $collection->all());
+ $this->assertSimpleRoute('/apps/app1/{folderId}/open', 'GET', 'FoldersController', 'open', defaults: ['hello' => 'world'], route: $collection->get('ocs.app1.folders.open'));
+ }
+
+ public function testParseOcsRoutesInvalidName(): void {
+ $routes = ['ocs' => [
+ ['name' => 'folders', 'url' => '/{folderId}/open', 'verb' => 'GET']
+ ]];
+
+ $this->expectException(\UnexpectedValueException::class);
+ $this->parser->parseOCSRoutes($routes, 'app1');
+ }
+
+ public function testParseOcsRoutesEmpty(): void {
+ $routes = ['ocs' => []];
+
+ $collection = $this->parser->parseOCSRoutes($routes, 'app1');
+ $this->assertEquals(0, $collection->count());
+ }
+
+ public function testParseOcsRoutesWithResources(): void {
+ $routes = ['ocs' => [
+ ['name' => 'folders#open', 'url' => '/{folderId}/open', 'verb' => 'GET'],
+ ], 'ocs-resources' => [
+ 'names' => ['url' => '/names', 'root' => '/core/something'],
+ 'folder_names' => ['url' => '/folder/names'],
+ ]];
+
+ $collection = $this->parser->parseOCSRoutes($routes, 'app1');
+ $this->assertArrayHasKey('ocs.app1.folders.open', $collection->all());
+ $this->assertOcsResource('/apps/app1/folder/names', 'folder_names', 'FolderNamesController', 'app1', $collection);
+ $this->assertOcsResource('/core/something/names', 'names', 'NamesController', 'app1', $collection);
+ }
+
+ protected function assertSimpleRoute(
+ string $path,
+ string $method,
+ string $controller,
+ string $action,
+ string $app = 'app1',
+ array $requirements = [],
+ array $defaults = [],
+ ?RoutingRoute $route = null,
+ ): void {
+ self::assertEquals($path, $route->getPath());
+ self::assertEqualsCanonicalizing([$method], $route->getMethods());
+ self::assertEqualsCanonicalizing($requirements, $route->getRequirements());
+ self::assertEquals([...$defaults, 'action' => null, 'caller' => [$app, $controller, $action]], $route->getDefaults());
+ }
+
+ protected function assertSimpleResource(
+ string $path,
+ string $resourceName,
+ string $controller,
+ string $app,
+ RouteCollection $collection,
+ ): void {
+ self::assertArrayHasKey("$app.$resourceName.index", $collection->all());
+ self::assertArrayHasKey("$app.$resourceName.show", $collection->all());
+ self::assertArrayHasKey("$app.$resourceName.create", $collection->all());
+ self::assertArrayHasKey("$app.$resourceName.update", $collection->all());
+ self::assertArrayHasKey("$app.$resourceName.destroy", $collection->all());
+
+ $this->assertSimpleRoute($path, 'GET', $controller, 'index', $app, route: $collection->get("$app.$resourceName.index"));
+ $this->assertSimpleRoute($path, 'POST', $controller, 'create', $app, route: $collection->get("$app.$resourceName.create"));
+ $this->assertSimpleRoute("$path/{id}", 'GET', $controller, 'show', $app, route: $collection->get("$app.$resourceName.show"));
+ $this->assertSimpleRoute("$path/{id}", 'PUT', $controller, 'update', $app, route: $collection->get("$app.$resourceName.update"));
+ $this->assertSimpleRoute("$path/{id}", 'DELETE', $controller, 'destroy', $app, route: $collection->get("$app.$resourceName.destroy"));
+ }
+
+ protected function assertOcsResource(
+ string $path,
+ string $resourceName,
+ string $controller,
+ string $app,
+ RouteCollection $collection,
+ ): void {
+ self::assertArrayHasKey("ocs.$app.$resourceName.index", $collection->all());
+ self::assertArrayHasKey("ocs.$app.$resourceName.show", $collection->all());
+ self::assertArrayHasKey("ocs.$app.$resourceName.create", $collection->all());
+ self::assertArrayHasKey("ocs.$app.$resourceName.update", $collection->all());
+ self::assertArrayHasKey("ocs.$app.$resourceName.destroy", $collection->all());
+
+ $this->assertSimpleRoute($path, 'GET', $controller, 'index', $app, route: $collection->get("ocs.$app.$resourceName.index"));
+ $this->assertSimpleRoute($path, 'POST', $controller, 'create', $app, route: $collection->get("ocs.$app.$resourceName.create"));
+ $this->assertSimpleRoute("$path/{id}", 'GET', $controller, 'show', $app, route: $collection->get("ocs.$app.$resourceName.show"));
+ $this->assertSimpleRoute("$path/{id}", 'PUT', $controller, 'update', $app, route: $collection->get("ocs.$app.$resourceName.update"));
+ $this->assertSimpleRoute("$path/{id}", 'DELETE', $controller, 'destroy', $app, route: $collection->get("ocs.$app.$resourceName.destroy"));
+ }
+}
diff --git a/tests/lib/AppFramework/Routing/RoutingTest.php b/tests/lib/AppFramework/Routing/RoutingTest.php
deleted file mode 100644
index 8522382ddcc..00000000000
--- a/tests/lib/AppFramework/Routing/RoutingTest.php
+++ /dev/null
@@ -1,476 +0,0 @@
-<?php
-/**
- * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
- * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
- * SPDX-License-Identifier: AGPL-3.0-or-later
- */
-namespace Test\AppFramework\Routing;
-
-use OC\AppFramework\DependencyInjection\DIContainer;
-use OC\AppFramework\Routing\RouteConfig;
-use OC\Route\Route;
-use OC\Route\Router;
-use OCP\App\IAppManager;
-use OCP\Diagnostics\IEventLogger;
-use OCP\IConfig;
-use OCP\IRequest;
-use OCP\Route\IRouter;
-use PHPUnit\Framework\MockObject\MockObject;
-use Psr\Container\ContainerInterface;
-use Psr\Log\LoggerInterface;
-
-class RoutingTest extends \Test\TestCase {
- public function testSimpleRoute(): void {
- $routes = ['routes' => [
- ['name' => 'folders#open', 'url' => '/folders/{folderId}/open', 'verb' => 'GET']
- ]];
-
- $this->assertSimpleRoute($routes, 'folders.open', 'GET', '/apps/app1/folders/{folderId}/open', 'FoldersController', 'open');
- }
-
- public function testSimpleRouteWithUnderScoreNames(): void {
- $routes = ['routes' => [
- ['name' => 'admin_folders#open_current', 'url' => '/folders/{folderId}/open', 'verb' => 'delete', 'root' => '']
- ]];
-
- $this->assertSimpleRoute($routes, 'admin_folders.open_current', 'DELETE', '/folders/{folderId}/open', 'AdminFoldersController', 'openCurrent', [], [], '', true);
- }
-
- public function testSimpleOCSRoute(): void {
- $routes = ['ocs' => [
- ['name' => 'folders#open', 'url' => '/folders/{folderId}/open', 'verb' => 'GET']
- ]
- ];
-
- $this->assertSimpleOCSRoute($routes, 'folders.open', 'GET', '/apps/app1/folders/{folderId}/open', 'FoldersController', 'open');
- }
-
- public function testSimpleRouteWithMissingVerb(): void {
- $routes = ['routes' => [
- ['name' => 'folders#open', 'url' => '/folders/{folderId}/open']
- ]];
-
- $this->assertSimpleRoute($routes, 'folders.open', 'GET', '/apps/app1/folders/{folderId}/open', 'FoldersController', 'open');
- }
-
- public function testSimpleOCSRouteWithMissingVerb(): void {
- $routes = ['ocs' => [
- ['name' => 'folders#open', 'url' => '/folders/{folderId}/open']
- ]
- ];
-
- $this->assertSimpleOCSRoute($routes, 'folders.open', 'GET', '/apps/app1/folders/{folderId}/open', 'FoldersController', 'open');
- }
-
- public function testSimpleRouteWithLowercaseVerb(): void {
- $routes = ['routes' => [
- ['name' => 'folders#open', 'url' => '/folders/{folderId}/open', 'verb' => 'delete']
- ]];
-
- $this->assertSimpleRoute($routes, 'folders.open', 'DELETE', '/apps/app1/folders/{folderId}/open', 'FoldersController', 'open');
- }
-
- public function testSimpleOCSRouteWithLowercaseVerb(): void {
- $routes = ['ocs' => [
- ['name' => 'folders#open', 'url' => '/folders/{folderId}/open', 'verb' => 'delete']
- ]
- ];
-
- $this->assertSimpleOCSRoute($routes, 'folders.open', 'DELETE', '/apps/app1/folders/{folderId}/open', 'FoldersController', 'open');
- }
-
- public function testSimpleRouteWithRequirements(): void {
- $routes = ['routes' => [
- ['name' => 'folders#open', 'url' => '/folders/{folderId}/open', 'verb' => 'delete', 'requirements' => ['something']]
- ]];
-
- $this->assertSimpleRoute($routes, 'folders.open', 'DELETE', '/apps/app1/folders/{folderId}/open', 'FoldersController', 'open', ['something']);
- }
-
- public function testSimpleOCSRouteWithRequirements(): void {
- $routes = ['ocs' => [
- ['name' => 'folders#open', 'url' => '/folders/{folderId}/open', 'verb' => 'delete', 'requirements' => ['something']]
- ]
- ];
-
- $this->assertSimpleOCSRoute($routes, 'folders.open', 'DELETE', '/apps/app1/folders/{folderId}/open', 'FoldersController', 'open', ['something']);
- }
-
- public function testSimpleRouteWithDefaults(): void {
- $routes = ['routes' => [
- ['name' => 'folders#open', 'url' => '/folders/{folderId}/open', 'verb' => 'delete', [], 'defaults' => ['param' => 'foobar']]
- ]];
-
- $this->assertSimpleRoute($routes, 'folders.open', 'DELETE', '/apps/app1/folders/{folderId}/open', 'FoldersController', 'open', [], ['param' => 'foobar']);
- }
-
-
- public function testSimpleOCSRouteWithDefaults(): void {
- $routes = ['ocs' => [
- ['name' => 'folders#open', 'url' => '/folders/{folderId}/open', 'verb' => 'delete', 'defaults' => ['param' => 'foobar']]
- ]
- ];
-
- $this->assertSimpleOCSRoute($routes, 'folders.open', 'DELETE', '/apps/app1/folders/{folderId}/open', 'FoldersController', 'open', [], ['param' => 'foobar']);
- }
-
- public function testSimpleRouteWithPostfix(): void {
- $routes = ['routes' => [
- ['name' => 'folders#open', 'url' => '/folders/{folderId}/open', 'verb' => 'delete', 'postfix' => '_something']
- ]];
-
- $this->assertSimpleRoute($routes, 'folders.open', 'DELETE', '/apps/app1/folders/{folderId}/open', 'FoldersController', 'open', [], [], '_something');
- }
-
- public function testSimpleOCSRouteWithPostfix(): void {
- $routes = ['ocs' => [
- ['name' => 'folders#open', 'url' => '/folders/{folderId}/open', 'verb' => 'delete', 'postfix' => '_something']
- ]
- ];
-
- $this->assertSimpleOCSRoute($routes, 'folders.open', 'DELETE', '/apps/app1/folders/{folderId}/open', 'FoldersController', 'open', [], [], '_something');
- }
-
-
- public function testSimpleRouteWithBrokenName(): void {
- $this->expectException(\UnexpectedValueException::class);
-
- $routes = ['routes' => [
- ['name' => 'folders_open', 'url' => '/folders/{folderId}/open', 'verb' => 'delete']
- ]];
-
- /** @var IRouter|MockObject $router */
- $router = $this->getMockBuilder(Router::class)
- ->onlyMethods(['create'])
- ->setConstructorArgs([
- $this->createMock(LoggerInterface::class),
- $this->createMock(IRequest::class),
- $this->createMock(IConfig::class),
- $this->createMock(IEventLogger::class),
- $this->createMock(ContainerInterface::class),
- $this->createMock(IAppManager::class),
- ])
- ->getMock();
-
- // load route configuration
- $container = new DIContainer('app1');
- $config = new RouteConfig($container, $router, $routes);
-
- $config->register();
- }
-
-
- public function testSimpleOCSRouteWithBrokenName(): void {
- $this->expectException(\UnexpectedValueException::class);
-
- $routes = ['ocs' => [
- ['name' => 'folders_open', 'url' => '/folders/{folderId}/open', 'verb' => 'delete']
- ]];
-
- /** @var IRouter|MockObject $router */
- $router = $this->getMockBuilder(Router::class)
- ->onlyMethods(['create'])
- ->setConstructorArgs([
- $this->createMock(LoggerInterface::class),
- $this->createMock(IRequest::class),
- $this->createMock(IConfig::class),
- $this->createMock(IEventLogger::class),
- $this->createMock(ContainerInterface::class),
- $this->createMock(IAppManager::class),
- ])
- ->getMock();
-
- // load route configuration
- $container = new DIContainer('app1');
- $config = new RouteConfig($container, $router, $routes);
-
- $config->register();
- }
-
- public function testSimpleOCSRouteWithUnderScoreNames(): void {
- $routes = ['ocs' => [
- ['name' => 'admin_folders#open_current', 'url' => '/folders/{folderId}/open', 'verb' => 'delete']
- ]];
-
- $this->assertSimpleOCSRoute($routes, 'admin_folders.open_current', 'DELETE', '/apps/app1/folders/{folderId}/open', 'AdminFoldersController', 'openCurrent');
- }
-
- public function testOCSResource(): void {
- $routes = ['ocs-resources' => ['account' => ['url' => '/accounts']]];
-
- $this->assertOCSResource($routes, 'account', '/apps/app1/accounts', 'AccountController', 'id');
- }
-
- public function testOCSResourceWithUnderScoreName(): void {
- $routes = ['ocs-resources' => ['admin_accounts' => ['url' => '/admin/accounts']]];
-
- $this->assertOCSResource($routes, 'admin_accounts', '/apps/app1/admin/accounts', 'AdminAccountsController', 'id');
- }
-
- public function testOCSResourceWithRoot(): void {
- $routes = ['ocs-resources' => ['admin_accounts' => ['url' => '/admin/accounts', 'root' => '/core/endpoint']]];
-
- $this->assertOCSResource($routes, 'admin_accounts', '/core/endpoint/admin/accounts', 'AdminAccountsController', 'id');
- }
-
- public function testResource(): void {
- $routes = ['resources' => ['account' => ['url' => '/accounts']]];
-
- $this->assertResource($routes, 'account', '/apps/app1/accounts', 'AccountController', 'id');
- }
-
- public function testResourceWithUnderScoreName(): void {
- $routes = ['resources' => ['admin_accounts' => ['url' => '/admin/accounts']]];
-
- $this->assertResource($routes, 'admin_accounts', '/apps/app1/admin/accounts', 'AdminAccountsController', 'id');
- }
-
- private function assertSimpleRoute($routes, $name, $verb, $url, $controllerName, $actionName, array $requirements = [], array $defaults = [], $postfix = '', $allowRootUrl = false): void {
- if ($postfix) {
- $name .= $postfix;
- }
-
- // route mocks
- $container = new DIContainer('app1');
- $route = $this->mockRoute($container, $verb, $controllerName, $actionName, $requirements, $defaults);
-
- /** @var IRouter|MockObject $router */
- $router = $this->getMockBuilder(Router::class)
- ->onlyMethods(['create'])
- ->setConstructorArgs([
- $this->createMock(LoggerInterface::class),
- $this->createMock(IRequest::class),
- $this->createMock(IConfig::class),
- $this->createMock(IEventLogger::class),
- $this->createMock(ContainerInterface::class),
- $this->createMock(IAppManager::class),
- ])
- ->getMock();
-
- // we expect create to be called once:
- $router
- ->expects($this->once())
- ->method('create')
- ->with($this->equalTo('app1.' . $name), $this->equalTo($url))
- ->willReturn($route);
-
- // load route configuration
- $config = new RouteConfig($container, $router, $routes);
- if ($allowRootUrl) {
- self::invokePrivate($config, 'rootUrlApps', [['app1']]);
- }
-
- $config->register();
- }
-
- /**
- * @param $routes
- * @param string $name
- * @param string $verb
- * @param string $url
- * @param string $controllerName
- * @param string $actionName
- * @param array $requirements
- * @param array $defaults
- * @param string $postfix
- */
- private function assertSimpleOCSRoute($routes,
- $name,
- $verb,
- $url,
- $controllerName,
- $actionName,
- array $requirements = [],
- array $defaults = [],
- $postfix = '') {
- if ($postfix) {
- $name .= $postfix;
- }
-
- // route mocks
- $container = new DIContainer('app1');
- $route = $this->mockRoute($container, $verb, $controllerName, $actionName, $requirements, $defaults);
-
- /** @var IRouter|MockObject $router */
- $router = $this->getMockBuilder(Router::class)
- ->onlyMethods(['create'])
- ->setConstructorArgs([
- $this->createMock(LoggerInterface::class),
- $this->createMock(IRequest::class),
- $this->createMock(IConfig::class),
- $this->createMock(IEventLogger::class),
- $this->createMock(ContainerInterface::class),
- $this->createMock(IAppManager::class),
- ])
- ->getMock();
-
- // we expect create to be called once:
- $router
- ->expects($this->once())
- ->method('create')
- ->with($this->equalTo('ocs.app1.' . $name), $this->equalTo($url))
- ->willReturn($route);
-
- // load route configuration
- $config = new RouteConfig($container, $router, $routes);
-
- $config->register();
- }
-
- /**
- * @param array $yaml
- * @param string $resourceName
- * @param string $url
- * @param string $controllerName
- * @param string $paramName
- */
- private function assertOCSResource($yaml, $resourceName, $url, $controllerName, $paramName): void {
- /** @var IRouter|MockObject $router */
- $router = $this->getMockBuilder(Router::class)
- ->onlyMethods(['create'])
- ->setConstructorArgs([
- $this->createMock(LoggerInterface::class),
- $this->createMock(IRequest::class),
- $this->createMock(IConfig::class),
- $this->createMock(IEventLogger::class),
- $this->createMock(ContainerInterface::class),
- $this->createMock(IAppManager::class),
- ])
- ->getMock();
-
- // route mocks
- $container = new DIContainer('app1');
- $indexRoute = $this->mockRoute($container, 'GET', $controllerName, 'index');
- $showRoute = $this->mockRoute($container, 'GET', $controllerName, 'show');
- $createRoute = $this->mockRoute($container, 'POST', $controllerName, 'create');
- $updateRoute = $this->mockRoute($container, 'PUT', $controllerName, 'update');
- $destroyRoute = $this->mockRoute($container, 'DELETE', $controllerName, 'destroy');
-
- $urlWithParam = $url . '/{' . $paramName . '}';
-
- // we expect create to be called five times:
- $router
- ->expects($this->exactly(5))
- ->method('create')
- ->withConsecutive(
- [$this->equalTo('ocs.app1.' . $resourceName . '.index'), $this->equalTo($url)],
- [$this->equalTo('ocs.app1.' . $resourceName . '.show'), $this->equalTo($urlWithParam)],
- [$this->equalTo('ocs.app1.' . $resourceName . '.create'), $this->equalTo($url)],
- [$this->equalTo('ocs.app1.' . $resourceName . '.update'), $this->equalTo($urlWithParam)],
- [$this->equalTo('ocs.app1.' . $resourceName . '.destroy'), $this->equalTo($urlWithParam)],
- )->willReturnOnConsecutiveCalls(
- $indexRoute,
- $showRoute,
- $createRoute,
- $updateRoute,
- $destroyRoute,
- );
-
- // load route configuration
- $config = new RouteConfig($container, $router, $yaml);
-
- $config->register();
- }
-
- /**
- * @param string $resourceName
- * @param string $url
- * @param string $controllerName
- * @param string $paramName
- */
- private function assertResource($yaml, $resourceName, $url, $controllerName, $paramName) {
- /** @var IRouter|MockObject $router */
- $router = $this->getMockBuilder(Router::class)
- ->onlyMethods(['create'])
- ->setConstructorArgs([
- $this->createMock(LoggerInterface::class),
- $this->createMock(IRequest::class),
- $this->createMock(IConfig::class),
- $this->createMock(IEventLogger::class),
- $this->createMock(ContainerInterface::class),
- $this->createMock(IAppManager::class),
- ])
- ->getMock();
-
- // route mocks
- $container = new DIContainer('app1');
- $indexRoute = $this->mockRoute($container, 'GET', $controllerName, 'index');
- $showRoute = $this->mockRoute($container, 'GET', $controllerName, 'show');
- $createRoute = $this->mockRoute($container, 'POST', $controllerName, 'create');
- $updateRoute = $this->mockRoute($container, 'PUT', $controllerName, 'update');
- $destroyRoute = $this->mockRoute($container, 'DELETE', $controllerName, 'destroy');
-
- $urlWithParam = $url . '/{' . $paramName . '}';
-
- // we expect create to be called five times:
- $router
- ->expects($this->exactly(5))
- ->method('create')
- ->withConsecutive(
- [$this->equalTo('app1.' . $resourceName . '.index'), $this->equalTo($url)],
- [$this->equalTo('app1.' . $resourceName . '.show'), $this->equalTo($urlWithParam)],
- [$this->equalTo('app1.' . $resourceName . '.create'), $this->equalTo($url)],
- [$this->equalTo('app1.' . $resourceName . '.update'), $this->equalTo($urlWithParam)],
- [$this->equalTo('app1.' . $resourceName . '.destroy'), $this->equalTo($urlWithParam)],
- )->willReturnOnConsecutiveCalls(
- $indexRoute,
- $showRoute,
- $createRoute,
- $updateRoute,
- $destroyRoute,
- );
-
- // load route configuration
- $config = new RouteConfig($container, $router, $yaml);
-
- $config->register();
- }
-
- /**
- * @param DIContainer $container
- * @param string $verb
- * @param string $controllerName
- * @param string $actionName
- * @param array $requirements
- * @param array $defaults
- * @return MockObject
- */
- private function mockRoute(
- DIContainer $container,
- $verb,
- $controllerName,
- $actionName,
- array $requirements = [],
- array $defaults = [],
- ) {
- $route = $this->getMockBuilder(Route::class)
- ->onlyMethods(['method', 'requirements', 'defaults'])
- ->disableOriginalConstructor()
- ->getMock();
- $route
- ->expects($this->once())
- ->method('method')
- ->with($this->equalTo($verb))
- ->willReturn($route);
-
- if (count($requirements) > 0) {
- $route
- ->expects($this->once())
- ->method('requirements')
- ->with($this->equalTo($requirements))
- ->willReturn($route);
- }
-
- $route->expects($this->once())
- ->method('defaults')
- ->with($this->callback(function (array $def) use ($defaults, $controllerName, $actionName) {
- $defaults['caller'] = ['app1', $controllerName, $actionName];
-
- $this->assertEquals($defaults, $def);
- return true;
- }))
- ->willReturn($route);
-
- return $route;
- }
-}
diff --git a/tests/lib/AppFramework/Services/AppConfigTest.php b/tests/lib/AppFramework/Services/AppConfigTest.php
index 46f73a8c088..38fa6bdcac6 100644
--- a/tests/lib/AppFramework/Services/AppConfigTest.php
+++ b/tests/lib/AppFramework/Services/AppConfigTest.php
@@ -28,7 +28,7 @@ class AppConfigTest extends TestCase {
parent::setUp();
$this->config = $this->createMock(IConfig::class);
$this->appConfigCore = $this->createMock(AppConfigCore::class);
-
+
$this->appConfig = new AppConfig($this->config, $this->appConfigCore, self::TEST_APPID);
}
@@ -46,7 +46,7 @@ class AppConfigTest extends TestCase {
* @return array
* @see testHasAppKey
*/
- public function providerHasAppKey(): array {
+ public static function providerHasAppKey(): array {
return [
// lazy, expected
[false, true],
@@ -57,11 +57,11 @@ class AppConfigTest extends TestCase {
}
/**
- * @dataProvider providerHasAppKey
*
* @param bool $lazy
* @param bool $expected
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('providerHasAppKey')]
public function testHasAppKey(bool $lazy, bool $expected): void {
$key = 'key';
$this->appConfigCore->expects($this->once())
@@ -76,7 +76,7 @@ class AppConfigTest extends TestCase {
* @return array
* @see testIsSensitive
*/
- public function providerIsSensitive(): array {
+ public static function providerIsSensitive(): array {
return [
// lazy, expected
[false, true],
@@ -87,11 +87,11 @@ class AppConfigTest extends TestCase {
}
/**
- * @dataProvider providerIsSensitive
*
* @param bool $lazy
* @param bool $expected
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('providerIsSensitive')]
public function testIsSensitive(bool $lazy, bool $expected): void {
$key = 'key';
$this->appConfigCore->expects($this->once())
@@ -103,11 +103,11 @@ class AppConfigTest extends TestCase {
}
/**
- * @dataProvider providerIsSensitive
*
* @param bool $lazy
* @param bool $expected
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('providerIsSensitive')]
public function testIsSensitiveException(bool $lazy, bool $expected): void {
$key = 'unknown-key';
$this->appConfigCore->expects($this->once())
@@ -123,7 +123,7 @@ class AppConfigTest extends TestCase {
* @return array
* @see testIsLazy
*/
- public function providerIsLazy(): array {
+ public static function providerIsLazy(): array {
return [
// expected
[true],
@@ -132,10 +132,9 @@ class AppConfigTest extends TestCase {
}
/**
- * @dataProvider providerIsLazy
- *
* @param bool $expected
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('providerIsLazy')]
public function testIsLazy(bool $expected): void {
$key = 'key';
$this->appConfigCore->expects($this->once())
@@ -161,7 +160,7 @@ class AppConfigTest extends TestCase {
* @return array
* @see testGetAllAppValues
*/
- public function providerGetAllAppValues(): array {
+ public static function providerGetAllAppValues(): array {
return [
// key, filtered
['', false],
@@ -172,11 +171,11 @@ class AppConfigTest extends TestCase {
}
/**
- * @dataProvider providerGetAllAppValues
*
* @param string $key
* @param bool $filtered
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('providerGetAllAppValues')]
public function testGetAllAppValues(string $key, bool $filtered): void {
$expected = [
'key1' => 'value1',
@@ -214,7 +213,7 @@ class AppConfigTest extends TestCase {
* @see testSetAppValueArray
* @see testSetAppValueArrayException
*/
- public function providerSetAppValue(): array {
+ public static function providerSetAppValue(): array {
return [
// lazy, sensitive, expected
[false, false, true],
@@ -229,12 +228,12 @@ class AppConfigTest extends TestCase {
}
/**
- * @dataProvider providerSetAppValue
*
* @param bool $lazy
* @param bool $sensitive
* @param bool $expected
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('providerSetAppValue')]
public function testSetAppValueString(bool $lazy, bool $sensitive, bool $expected): void {
$key = 'key';
$value = 'valueString';
@@ -247,11 +246,11 @@ class AppConfigTest extends TestCase {
}
/**
- * @dataProvider providerSetAppValue
*
* @param bool $lazy
* @param bool $sensitive
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('providerSetAppValue')]
public function testSetAppValueStringException(bool $lazy, bool $sensitive): void {
$key = 'key';
$value = 'valueString';
@@ -265,12 +264,12 @@ class AppConfigTest extends TestCase {
}
/**
- * @dataProvider providerSetAppValue
*
* @param bool $lazy
* @param bool $sensitive
* @param bool $expected
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('providerSetAppValue')]
public function testSetAppValueInt(bool $lazy, bool $sensitive, bool $expected): void {
$key = 'key';
$value = 42;
@@ -283,11 +282,11 @@ class AppConfigTest extends TestCase {
}
/**
- * @dataProvider providerSetAppValue
*
* @param bool $lazy
* @param bool $sensitive
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('providerSetAppValue')]
public function testSetAppValueIntException(bool $lazy, bool $sensitive): void {
$key = 'key';
$value = 42;
@@ -301,12 +300,12 @@ class AppConfigTest extends TestCase {
}
/**
- * @dataProvider providerSetAppValue
*
* @param bool $lazy
* @param bool $sensitive
* @param bool $expected
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('providerSetAppValue')]
public function testSetAppValueFloat(bool $lazy, bool $sensitive, bool $expected): void {
$key = 'key';
$value = 3.14;
@@ -319,11 +318,11 @@ class AppConfigTest extends TestCase {
}
/**
- * @dataProvider providerSetAppValue
*
* @param bool $lazy
* @param bool $sensitive
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('providerSetAppValue')]
public function testSetAppValueFloatException(bool $lazy, bool $sensitive): void {
$key = 'key';
$value = 3.14;
@@ -340,7 +339,7 @@ class AppConfigTest extends TestCase {
* @return array
* @see testSetAppValueBool
*/
- public function providerSetAppValueBool(): array {
+ public static function providerSetAppValueBool(): array {
return [
// lazy, expected
[false, true],
@@ -351,11 +350,11 @@ class AppConfigTest extends TestCase {
}
/**
- * @dataProvider providerSetAppValueBool
*
* @param bool $lazy
* @param bool $expected
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('providerSetAppValueBool')]
public function testSetAppValueBool(bool $lazy, bool $expected): void {
$key = 'key';
$value = true;
@@ -368,10 +367,9 @@ class AppConfigTest extends TestCase {
}
/**
- * @dataProvider providerSetAppValueBool
- *
* @param bool $lazy
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('providerSetAppValueBool')]
public function testSetAppValueBoolException(bool $lazy): void {
$key = 'key';
$value = true;
@@ -385,12 +383,12 @@ class AppConfigTest extends TestCase {
}
/**
- * @dataProvider providerSetAppValue
*
* @param bool $lazy
* @param bool $sensitive
* @param bool $expected
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('providerSetAppValue')]
public function testSetAppValueArray(bool $lazy, bool $sensitive, bool $expected): void {
$key = 'key';
$value = ['item' => true];
@@ -403,11 +401,11 @@ class AppConfigTest extends TestCase {
}
/**
- * @dataProvider providerSetAppValue
*
* @param bool $lazy
* @param bool $sensitive
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('providerSetAppValue')]
public function testSetAppValueArrayException(bool $lazy, bool $sensitive): void {
$key = 'key';
$value = ['item' => true];
@@ -456,7 +454,7 @@ class AppConfigTest extends TestCase {
* @see testGetAppValueArray
* @see testGetAppValueArrayException
*/
- public function providerGetAppValue(): array {
+ public static function providerGetAppValue(): array {
return [
// lazy, exist
[false, false],
@@ -467,11 +465,11 @@ class AppConfigTest extends TestCase {
}
/**
- * @dataProvider providerGetAppValue
*
* @param bool $lazy
* @param bool $exist
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('providerGetAppValue')]
public function testGetAppValueString(bool $lazy, bool $exist): void {
$key = 'key';
$value = 'valueString';
@@ -487,10 +485,9 @@ class AppConfigTest extends TestCase {
}
/**
- * @dataProvider providerGetAppValue
- *
* @param bool $lazy
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('providerGetAppValue')]
public function testGetAppValueStringException(bool $lazy): void {
$key = 'key';
$default = 'default';
@@ -505,11 +502,11 @@ class AppConfigTest extends TestCase {
}
/**
- * @dataProvider providerGetAppValue
*
* @param bool $lazy
* @param bool $exist
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('providerGetAppValue')]
public function testGetAppValueInt(bool $lazy, bool $exist): void {
$key = 'key';
$value = 42;
@@ -525,10 +522,9 @@ class AppConfigTest extends TestCase {
}
/**
- * @dataProvider providerGetAppValue
- *
* @param bool $lazy
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('providerGetAppValue')]
public function testGetAppValueIntException(bool $lazy): void {
$key = 'key';
$default = 17;
@@ -543,11 +539,11 @@ class AppConfigTest extends TestCase {
}
/**
- * @dataProvider providerGetAppValue
*
* @param bool $lazy
* @param bool $exist
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('providerGetAppValue')]
public function testGetAppValueFloat(bool $lazy, bool $exist): void {
$key = 'key';
$value = 3.14;
@@ -563,10 +559,9 @@ class AppConfigTest extends TestCase {
}
/**
- * @dataProvider providerGetAppValue
- *
* @param bool $lazy
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('providerGetAppValue')]
public function testGetAppValueFloatException(bool $lazy): void {
$key = 'key';
$default = 17.04;
@@ -581,11 +576,11 @@ class AppConfigTest extends TestCase {
}
/**
- * @dataProvider providerGetAppValue
*
* @param bool $lazy
* @param bool $exist
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('providerGetAppValue')]
public function testGetAppValueBool(bool $lazy, bool $exist): void {
$key = 'key';
$value = true;
@@ -601,10 +596,9 @@ class AppConfigTest extends TestCase {
}
/**
- * @dataProvider providerGetAppValue
- *
* @param bool $lazy
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('providerGetAppValue')]
public function testGetAppValueBoolException(bool $lazy): void {
$key = 'key';
$default = false;
@@ -619,11 +613,11 @@ class AppConfigTest extends TestCase {
}
/**
- * @dataProvider providerGetAppValue
*
* @param bool $lazy
* @param bool $exist
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('providerGetAppValue')]
public function testGetAppValueArray(bool $lazy, bool $exist): void {
$key = 'key';
$value = ['item' => true];
@@ -639,10 +633,9 @@ class AppConfigTest extends TestCase {
}
/**
- * @dataProvider providerGetAppValue
- *
* @param bool $lazy
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('providerGetAppValue')]
public function testGetAppValueArrayException(bool $lazy): void {
$key = 'key';
$default = [];
diff --git a/tests/lib/AppFramework/Utility/SimpleContainerTest.php b/tests/lib/AppFramework/Utility/SimpleContainerTest.php
index d3e9dec18e0..33800c7376f 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,40 +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 function __construct($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,
+ ) {
}
}
@@ -81,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);
}
}
@@ -95,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);
}
}
@@ -103,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');
}
@@ -191,7 +192,7 @@ class SimpleContainerTest extends \Test\TestCase {
$this->container->query('test'), $this->container->query('test1'));
}
- public function sanitizeNameProvider() {
+ public static function sanitizeNameProvider(): array {
return [
['ABC\\Foo', 'ABC\\Foo'],
['\\ABC\\Foo', '\\ABC\\Foo'],
@@ -200,9 +201,7 @@ class SimpleContainerTest extends \Test\TestCase {
];
}
- /**
- * @dataProvider sanitizeNameProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('sanitizeNameProvider')]
public function testSanitizeName($register, $query): void {
$this->container->registerService($register, function () {
return 'abc';
@@ -212,11 +211,13 @@ 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'
);
+ /* Use the object to trigger DI on PHP >= 8.4 */
+ get_object_vars($object);
}
public function testRegisterFactory(): void {
@@ -241,9 +242,13 @@ class SimpleContainerTest extends \Test\TestCase {
}
public function testQueryUntypedNullable(): void {
- $this->expectException(\OCP\AppFramework\QueryException::class);
+ $this->expectException(QueryException::class);
- $this->container->query(ClassNullableUntypedConstructorArg::class);
+ $object = $this->container->query(
+ ClassNullableUntypedConstructorArg::class
+ );
+ /* Use the object to trigger DI on PHP >= 8.4 */
+ get_object_vars($object);
}
public function testQueryTypedNullable(): void {
diff --git a/tests/lib/AppScriptSortTest.php b/tests/lib/AppScriptSortTest.php
index ae7b5c326ec..7dc2bde1897 100644
--- a/tests/lib/AppScriptSortTest.php
+++ b/tests/lib/AppScriptSortTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
diff --git a/tests/lib/AppTest.php b/tests/lib/AppTest.php
index 3e4d762a0a4..e174a59bfaf 100644
--- a/tests/lib/AppTest.php
+++ b/tests/lib/AppTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -10,6 +11,7 @@ namespace Test;
use OC\App\AppManager;
use OC\App\InfoParser;
use OC\AppConfig;
+use OC\Config\ConfigManager;
use OCP\EventDispatcher\IEventDispatcher;
use OCP\IAppConfig;
use OCP\ICacheFactory;
@@ -18,6 +20,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;
@@ -34,7 +37,7 @@ class AppTest extends \Test\TestCase {
public const TEST_GROUP1 = 'group1';
public const TEST_GROUP2 = 'group2';
- public function appVersionsProvider() {
+ public static function appVersionsProvider(): array {
return [
// exact match
[
@@ -311,9 +314,7 @@ class AppTest extends \Test\TestCase {
];
}
- /**
- * @dataProvider appVersionsProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('appVersionsProvider')]
public function testIsAppCompatible($ocVersion, $appInfo, $expectedResult): void {
$this->assertEquals($expectedResult, \OC_App::isAppCompatible($ocVersion, $appInfo));
}
@@ -335,7 +336,7 @@ class AppTest extends \Test\TestCase {
/**
* Providers for the app config values
*/
- public function appConfigValuesProvider() {
+ public static function appConfigValuesProvider(): array {
return [
// logged in user1
[
@@ -465,12 +466,11 @@ class AppTest extends \Test\TestCase {
/**
* Test enabled apps
- *
- * @dataProvider appConfigValuesProvider
*/
+ #[\PHPUnit\Framework\Attributes\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?');
@@ -485,7 +485,7 @@ class AppTest extends \Test\TestCase {
\OC_User::setUserId($user);
$this->setupAppConfigMock()->expects($this->once())
- ->method('getValues')
+ ->method('searchValues')
->willReturn(
[
'app3' => 'yes',
@@ -495,7 +495,6 @@ class AppTest extends \Test\TestCase {
'appforgroup2' => '["group2"]',
'appforgroup12' => '["group2","group1"]',
]
-
);
$apps = \OC_App::getEnabledApps(false, $forceAll);
@@ -518,19 +517,18 @@ 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);
$this->setupAppConfigMock()->expects($this->once())
- ->method('getValues')
+ ->method('searchValues')
->willReturn(
[
'app3' => 'yes',
'app2' => 'no',
]
-
);
$apps = \OC_App::getEnabledApps();
@@ -550,8 +548,8 @@ class AppTest extends \Test\TestCase {
private function setupAppConfigMock() {
/** @var AppConfig|MockObject */
$appConfig = $this->getMockBuilder(AppConfig::class)
- ->onlyMethods(['getValues'])
- ->setConstructorArgs([\OCP\Server::get(IDBConnection::class)])
+ ->onlyMethods(['searchValues'])
+ ->setConstructorArgs([Server::get(IDBConnection::class)])
->disableOriginalConstructor()
->getMock();
@@ -567,13 +565,14 @@ 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),
+ Server::get(ConfigManager::class),
));
}
@@ -591,7 +590,7 @@ class AppTest extends \Test\TestCase {
/**
* Providers for the app data values
*/
- public function appDataProvider() {
+ public static function appDataProvider(): array {
return [
[
['description' => " \t This is a multiline \n test with \n \t \n \n some new lines "],
@@ -622,10 +621,10 @@ class AppTest extends \Test\TestCase {
/**
* Test app info parser
*
- * @dataProvider appDataProvider
* @param array $data
* @param array $expected
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('appDataProvider')]
public function testParseAppInfo(array $data, array $expected): void {
$this->assertSame($expected, \OC_App::parseAppInfo($data));
}
diff --git a/tests/lib/Archive/TARTest.php b/tests/lib/Archive/TARTest.php
index 36629a0273f..e77f97ac8e1 100644
--- a/tests/lib/Archive/TARTest.php
+++ b/tests/lib/Archive/TARTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -8,6 +9,8 @@
namespace Test\Archive;
use OC\Archive\TAR;
+use OCP\ITempManager;
+use OCP\Server;
class TARTest extends TestBase {
protected function getExisting() {
@@ -16,6 +19,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..1b7f7d3325a 100644
--- a/tests/lib/Archive/TestBase.php
+++ b/tests/lib/Archive/TestBase.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -7,6 +8,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 +61,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 +95,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 +115,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 25707e4b051..0996d5abf61 100644
--- a/tests/lib/Archive/ZIPTest.php
+++ b/tests/lib/Archive/ZIPTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -8,6 +9,8 @@
namespace Test\Archive;
use OC\Archive\ZIP;
+use OCP\ITempManager;
+use OCP\Server;
class ZIPTest extends TestBase {
protected function getExisting() {
@@ -16,6 +19,10 @@ class ZIPTest extends TestBase {
}
protected function getNew() {
- return new ZIP(\OC::$server->getTempManager()->getTempBaseDir() . '/newArchive.zip');
+ $newZip = Server::get(ITempManager::class)->getTempBaseDir() . '/newArchive.zip';
+ if (file_exists($newZip)) {
+ unlink($newZip);
+ }
+ return new ZIP($newZip);
}
}
diff --git a/tests/lib/Authentication/Listeners/UserDeletedTokenCleanupListenerTest.php b/tests/lib/Authentication/Listeners/UserDeletedTokenCleanupListenerTest.php
index f91371a86b7..1861a5b2150 100644
--- a/tests/lib/Authentication/Listeners/UserDeletedTokenCleanupListenerTest.php
+++ b/tests/lib/Authentication/Listeners/UserDeletedTokenCleanupListenerTest.php
@@ -83,13 +83,18 @@ class UserDeletedTokenCleanupListenerTest extends TestCase {
$token2,
$token3,
]);
+
+ $calls = [
+ ['user123', 1],
+ ['user123', 2],
+ ['user123', 3],
+ ];
$this->manager->expects($this->exactly(3))
->method('invalidateTokenById')
- ->withConsecutive(
- ['user123', 1],
- ['user123', 2],
- ['user123', 3]
- );
+ ->willReturnCallback(function () use (&$calls): void {
+ $expected = array_shift($calls);
+ $this->assertEquals($expected, func_get_args());
+ });
$this->logger->expects($this->never())
->method('error');
diff --git a/tests/lib/Authentication/Login/ALoginCommandTest.php b/tests/lib/Authentication/Login/ALoginTestCommand.php
index 2ab59835bfe..b955b20beba 100644
--- a/tests/lib/Authentication/Login/ALoginCommandTest.php
+++ b/tests/lib/Authentication/Login/ALoginTestCommand.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2019 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
@@ -8,14 +9,13 @@ declare(strict_types=1);
namespace Test\Authentication\Login;
-use OC\Authentication\Login\ALoginCommand;
use OC\Authentication\Login\LoginData;
use OCP\IRequest;
use OCP\IUser;
use PHPUnit\Framework\MockObject\MockObject;
use Test\TestCase;
-abstract class ALoginCommandTest extends TestCase {
+abstract class ALoginTestCommand extends TestCase {
/** @var IRequest|MockObject */
protected $request;
@@ -36,7 +36,7 @@ abstract class ALoginCommandTest extends TestCase {
/** @var IUser|MockObject */
protected $user;
- /** @var ALoginCommand */
+ /** @var ALoginTestCommand */
protected $cmd;
protected function setUp(): void {
diff --git a/tests/lib/Authentication/Login/ClearLostPasswordTokensCommandTest.php b/tests/lib/Authentication/Login/ClearLostPasswordTokensCommandTest.php
index 025612e963e..5ff2da28946 100644
--- a/tests/lib/Authentication/Login/ClearLostPasswordTokensCommandTest.php
+++ b/tests/lib/Authentication/Login/ClearLostPasswordTokensCommandTest.php
@@ -13,7 +13,7 @@ use OC\Authentication\Login\ClearLostPasswordTokensCommand;
use OCP\IConfig;
use PHPUnit\Framework\MockObject\MockObject;
-class ClearLostPasswordTokensCommandTest extends ALoginCommandTest {
+class ClearLostPasswordTokensCommandTest extends ALoginTestCommand {
/** @var IConfig|MockObject */
private $config;
diff --git a/tests/lib/Authentication/Login/CompleteLoginCommandTest.php b/tests/lib/Authentication/Login/CompleteLoginCommandTest.php
index 4ddb26e7648..5b08368671f 100644
--- a/tests/lib/Authentication/Login/CompleteLoginCommandTest.php
+++ b/tests/lib/Authentication/Login/CompleteLoginCommandTest.php
@@ -13,7 +13,7 @@ use OC\Authentication\Login\CompleteLoginCommand;
use OC\User\Session;
use PHPUnit\Framework\MockObject\MockObject;
-class CompleteLoginCommandTest extends ALoginCommandTest {
+class CompleteLoginCommandTest extends ALoginTestCommand {
/** @var Session|MockObject */
private $session;
diff --git a/tests/lib/Authentication/Login/CreateSessionTokenCommandTest.php b/tests/lib/Authentication/Login/CreateSessionTokenCommandTest.php
index fd6a154ef5d..668c0a6d6ea 100644
--- a/tests/lib/Authentication/Login/CreateSessionTokenCommandTest.php
+++ b/tests/lib/Authentication/Login/CreateSessionTokenCommandTest.php
@@ -15,7 +15,7 @@ use OC\User\Session;
use OCP\IConfig;
use PHPUnit\Framework\MockObject\MockObject;
-class CreateSessionTokenCommandTest extends ALoginCommandTest {
+class CreateSessionTokenCommandTest extends ALoginTestCommand {
/** @var IConfig|MockObject */
private $config;
diff --git a/tests/lib/Authentication/Login/FinishRememberedLoginCommandTest.php b/tests/lib/Authentication/Login/FinishRememberedLoginCommandTest.php
index 4eb4f94055f..499abafa6e3 100644
--- a/tests/lib/Authentication/Login/FinishRememberedLoginCommandTest.php
+++ b/tests/lib/Authentication/Login/FinishRememberedLoginCommandTest.php
@@ -14,7 +14,7 @@ use OC\User\Session;
use OCP\IConfig;
use PHPUnit\Framework\MockObject\MockObject;
-class FinishRememberedLoginCommandTest extends ALoginCommandTest {
+class FinishRememberedLoginCommandTest extends ALoginTestCommand {
/** @var Session|MockObject */
private $userSession;
/** @var IConfig|MockObject */
diff --git a/tests/lib/Authentication/Login/LoggedInCheckCommandTest.php b/tests/lib/Authentication/Login/LoggedInCheckCommandTest.php
index ce783050921..7b011d70673 100644
--- a/tests/lib/Authentication/Login/LoggedInCheckCommandTest.php
+++ b/tests/lib/Authentication/Login/LoggedInCheckCommandTest.php
@@ -15,7 +15,7 @@ use OCP\EventDispatcher\IEventDispatcher;
use PHPUnit\Framework\MockObject\MockObject;
use Psr\Log\LoggerInterface;
-class LoggedInCheckCommandTest extends ALoginCommandTest {
+class LoggedInCheckCommandTest extends ALoginTestCommand {
/** @var LoggerInterface|MockObject */
private $logger;
diff --git a/tests/lib/Authentication/Login/PreLoginHookCommandTest.php b/tests/lib/Authentication/Login/PreLoginHookCommandTest.php
index b6d826f1c21..0e5096baf55 100644
--- a/tests/lib/Authentication/Login/PreLoginHookCommandTest.php
+++ b/tests/lib/Authentication/Login/PreLoginHookCommandTest.php
@@ -14,7 +14,7 @@ use OC\User\Manager;
use OCP\IUserManager;
use PHPUnit\Framework\MockObject\MockObject;
-class PreLoginHookCommandTest extends ALoginCommandTest {
+class PreLoginHookCommandTest extends ALoginTestCommand {
/** @var IUserManager|MockObject */
private $userManager;
diff --git a/tests/lib/Authentication/Login/SetUserTimezoneCommandTest.php b/tests/lib/Authentication/Login/SetUserTimezoneCommandTest.php
index d4e15f68257..fb8240c4b1e 100644
--- a/tests/lib/Authentication/Login/SetUserTimezoneCommandTest.php
+++ b/tests/lib/Authentication/Login/SetUserTimezoneCommandTest.php
@@ -14,7 +14,7 @@ use OCP\IConfig;
use OCP\ISession;
use PHPUnit\Framework\MockObject\MockObject;
-class SetUserTimezoneCommandTest extends ALoginCommandTest {
+class SetUserTimezoneCommandTest extends ALoginTestCommand {
/** @var IConfig|MockObject */
private $config;
diff --git a/tests/lib/Authentication/Login/TwoFactorCommandTest.php b/tests/lib/Authentication/Login/TwoFactorCommandTest.php
index af7d7446bfb..a95e4b50cbc 100644
--- a/tests/lib/Authentication/Login/TwoFactorCommandTest.php
+++ b/tests/lib/Authentication/Login/TwoFactorCommandTest.php
@@ -18,7 +18,7 @@ use OCP\Authentication\TwoFactorAuth\IProvider as ITwoFactorAuthProvider;
use OCP\IURLGenerator;
use PHPUnit\Framework\MockObject\MockObject;
-class TwoFactorCommandTest extends ALoginCommandTest {
+class TwoFactorCommandTest extends ALoginTestCommand {
/** @var Manager|MockObject */
private $twoFactorManager;
diff --git a/tests/lib/Authentication/Login/UidLoginCommandTest.php b/tests/lib/Authentication/Login/UidLoginCommandTest.php
index 3073aac1859..daae34e2212 100644
--- a/tests/lib/Authentication/Login/UidLoginCommandTest.php
+++ b/tests/lib/Authentication/Login/UidLoginCommandTest.php
@@ -13,7 +13,7 @@ use OC\Authentication\Login\UidLoginCommand;
use OC\User\Manager;
use PHPUnit\Framework\MockObject\MockObject;
-class UidLoginCommandTest extends ALoginCommandTest {
+class UidLoginCommandTest extends ALoginTestCommand {
/** @var Manager|MockObject */
private $userManager;
diff --git a/tests/lib/Authentication/Login/UpdateLastPasswordConfirmCommandTest.php b/tests/lib/Authentication/Login/UpdateLastPasswordConfirmCommandTest.php
index f5760f3f232..1a845a05c23 100644
--- a/tests/lib/Authentication/Login/UpdateLastPasswordConfirmCommandTest.php
+++ b/tests/lib/Authentication/Login/UpdateLastPasswordConfirmCommandTest.php
@@ -13,7 +13,7 @@ use OC\Authentication\Login\UpdateLastPasswordConfirmCommand;
use OCP\ISession;
use PHPUnit\Framework\MockObject\MockObject;
-class UpdateLastPasswordConfirmCommandTest extends ALoginCommandTest {
+class UpdateLastPasswordConfirmCommandTest extends ALoginTestCommand {
/** @var ISession|MockObject */
private $session;
diff --git a/tests/lib/Authentication/Login/UserDisabledCheckCommandTest.php b/tests/lib/Authentication/Login/UserDisabledCheckCommandTest.php
index 84b1018e5fa..ee4e171d443 100644
--- a/tests/lib/Authentication/Login/UserDisabledCheckCommandTest.php
+++ b/tests/lib/Authentication/Login/UserDisabledCheckCommandTest.php
@@ -15,7 +15,7 @@ use OCP\IUserManager;
use PHPUnit\Framework\MockObject\MockObject;
use Psr\Log\LoggerInterface;
-class UserDisabledCheckCommandTest extends ALoginCommandTest {
+class UserDisabledCheckCommandTest extends ALoginTestCommand {
/** @var IUserManager|MockObject */
private $userManager;
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 4fde9817d09..58bbe236248 100644
--- a/tests/lib/Authentication/Token/ManagerTest.php
+++ b/tests/lib/Authentication/Token/ManagerTest.php
@@ -128,10 +128,10 @@ class ManagerTest extends TestCase {
$this->assertSame(121, mb_strlen($actual->getName()));
}
- public function tokenData(): array {
+ public static function tokenData(): array {
return [
[new PublicKeyToken()],
- [$this->createMock(IToken::class)],
+ [IToken::class],
];
}
@@ -157,10 +157,12 @@ class ManagerTest extends TestCase {
}
}
- /**
- * @dataProvider tokenData
- */
- public function testUpdateToken(IToken $token): void {
+ #[\PHPUnit\Framework\Attributes\DataProvider('tokenData')]
+ public function testUpdateToken(IToken|string $token): void {
+ if (is_string($token)) {
+ $token = $this->createMock($token);
+ }
+
$this->setNoCall($token);
$this->setCall($token, 'updateToken');
$this->setException($token);
@@ -168,10 +170,12 @@ class ManagerTest extends TestCase {
$this->manager->updateToken($token);
}
- /**
- * @dataProvider tokenData
- */
- public function testUpdateTokenActivity(IToken $token): void {
+ #[\PHPUnit\Framework\Attributes\DataProvider('tokenData')]
+ public function testUpdateTokenActivity(IToken|string $token): void {
+ if (is_string($token)) {
+ $token = $this->createMock($token);
+ }
+
$this->setNoCall($token);
$this->setCall($token, 'updateTokenActivity');
$this->setException($token);
@@ -179,10 +183,12 @@ class ManagerTest extends TestCase {
$this->manager->updateTokenActivity($token);
}
- /**
- * @dataProvider tokenData
- */
- public function testGetPassword(IToken $token): void {
+ #[\PHPUnit\Framework\Attributes\DataProvider('tokenData')]
+ public function testGetPassword(IToken|string $token): void {
+ if (is_string($token)) {
+ $token = $this->createMock($token);
+ }
+
$this->setNoCall($token);
$this->setCall($token, 'getPassword', 'password');
$this->setException($token);
@@ -192,10 +198,12 @@ class ManagerTest extends TestCase {
$this->assertSame('password', $result);
}
- /**
- * @dataProvider tokenData
- */
- public function testSetPassword(IToken $token): void {
+ #[\PHPUnit\Framework\Attributes\DataProvider('tokenData')]
+ public function testSetPassword(IToken|string $token): void {
+ if (is_string($token)) {
+ $token = $this->createMock($token);
+ }
+
$this->setNoCall($token);
$this->setCall($token, 'setPassword');
$this->setException($token);
@@ -358,13 +366,18 @@ class ManagerTest extends TestCase {
->method('getTokenByUser')
->with('theUser')
->willReturn([$t1, $t2]);
+
+ $calls = [
+ ['theUser', 123],
+ ['theUser', 456],
+ ];
$this->publicKeyTokenProvider
->expects($this->exactly(2))
->method('invalidateTokenById')
- ->withConsecutive(
- ['theUser', 123],
- ['theUser', 456],
- );
+ ->willReturnCallback(function () use (&$calls): void {
+ $expected = array_shift($calls);
+ $this->assertEquals($expected, func_get_args());
+ });
$this->manager->invalidateTokensOfUser('theUser', null);
}
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 6097c1f482d..7e7f949965f 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';
@@ -304,12 +305,17 @@ class PublicKeyTokenProviderTest extends TestCase {
}
public function testInvalidateToken(): void {
+ $calls = [
+ [hash('sha512', 'token7' . '1f4h9s')],
+ [hash('sha512', 'token7')]
+ ];
+
$this->mapper->expects($this->exactly(2))
->method('invalidate')
- ->withConsecutive(
- [hash('sha512', 'token7' . '1f4h9s')],
- [hash('sha512', 'token7')]
- );
+ ->willReturnCallback(function () use (&$calls): void {
+ $expected = array_shift($calls);
+ $this->assertEquals($expected, func_get_args());
+ });
$this->tokenProvider->invalidateToken('token7');
}
@@ -336,14 +342,19 @@ class PublicKeyTokenProviderTest extends TestCase {
['token_auth_wipe_token_retention', $wipeTokenLifetime, 500],
['token_auth_token_retention', 60 * 60 * 24 * 365, 800],
]);
+
+ $calls = [
+ [$this->time - 150, IToken::TEMPORARY_TOKEN, IToken::DO_NOT_REMEMBER],
+ [$this->time - 300, IToken::TEMPORARY_TOKEN, IToken::REMEMBER],
+ [$this->time - 500, IToken::WIPE_TOKEN, null],
+ [$this->time - 800, IToken::PERMANENT_TOKEN, null],
+ ];
$this->mapper->expects($this->exactly(4))
->method('invalidateOld')
- ->withConsecutive(
- [$this->time - 150, IToken::TEMPORARY_TOKEN, IToken::DO_NOT_REMEMBER],
- [$this->time - 300, IToken::TEMPORARY_TOKEN, IToken::REMEMBER],
- [$this->time - 500, IToken::WIPE_TOKEN, null],
- [$this->time - 800, IToken::PERMANENT_TOKEN, null],
- );
+ ->willReturnCallback(function () use (&$calls): void {
+ $expected = array_shift($calls);
+ $this->assertEquals($expected, func_get_args());
+ });
$this->tokenProvider->invalidateOldTokens();
}
@@ -375,12 +386,12 @@ class PublicKeyTokenProviderTest extends TestCase {
->expects($this->once())
->method('insert')
->with($this->callback(function (PublicKeyToken $token) use ($user, $uid, $name) {
- return $token->getUID() === $uid &&
- $token->getLoginName() === $user &&
- $token->getName() === $name &&
- $token->getType() === IToken::DO_NOT_REMEMBER &&
- $token->getLastActivity() === $this->time &&
- $token->getPassword() === null;
+ return $token->getUID() === $uid
+ && $token->getLoginName() === $user
+ && $token->getName() === $name
+ && $token->getType() === IToken::DO_NOT_REMEMBER
+ && $token->getLastActivity() === $this->time
+ && $token->getPassword() === null;
}));
$this->mapper
->expects($this->once())
@@ -415,13 +426,13 @@ class PublicKeyTokenProviderTest extends TestCase {
->expects($this->once())
->method('insert')
->with($this->callback(function (PublicKeyToken $token) use ($user, $uid, $name): bool {
- return $token->getUID() === $uid &&
- $token->getLoginName() === $user &&
- $token->getName() === $name &&
- $token->getType() === IToken::DO_NOT_REMEMBER &&
- $token->getLastActivity() === $this->time &&
- $token->getPassword() !== null &&
- $this->tokenProvider->getPassword($token, 'newIdtokentokentokentoken') === 'password';
+ return $token->getUID() === $uid
+ && $token->getLoginName() === $user
+ && $token->getName() === $name
+ && $token->getType() === IToken::DO_NOT_REMEMBER
+ && $token->getLastActivity() === $this->time
+ && $token->getPassword() !== null
+ && $this->tokenProvider->getPassword($token, 'newIdtokentokentokentoken') === 'password';
}));
$this->mapper
->expects($this->once())
@@ -453,16 +464,17 @@ class PublicKeyTokenProviderTest extends TestCase {
public function testGetInvalidToken(): void {
$this->expectException(InvalidTokenException::class);
+ $calls = [
+ 'unhashedTokentokentokentokentoken' . '1f4h9s',
+ 'unhashedTokentokentokentokentoken',
+ ];
$this->mapper->expects($this->exactly(2))
->method('getToken')
- ->withConsecutive(
- [$this->callback(function (string $token): bool {
- return hash('sha512', 'unhashedTokentokentokentokentoken' . '1f4h9s') === $token;
- })],
- [$this->callback(function (string $token): bool {
- return hash('sha512', 'unhashedTokentokentokentokentoken') === $token;
- })]
- )->willThrowException(new DoesNotExistException('nope'));
+ ->willReturnCallback(function (string $token) use (&$calls): void {
+ $expected = array_shift($calls);
+ $this->assertEquals(hash('sha512', $expected), $token);
+ throw new DoesNotExistException('nope');
+ });
$this->tokenProvider->getToken('unhashedTokentokentokentokentoken');
}
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/EnforcementStateTest.php b/tests/lib/Authentication/TwoFactorAuth/EnforcementStateTest.php
index 5323a36867a..f1d38c10801 100644
--- a/tests/lib/Authentication/TwoFactorAuth/EnforcementStateTest.php
+++ b/tests/lib/Authentication/TwoFactorAuth/EnforcementStateTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2018 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
diff --git a/tests/lib/Authentication/TwoFactorAuth/ManagerTest.php b/tests/lib/Authentication/TwoFactorAuth/ManagerTest.php
index 52792c29ed0..a2bed8a3652 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;
@@ -204,7 +205,7 @@ class ManagerTest extends TestCase {
$this->assertTrue($this->manager->isTwoFactorAuthenticated($this->user));
}
- public function providerStatesFixData(): array {
+ public static function providerStatesFixData(): array {
return [
[false, false],
[true, true],
@@ -217,9 +218,8 @@ class ManagerTest extends TestCase {
* enabled providers.
*
* If any of these providers is active, 2FA is enabled
- *
- * @dataProvider providerStatesFixData
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('providerStatesFixData')]
public function testIsTwoFactorAuthenticatedFixesProviderStates(bool $providerEnabled, bool $expected): void {
$this->providerRegistry->expects($this->once())
->method('getProviderStates')
@@ -356,12 +356,18 @@ class ManagerTest extends TestCase {
->method('get')
->with('two_factor_remember_login')
->willReturn(false);
+
+ $calls = [
+ ['two_factor_auth_uid'],
+ ['two_factor_remember_login'],
+ ];
$this->session->expects($this->exactly(2))
->method('remove')
- ->withConsecutive(
- ['two_factor_auth_uid'],
- ['two_factor_remember_login']
- );
+ ->willReturnCallback(function () use (&$calls): void {
+ $expected = array_shift($calls);
+ $this->assertEquals($expected, func_get_args());
+ });
+
$this->session->expects($this->once())
->method('set')
->with(Manager::SESSION_UID_DONE, 'jos');
@@ -398,7 +404,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);
@@ -474,18 +480,23 @@ class ManagerTest extends TestCase {
public function testNeedsSecondFactor(): void {
$user = $this->createMock(IUser::class);
+
+ $calls = [
+ ['app_password'],
+ ['two_factor_auth_uid'],
+ [Manager::SESSION_UID_DONE],
+ ];
$this->session->expects($this->exactly(3))
->method('exists')
- ->withConsecutive(
- ['app_password'],
- ['two_factor_auth_uid'],
- [Manager::SESSION_UID_DONE],
- )
- ->willReturn(false);
+ ->willReturnCallback(function () use (&$calls) {
+ $expected = array_shift($calls);
+ $this->assertEquals($expected, func_get_args());
+ return false;
+ });
$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);
@@ -513,7 +524,7 @@ class ManagerTest extends TestCase {
$this->timeFactory,
$this->dispatcher,
])
- ->setMethods(['loadTwoFactorApp', 'isTwoFactorAuthenticated'])// Do not actually load the apps
+ ->onlyMethods(['isTwoFactorAuthenticated'])// Do not actually load the apps
->getMock();
$manager->method('isTwoFactorAuthenticated')
@@ -550,16 +561,20 @@ class ManagerTest extends TestCase {
$this->user->method('getUID')
->willReturn('ferdinand');
+ $calls = [
+ ['two_factor_auth_uid', 'ferdinand'],
+ ['two_factor_remember_login', true],
+ ];
$this->session->expects($this->exactly(2))
->method('set')
- ->withConsecutive(
- ['two_factor_auth_uid', 'ferdinand'],
- ['two_factor_remember_login', true]
- );
+ ->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);
@@ -580,16 +595,20 @@ class ManagerTest extends TestCase {
$this->user->method('getUID')
->willReturn('ferdinand');
+ $calls = [
+ ['two_factor_auth_uid', 'ferdinand'],
+ ['two_factor_remember_login', false],
+ ];
$this->session->expects($this->exactly(2))
->method('set')
- ->withConsecutive(
- ['two_factor_auth_uid', 'ferdinand'],
- ['two_factor_remember_login', false]
- );
+ ->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);
@@ -650,7 +669,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);
@@ -685,7 +704,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([]);
@@ -710,21 +729,29 @@ class ManagerTest extends TestCase {
'42', '43', '44'
]);
+ $deleteUserValueCalls = [
+ ['theUserId', 'login_token_2fa', '42'],
+ ['theUserId', 'login_token_2fa', '43'],
+ ['theUserId', 'login_token_2fa', '44'],
+ ];
$this->config->expects($this->exactly(3))
->method('deleteUserValue')
- ->withConsecutive(
- ['theUserId', 'login_token_2fa', '42'],
- ['theUserId', 'login_token_2fa', '43'],
- ['theUserId', 'login_token_2fa', '44'],
- );
+ ->willReturnCallback(function () use (&$deleteUserValueCalls): void {
+ $expected = array_shift($deleteUserValueCalls);
+ $this->assertEquals($expected, func_get_args());
+ });
+ $invalidateCalls = [
+ ['theUserId', 42],
+ ['theUserId', 43],
+ ['theUserId', 44],
+ ];
$this->tokenProvider->expects($this->exactly(3))
->method('invalidateTokenById')
- ->withConsecutive(
- ['theUserId', 42],
- ['theUserId', 43],
- ['theUserId', 44],
- );
+ ->willReturnCallback(function () use (&$invalidateCalls): void {
+ $expected = array_shift($invalidateCalls);
+ $this->assertEquals($expected, func_get_args());
+ });
$this->manager->clearTwoFactorPending('theUserId');
}
@@ -736,22 +763,28 @@ class ManagerTest extends TestCase {
'42', '43', '44'
]);
+ $deleteUserValueCalls = [
+ ['theUserId', 'login_token_2fa', '42'],
+ ['theUserId', 'login_token_2fa', '43'],
+ ['theUserId', 'login_token_2fa', '44'],
+ ];
$this->config->expects($this->exactly(3))
->method('deleteUserValue')
- ->withConsecutive(
- ['theUserId', 'login_token_2fa', '42'],
- ['theUserId', 'login_token_2fa', '43'],
- ['theUserId', 'login_token_2fa', '44'],
- );
+ ->willReturnCallback(function () use (&$deleteUserValueCalls): void {
+ $expected = array_shift($deleteUserValueCalls);
+ $this->assertEquals($expected, func_get_args());
+ });
+ $invalidateCalls = [
+ ['theUserId', 42],
+ ['theUserId', 43],
+ ['theUserId', 44],
+ ];
$this->tokenProvider->expects($this->exactly(3))
->method('invalidateTokenById')
- ->withConsecutive(
- ['theUserId', 42],
- ['theUserId', 43],
- ['theUserId', 44],
- )
- ->willReturnCallback(function ($user, $tokenId) {
+ ->willReturnCallback(function ($user, $tokenId) use (&$invalidateCalls): void {
+ $expected = array_shift($invalidateCalls);
+ $this->assertEquals($expected, func_get_args());
if ($tokenId === 43) {
throw new DoesNotExistException('token does not exist');
}
diff --git a/tests/lib/Authentication/TwoFactorAuth/ProviderManagerTest.php b/tests/lib/Authentication/TwoFactorAuth/ProviderManagerTest.php
index 34248f11f21..a1f2a6fa69a 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;
@@ -41,9 +42,9 @@ 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);
@@ -87,9 +88,9 @@ class ProviderManagerTest extends TestCase {
$this->assertTrue($res);
}
-
+
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 77e619d03a2..2018dc1a634 100644
--- a/tests/lib/Authentication/TwoFactorAuth/RegistryTest.php
+++ b/tests/lib/Authentication/TwoFactorAuth/RegistryTest.php
@@ -119,12 +119,17 @@ class RegistryTest extends TestCase {
'provider_id' => 'twofactor_u2f',
]
]);
+
+ $calls = [
+ [new TwoFactorProviderDisabled('twofactor_u2f')],
+ [new TwoFactorProviderUserDeleted($user, 'twofactor_u2f')],
+ ];
$this->dispatcher->expects($this->exactly(2))
->method('dispatchTyped')
- ->withConsecutive(
- [new TwoFactorProviderDisabled('twofactor_u2f')],
- [new TwoFactorProviderUserDeleted($user, 'twofactor_u2f')],
- );
+ ->willReturnCallback(function () use (&$calls): void {
+ $expected = array_shift($calls);
+ $this->assertEquals($expected, func_get_args());
+ });
$this->registry->deleteUserData($user);
}
diff --git a/tests/lib/AutoLoaderTest.php b/tests/lib/AutoLoaderTest.php
deleted file mode 100644
index 72d4a2e94cf..00000000000
--- a/tests/lib/AutoLoaderTest.php
+++ /dev/null
@@ -1,57 +0,0 @@
-<?php
-/**
- * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
- * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
- * SPDX-License-Identifier: AGPL-3.0-or-later
- */
-
-namespace Test;
-
-class AutoLoaderTest extends TestCase {
- /**
- * @var \OC\Autoloader $loader
- */
- private $loader;
-
- protected function setUp(): void {
- parent::setUp();
- $this->loader = new \OC\AutoLoader([]);
- }
-
- public function testLegacyPath(): void {
- $this->assertEquals([
- \OC::$SERVERROOT . '/lib/private/legacy/json.php',
- ], $this->loader->findClass('OC_JSON'));
- }
-
- public function testLoadTestTestCase(): void {
- $this->assertEquals([
- \OC::$SERVERROOT . '/tests/lib/TestCase.php'
- ], $this->loader->findClass('Test\TestCase'));
- }
-
- public function testLoadCore(): void {
- $this->assertEquals([
- \OC::$SERVERROOT . '/lib/private/legacy/foo/bar.php',
- ], $this->loader->findClass('OC_Foo_Bar'));
- }
-
- public function testLoadPublicNamespace(): void {
- $this->assertEquals([], $this->loader->findClass('OCP\Foo\Bar'));
- }
-
- public function testLoadAppNamespace(): void {
- $result = $this->loader->findClass('OCA\Files\Foobar');
- $this->assertEquals(2, count($result));
- $this->assertStringEndsWith('apps/files/foobar.php', $result[0]);
- $this->assertStringEndsWith('apps/files/lib/foobar.php', $result[1]);
- }
-
- public function testLoadCoreNamespaceCore(): void {
- $this->assertEquals([], $this->loader->findClass('OC\Core\Foo\Bar'));
- }
-
- public function testLoadCoreNamespaceSettings(): void {
- $this->assertEquals([], $this->loader->findClass('OC\Settings\Foo\Bar'));
- }
-}
diff --git a/tests/lib/Avatar/AvatarManagerTest.php b/tests/lib/Avatar/AvatarManagerTest.php
index 25e8e1563f5..23d3b9d1c2a 100644
--- a/tests/lib/Avatar/AvatarManagerTest.php
+++ b/tests/lib/Avatar/AvatarManagerTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -186,7 +187,7 @@ class AvatarManagerTest extends \Test\TestCase {
$this->assertEquals($expected, $this->avatarManager->getAvatar('vaLid-USER'));
}
- public function dataGetAvatarScopes() {
+ public static function dataGetAvatarScopes(): array {
return [
// public access cannot see real avatar
[IAccountManager::SCOPE_PRIVATE, true, false, true],
@@ -203,9 +204,7 @@ class AvatarManagerTest extends \Test\TestCase {
];
}
- /**
- * @dataProvider dataGetAvatarScopes
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataGetAvatarScopes')]
public function testGetAvatarScopes($avatarScope, $isPublicCall, $isKnownUser, $expectedPlaceholder): void {
if ($isPublicCall) {
$requestingUser = null;
diff --git a/tests/lib/Avatar/UserAvatarTest.php b/tests/lib/Avatar/UserAvatarTest.php
index 0e2bfe6872f..03a868c7854 100644
--- a/tests/lib/Avatar/UserAvatarTest.php
+++ b/tests/lib/Avatar/UserAvatarTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -7,8 +8,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;
@@ -24,10 +27,10 @@ class UserAvatarTest extends \Test\TestCase {
/** @var \OC\Avatar\UserAvatar */
private $avatar;
- /** @var \OC\User\User | \PHPUnit\Framework\MockObject\MockObject $user */
+ /** @var User|\PHPUnit\Framework\MockObject\MockObject $user */
private $user;
- /** @var \OCP\IConfig|\PHPUnit\Framework\MockObject\MockObject */
+ /** @var IConfig|\PHPUnit\Framework\MockObject\MockObject */
private $config;
protected function setUp(): void {
@@ -41,7 +44,7 @@ class UserAvatarTest extends \Test\TestCase {
$this->avatar = $this->getUserAvatar($this->user);
}
- public function avatarTextData() {
+ public static function avatarTextData(): array {
return [
['', '?'],
['matchish', 'M'],
@@ -56,7 +59,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 +147,7 @@ class UserAvatarTest extends \Test\TestCase {
if ($path === 'avatar.png') {
return $file;
} else {
- throw new \OCP\Files\NotFoundException;
+ throw new NotFoundException;
}
}
);
@@ -244,9 +247,7 @@ class UserAvatarTest extends \Test\TestCase {
}
- /**
- * @dataProvider avatarTextData
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('avatarTextData')]
public function testGetAvatarText($displayName, $expectedAvatarText): void {
$user = $this->getUserWithDisplayName($displayName);
$avatar = $this->getUserAvatar($user);
@@ -261,17 +262,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');
@@ -284,11 +285,11 @@ class UserAvatarTest extends \Test\TestCase {
}
private function getUserAvatar($user) {
- /** @var \OCP\IL10N | \PHPUnit\Framework\MockObject\MockObject $l */
+ /** @var IL10N|\PHPUnit\Framework\MockObject\MockObject $l */
$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..717db52715f 100644
--- a/tests/lib/BackgroundJob/DummyJobList.php
+++ b/tests/lib/BackgroundJob/DummyJobList.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2017-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -7,14 +8,17 @@
namespace Test\BackgroundJob;
+use OC\BackgroundJob\JobList;
use OCP\BackgroundJob\IJob;
+use OCP\BackgroundJob\Job;
+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 +42,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);
@@ -129,7 +133,7 @@ class DummyJobList extends \OC\BackgroundJob\JobList {
/**
* set the job that was last ran
*
- * @param \OCP\BackgroundJob\Job $job
+ * @param Job $job
*/
public function setLastJob(IJob $job): void {
$i = array_search($job, $this->jobs);
diff --git a/tests/lib/BackgroundJob/JobListTest.php b/tests/lib/BackgroundJob/JobListTest.php
index bf21639d3aa..d816bf707e8 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;
@@ -27,28 +30,28 @@ class JobListTest extends TestCase {
/** @var \OC\BackgroundJob\JobList */
protected $instance;
- /** @var \OCP\IDBConnection */
+ /** @var IDBConnection */
protected $connection;
- /** @var \OCP\IConfig|\PHPUnit\Framework\MockObject\MockObject */
+ /** @var IConfig|\PHPUnit\Framework\MockObject\MockObject */
protected $config;
- /** @var \OCP\AppFramework\Utility\ITimeFactory|\PHPUnit\Framework\MockObject\MockObject */
+ /** @var ITimeFactory|\PHPUnit\Framework\MockObject\MockObject */
protected $timeFactory;
private bool $ran = false;
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),
);
}
@@ -73,7 +76,7 @@ class JobListTest extends TestCase {
return $jobs;
}
- public function argumentProvider() {
+ public static function argumentProvider(): array {
return [
[null],
[false],
@@ -87,9 +90,9 @@ class JobListTest extends TestCase {
}
/**
- * @dataProvider argumentProvider
* @param $argument
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('argumentProvider')]
public function testAddRemove($argument): void {
$existingJobs = $this->getAllSorted();
$job = new TestJob();
@@ -109,9 +112,9 @@ class JobListTest extends TestCase {
}
/**
- * @dataProvider argumentProvider
* @param $argument
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('argumentProvider')]
public function testRemoveDifferentArgument($argument): void {
$existingJobs = $this->getAllSorted();
$job = new TestJob();
@@ -130,9 +133,9 @@ class JobListTest extends TestCase {
}
/**
- * @dataProvider argumentProvider
* @param $argument
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('argumentProvider')]
public function testHas($argument): void {
$job = new TestJob();
$this->assertFalse($this->instance->has($job, $argument));
@@ -146,9 +149,9 @@ class JobListTest extends TestCase {
}
/**
- * @dataProvider argumentProvider
* @param $argument
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('argumentProvider')]
public function testHasDifferentArgument($argument): void {
$job = new TestJob();
$this->instance->add($job, $argument);
@@ -238,9 +241,9 @@ class JobListTest extends TestCase {
}
/**
- * @dataProvider argumentProvider
* @param $argument
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('argumentProvider')]
public function testGetById($argument): void {
$job = new TestJob();
$this->instance->add($job, $argument);
@@ -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..b67059f0380 100644
--- a/tests/lib/BackgroundJob/JobTest.php
+++ b/tests/lib/BackgroundJob/JobTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2017-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -8,6 +9,7 @@
namespace Test\BackgroundJob;
use OCP\AppFramework\Utility\ITimeFactory;
+use OCP\Server;
use Psr\Log\LoggerInterface;
class JobTest extends \Test\TestCase {
@@ -18,7 +20,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 +29,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 +45,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..1c0946ff2f2 100644
--- a/tests/lib/BackgroundJob/QueuedJobTest.php
+++ b/tests/lib/BackgroundJob/QueuedJobTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2018-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -9,6 +10,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 +30,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..ac18530ac7f 100644
--- a/tests/lib/BackgroundJob/TestJob.php
+++ b/tests/lib/BackgroundJob/TestJob.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2020-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -8,10 +9,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 +22,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..6efb1a1fd8d 100644
--- a/tests/lib/BackgroundJob/TestParallelAwareJob.php
+++ b/tests/lib/BackgroundJob/TestParallelAwareJob.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2023 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
@@ -7,10 +8,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 +21,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..d56240eb75e 100644
--- a/tests/lib/BackgroundJob/TimedJobTest.php
+++ b/tests/lib/BackgroundJob/TimedJobTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2018-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -8,6 +9,7 @@
namespace Test\BackgroundJob;
use OCP\AppFramework\Utility\ITimeFactory;
+use OCP\Server;
class TimedJobTest extends \Test\TestCase {
private DummyJobList $jobList;
@@ -17,7 +19,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..b9731c7cdde 100644
--- a/tests/lib/Cache/CappedMemoryCacheTest.php
+++ b/tests/lib/Cache/CappedMemoryCacheTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -7,6 +8,8 @@
namespace Test\Cache;
+use OCP\Cache\CappedMemoryCache;
+
/**
* Class CappedMemoryCacheTest
*
@@ -15,11 +18,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 1d12147af0d..4daa8d3b7ef 100644
--- a/tests/lib/Cache/FileCacheTest.php
+++ b/tests/lib/Cache/FileCacheTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -7,8 +8,17 @@
namespace Test\Cache;
+use OC\Cache\File;
+use OC\Files\Filesystem;
use OC\Files\Storage\Local;
+use OC\Files\Storage\Storage;
+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;
/**
@@ -30,11 +40,11 @@ class FileCacheTest extends TestCache {
* */
private $datadir;
/**
- * @var \OC\Files\Storage\Storage
+ * @var Storage
* */
private $storage;
/**
- * @var \OC\Files\View
+ * @var View
* */
private $rootView;
@@ -55,17 +65,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');
@@ -88,11 +98,11 @@ class FileCacheTest extends TestCache {
private function setupMockStorage() {
$mockStorage = $this->getMockBuilder(Local::class)
- ->setMethods(['filemtime', 'unlink'])
- ->setConstructorArgs([['datadir' => \OC::$server->getTempManager()->getTemporaryFolder()]])
+ ->onlyMethods(['filemtime', 'unlink'])
+ ->setConstructorArgs([['datadir' => Server::get(ITempManager::class)->getTemporaryFolder()]])
->getMock();
- \OC\Files\Filesystem::mount($mockStorage, [], '/test/cache');
+ Filesystem::mount($mockStorage, [], '/test/cache');
return $mockStorage;
}
@@ -125,16 +135,14 @@ class FileCacheTest extends TestCache {
$this->instance->gc();
}
- public function lockExceptionProvider() {
+ public static function lockExceptionProvider(): array {
return [
- [new \OCP\Lock\LockedException('key1')],
- [new \OCP\Files\LockNotAcquiredException('key1', 1)],
+ [new LockedException('key1')],
+ [new LockNotAcquiredException('key1', 1)],
];
}
- /**
- * @dataProvider lockExceptionProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('lockExceptionProvider')]
public function testGarbageCollectIgnoreLockedKeys($testException): void {
$mockStorage = $this->setupMockStorage();
@@ -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/Cache/TestCache.php b/tests/lib/Cache/TestCache.php
index 3245cd90a38..ec150152816 100644
--- a/tests/lib/Cache/TestCache.php
+++ b/tests/lib/Cache/TestCache.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2017-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -7,9 +8,11 @@
namespace Test\Cache;
+use OCP\ICache;
+
abstract class TestCache extends \Test\TestCase {
/**
- * @var \OCP\ICache cache;
+ * @var ICache cache;
*/
protected $instance;
@@ -24,7 +27,7 @@ abstract class TestCache extends \Test\TestCase {
public function testSimple(): void {
$this->assertNull($this->instance->get('value1'));
$this->assertFalse($this->instance->hasKey('value1'));
-
+
$value = 'foobar';
$this->instance->set('value1', $value);
$this->assertTrue($this->instance->hasKey('value1'));
diff --git a/tests/lib/Calendar/ManagerTest.php b/tests/lib/Calendar/ManagerTest.php
index 6c01cd90811..fec2cfa0efe 100644
--- a/tests/lib/Calendar/ManagerTest.php
+++ b/tests/lib/Calendar/ManagerTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2017 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
@@ -11,6 +12,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;
@@ -27,8 +29,6 @@ use Psr\Log\LoggerInterface;
use Sabre\HTTP\RequestInterface;
use Sabre\HTTP\ResponseInterface;
use Sabre\VObject\Component\VCalendar;
-use Sabre\VObject\Document;
-use Sabre\VObject\Reader;
use Test\TestCase;
/*
@@ -60,6 +60,8 @@ class ManagerTest extends TestCase {
private ServerFactory&MockObject $serverFactory;
private VCalendar $vCalendar1a;
+ private VCalendar $vCalendar2a;
+ private VCalendar $vCalendar3a;
protected function setUp(): void {
parent::setUp();
@@ -90,6 +92,9 @@ class ManagerTest extends TestCase {
$vEvent->add('DTSTART', '20240701T080000', ['TZID' => 'America/Toronto']);
$vEvent->add('DTEND', '20240701T090000', ['TZID' => 'America/Toronto']);
$vEvent->add('SUMMARY', 'Test Event');
+ $vEvent->add('SEQUENCE', 3);
+ $vEvent->add('STATUS', 'CONFIRMED');
+ $vEvent->add('TRANSP', 'OPAQUE');
$vEvent->add('ORGANIZER', 'mailto:organizer@testing.com', ['CN' => 'Organizer']);
$vEvent->add('ATTENDEE', 'mailto:attendee1@testing.com', [
'CN' => 'Attendee One',
@@ -98,11 +103,48 @@ class ManagerTest extends TestCase {
'ROLE' => 'REQ-PARTICIPANT',
'RSVP' => 'TRUE'
]);
+
+ // construct calendar with a event for reply
+ $this->vCalendar2a = new VCalendar();
+ /** @var VEvent $vEvent */
+ $vEvent = $this->vCalendar2a->add('VEVENT', []);
+ $vEvent->UID->setValue('dcc733bf-b2b2-41f2-a8cf-550ae4b67aff');
+ $vEvent->add('DTSTART', '20210820');
+ $vEvent->add('DTEND', '20220821');
+ $vEvent->add('SUMMARY', 'berry basket');
+ $vEvent->add('SEQUENCE', 3);
+ $vEvent->add('STATUS', 'CONFIRMED');
+ $vEvent->add('TRANSP', 'OPAQUE');
+ $vEvent->add('ORGANIZER', 'mailto:linus@stardew-tent-living.com', ['CN' => 'admin']);
+ $vEvent->add('ATTENDEE', 'mailto:pierre@general-store.com', [
+ 'CN' => 'pierre@general-store.com',
+ 'CUTYPE' => 'INDIVIDUAL',
+ 'ROLE' => 'REQ-PARTICIPANT',
+ 'PARTSTAT' => 'ACCEPTED',
+ ]);
+
+ // construct calendar with a event for reply
+ $this->vCalendar3a = new VCalendar();
+ /** @var VEvent $vEvent */
+ $vEvent = $this->vCalendar3a->add('VEVENT', []);
+ $vEvent->UID->setValue('dcc733bf-b2b2-41f2-a8cf-550ae4b67aff');
+ $vEvent->add('DTSTART', '20210820');
+ $vEvent->add('DTEND', '20220821');
+ $vEvent->add('SUMMARY', 'berry basket');
+ $vEvent->add('SEQUENCE', 3);
+ $vEvent->add('STATUS', 'CANCELLED');
+ $vEvent->add('TRANSP', 'OPAQUE');
+ $vEvent->add('ORGANIZER', 'mailto:linus@stardew-tent-living.com', ['CN' => 'admin']);
+ $vEvent->add('ATTENDEE', 'mailto:pierre@general-store.com', [
+ 'CN' => 'pierre@general-store.com',
+ 'CUTYPE' => 'INDIVIDUAL',
+ 'ROLE' => 'REQ-PARTICIPANT',
+ 'PARTSTAT' => 'ACCEPTED',
+ ]);
+
}
- /**
- * @dataProvider searchProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('searchProvider')]
public function testSearch($search1, $search2, $expected): void {
/** @var ICalendar | MockObject $calendar1 */
$calendar1 = $this->createMock(ICalendar::class);
@@ -127,9 +169,7 @@ class ManagerTest extends TestCase {
$this->assertEquals($expected, $result);
}
- /**
- * @dataProvider searchProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('searchProvider')]
public function testSearchOptions($search1, $search2, $expected): void {
/** @var ICalendar | MockObject $calendar1 */
$calendar1 = $this->createMock(ICalendar::class);
@@ -157,7 +197,7 @@ class ManagerTest extends TestCase {
$this->assertEquals($expected, $result);
}
- public function searchProvider() {
+ public static function searchProvider(): array {
$search1 = [
[
'id' => 1,
@@ -300,8 +340,42 @@ class ManagerTest extends TestCase {
$recipient = 'attendee1@testing.com';
$calendar = $this->vCalendar1a;
$calendar->add('METHOD', 'REQUEST');
- // test method
+ // Act
$result = $manager->handleIMipRequest($principalUri, $sender, $recipient, $calendar->serialize());
+ // Assert
+ $this->assertFalse($result);
+ }
+
+ public function testHandleImipRequestWithInvalidData(): void {
+ // construct mock user calendar
+ $userCalendar = $this->createMock(ITestCalendar::class);
+ // construct mock calendar manager and returns
+ /** @var Manager&MockObject $manager */
+ $manager = $this->getMockBuilder(Manager::class)
+ ->setConstructorArgs([
+ $this->coordinator,
+ $this->container,
+ $this->logger,
+ $this->time,
+ $this->secureRandom,
+ $this->userManager,
+ $this->serverFactory,
+ ])
+ ->onlyMethods(['getCalendarsForPrincipal'])
+ ->getMock();
+ $manager->expects(self::once())
+ ->method('getCalendarsForPrincipal')
+ ->willReturn([$userCalendar]);
+ // construct logger returns
+ $this->logger->expects(self::once())->method('error')
+ ->with('iMip message could not be processed because an error occurred while parsing the iMip message');
+ // construct parameters
+ $principalUri = 'principals/user/attendee1';
+ $sender = 'organizer@testing.com';
+ $recipient = 'attendee1@testing.com';
+ // Act
+ $result = $manager->handleIMipRequest($principalUri, $sender, $recipient, 'Invalid data');
+ // Assert
$this->assertFalse($result);
}
@@ -333,8 +407,9 @@ class ManagerTest extends TestCase {
$sender = 'organizer@testing.com';
$recipient = 'attendee1@testing.com';
$calendar = $this->vCalendar1a;
- // test method
+ // Act
$result = $manager->handleIMipRequest($principalUri, $sender, $recipient, $calendar->serialize());
+ // Assert
$this->assertFalse($result);
}
@@ -367,8 +442,9 @@ class ManagerTest extends TestCase {
$recipient = 'attendee1@testing.com';
$calendar = $this->vCalendar1a;
$calendar->add('METHOD', 'CANCEL');
- // test method
+ // Act
$result = $manager->handleIMipRequest($principalUri, $sender, $recipient, $calendar->serialize());
+ // Assert
$this->assertFalse($result);
}
@@ -402,8 +478,9 @@ class ManagerTest extends TestCase {
$calendar = $this->vCalendar1a;
$calendar->add('METHOD', 'REQUEST');
$calendar->remove('VEVENT');
- // test method
+ // Act
$result = $manager->handleIMipRequest($principalUri, $sender, $recipient, $calendar->serialize());
+ // Assert
$this->assertFalse($result);
}
@@ -437,8 +514,45 @@ class ManagerTest extends TestCase {
$calendar = $this->vCalendar1a;
$calendar->add('METHOD', 'REQUEST');
$calendar->VEVENT->remove('UID');
- // test method
+ // Act
+ $result = $manager->handleIMipRequest($principalUri, $sender, $recipient, $calendar->serialize());
+ // Assert
+ $this->assertFalse($result);
+ }
+
+ public function testHandleImipRequestWithNoOrganizer(): void {
+ // construct mock user calendar
+ $userCalendar = $this->createMock(ITestCalendar::class);
+ // construct mock calendar manager and returns
+ /** @var Manager&MockObject $manager */
+ $manager = $this->getMockBuilder(Manager::class)
+ ->setConstructorArgs([
+ $this->coordinator,
+ $this->container,
+ $this->logger,
+ $this->time,
+ $this->secureRandom,
+ $this->userManager,
+ $this->serverFactory,
+ ])
+ ->onlyMethods(['getCalendarsForPrincipal'])
+ ->getMock();
+ $manager->expects(self::once())
+ ->method('getCalendarsForPrincipal')
+ ->willReturn([$userCalendar]);
+ // construct logger returns
+ $this->logger->expects(self::once())->method('warning')
+ ->with('iMip message event dose not contains an organizer');
+ // construct parameters
+ $principalUri = 'principals/user/attendee1';
+ $sender = 'organizer@testing.com';
+ $recipient = 'attendee1@testing.com';
+ $calendar = $this->vCalendar1a;
+ $calendar->add('METHOD', 'REQUEST');
+ $calendar->VEVENT->remove('ORGANIZER');
+ // Act
$result = $manager->handleIMipRequest($principalUri, $sender, $recipient, $calendar->serialize());
+ // Assert
$this->assertFalse($result);
}
@@ -472,8 +586,9 @@ class ManagerTest extends TestCase {
$calendar = $this->vCalendar1a;
$calendar->add('METHOD', 'REQUEST');
$calendar->VEVENT->remove('ATTENDEE');
- // test method
+ // Act
$result = $manager->handleIMipRequest($principalUri, $sender, $recipient, $calendar->serialize());
+ // Assert
$this->assertFalse($result);
}
@@ -506,8 +621,9 @@ class ManagerTest extends TestCase {
$recipient = 'attendee2@testing.com';
$calendar = $this->vCalendar1a;
$calendar->add('METHOD', 'REQUEST');
- // test method
+ // Act
$result = $manager->handleIMipRequest($principalUri, $sender, $recipient, $calendar->serialize());
+ // Assert
$this->assertFalse($result);
}
@@ -545,15 +661,16 @@ class ManagerTest extends TestCase {
->willReturn([$userCalendar]);
// construct logger returns
$this->logger->expects(self::once())->method('warning')
- ->with('iMip message event could not be processed because the no corresponding event was found in any calendar');
+ ->with('iMip message event could not be processed because no corresponding event was found in any calendar');
// construct parameters
$principalUri = 'principals/user/attendee1';
$sender = 'organizer@testing.com';
$recipient = 'attendee1@testing.com';
$calendar = $this->vCalendar1a;
$calendar->add('METHOD', 'REQUEST');
- // test method
+ // Act
$result = $manager->handleIMipRequest($principalUri, $sender, $recipient, $calendar->serialize());
+ // Assert
$this->assertFalse($result);
}
@@ -599,62 +716,152 @@ class ManagerTest extends TestCase {
$userCalendar->expects(self::once())
->method('handleIMipMessage')
->with('', $calendar->serialize());
- // test method
+ // Act
$result = $manager->handleIMipRequest($principalUri, $sender, $recipient, $calendar->serialize());
+ // Assert
$this->assertTrue($result);
}
- public function testHandleImipReplyWrongMethod(): void {
+ public function testHandleImipReplyWithNoCalendars(): void {
+ // construct calendar manager returns
+ /** @var Manager&MockObject $manager */
+ $manager = $this->getMockBuilder(Manager::class)
+ ->setConstructorArgs([
+ $this->coordinator,
+ $this->container,
+ $this->logger,
+ $this->time,
+ $this->secureRandom,
+ $this->userManager,
+ $this->serverFactory,
+ ])
+ ->onlyMethods(['getCalendarsForPrincipal'])
+ ->getMock();
+ $manager->expects(self::once())
+ ->method('getCalendarsForPrincipal')
+ ->willReturn([]);
+ // construct logger returns
+ $this->logger->expects(self::once())->method('warning')
+ ->with('iMip message could not be processed because user has no calendars');
+ // construct parameters
$principalUri = 'principals/user/linus';
$sender = 'pierre@general-store.com';
$recipient = 'linus@stardew-tent-living.com';
- $calendarData = $this->getVCalendarReply();
- $calendarData->METHOD = 'REQUEST';
-
- $this->logger->expects(self::once())
- ->method('warning');
- $this->time->expects(self::never())
- ->method('getTime');
+ $calendar = $this->vCalendar2a;
+ $calendar->add('METHOD', 'REPLY');
+ // Act
+ $result = $manager->handleIMipReply($principalUri, $sender, $recipient, $calendar->serialize());
+ // Assert
+ $this->assertFalse($result);
+ }
- $result = $this->manager->handleIMipReply($principalUri, $sender, $recipient, $calendarData->serialize());
+ public function testHandleImipReplyWithInvalidData(): void {
+ // construct mock user calendar
+ $userCalendar = $this->createMock(ITestCalendar::class);
+ // construct mock calendar manager and returns
+ /** @var Manager&MockObject $manager */
+ $manager = $this->getMockBuilder(Manager::class)
+ ->setConstructorArgs([
+ $this->coordinator,
+ $this->container,
+ $this->logger,
+ $this->time,
+ $this->secureRandom,
+ $this->userManager,
+ $this->serverFactory,
+ ])
+ ->onlyMethods(['getCalendarsForPrincipal'])
+ ->getMock();
+ $manager->expects(self::once())
+ ->method('getCalendarsForPrincipal')
+ ->willReturn([$userCalendar]);
+ // construct logger returns
+ $this->logger->expects(self::once())->method('error')
+ ->with('iMip message could not be processed because an error occurred while parsing the iMip message');
+ // construct parameters
+ $principalUri = 'principals/user/attendee1';
+ $sender = 'organizer@testing.com';
+ $recipient = 'attendee1@testing.com';
+ // Act
+ $result = $manager->handleIMipReply($principalUri, $sender, $recipient, 'Invalid data');
+ // Assert
$this->assertFalse($result);
}
- public function testHandleImipReplyOrganizerNotRecipient(): void {
+ public function testHandleImipReplyWithNoMethod(): void {
+ // construct mock user calendar
+ $userCalendar = $this->createMock(ITestCalendar::class);
+ // construct mock calendar manager and returns
+ /** @var Manager&MockObject $manager */
+ $manager = $this->getMockBuilder(Manager::class)
+ ->setConstructorArgs([
+ $this->coordinator,
+ $this->container,
+ $this->logger,
+ $this->time,
+ $this->secureRandom,
+ $this->userManager,
+ $this->serverFactory,
+ ])
+ ->onlyMethods(['getCalendarsForPrincipal'])
+ ->getMock();
+ $manager->expects(self::once())
+ ->method('getCalendarsForPrincipal')
+ ->willReturn([$userCalendar]);
+ // construct logger returns
+ $this->logger->expects(self::once())->method('warning')
+ ->with('iMip message contains an incorrect or invalid method');
+ // construct parameters
$principalUri = 'principals/user/linus';
- $recipient = 'pierre@general-store.com';
- $sender = 'linus@stardew-tent-living.com';
- $calendarData = $this->getVCalendarReply();
-
- $this->logger->expects(self::once())
- ->method('warning');
- $this->time->expects(self::never())
- ->method('getTime');
-
- $result = $this->manager->handleIMipReply($principalUri, $sender, $recipient, $calendarData->serialize());
+ $sender = 'pierre@general-store.com';
+ $recipient = 'linus@stardew-tent-living.com';
+ $calendar = $this->vCalendar2a;
+ // Act
+ $result = $manager->handleIMipReply($principalUri, $sender, $recipient, $calendar->serialize());
+ // Assert
$this->assertFalse($result);
}
- public function testHandleImipReplyDateInThePast(): void {
+ public function testHandleImipReplyWithInvalidMethod(): void {
+ // construct mock user calendar
+ $userCalendar = $this->createMock(ITestCalendar::class);
+ // construct mock calendar manager and returns
+ /** @var Manager&MockObject $manager */
+ $manager = $this->getMockBuilder(Manager::class)
+ ->setConstructorArgs([
+ $this->coordinator,
+ $this->container,
+ $this->logger,
+ $this->time,
+ $this->secureRandom,
+ $this->userManager,
+ $this->serverFactory,
+ ])
+ ->onlyMethods(['getCalendarsForPrincipal'])
+ ->getMock();
+ $manager->expects(self::once())
+ ->method('getCalendarsForPrincipal')
+ ->willReturn([$userCalendar]);
+ // construct logger returns
+ $this->logger->expects(self::once())->method('warning')
+ ->with('iMip message contains an incorrect or invalid method');
+ // construct parameters
$principalUri = 'principals/user/linus';
$sender = 'pierre@general-store.com';
$recipient = 'linus@stardew-tent-living.com';
- $calendarData = $this->getVCalendarReply();
- $calendarData->VEVENT->DTSTART = new \DateTime('2013-04-07'); // set to in the past
-
- $this->time->expects(self::once())
- ->method('getTime')
- ->willReturn(time());
-
- $this->logger->expects(self::once())
- ->method('warning');
-
- $result = $this->manager->handleIMipReply($principalUri, $sender, $recipient, $calendarData->serialize());
+ $calendar = $this->vCalendar2a;
+ $calendar->add('METHOD', 'UNKNOWN');
+ // Act
+ $result = $manager->handleIMipReply($principalUri, $sender, $recipient, $calendar->serialize());
+ // Assert
$this->assertFalse($result);
}
- public function testHandleImipReplyNoCalendars(): void {
- /** @var Manager | \PHPUnit\Framework\MockObject\MockObject $manager */
+ public function testHandleImipReplyWithNoEvent(): void {
+ // construct mock user calendar
+ $userCalendar = $this->createMock(ITestCalendar::class);
+ // construct mock calendar manager and returns
+ /** @var Manager&MockObject $manager */
$manager = $this->getMockBuilder(Manager::class)
->setConstructorArgs([
$this->coordinator,
@@ -665,30 +872,68 @@ class ManagerTest extends TestCase {
$this->userManager,
$this->serverFactory,
])
- ->setMethods([
- 'getCalendarsForPrincipal'
- ])
+ ->onlyMethods(['getCalendarsForPrincipal'])
->getMock();
+ $manager->expects(self::once())
+ ->method('getCalendarsForPrincipal')
+ ->willReturn([$userCalendar]);
+ // construct logger returns
+ $this->logger->expects(self::once())->method('warning')
+ ->with('iMip message contains no event');
+ // construct parameters
$principalUri = 'principals/user/linus';
$sender = 'pierre@general-store.com';
$recipient = 'linus@stardew-tent-living.com';
- $calendarData = $this->getVCalendarReply();
+ $calendar = $this->vCalendar2a;
+ $calendar->add('METHOD', 'REPLY');
+ $calendar->remove('VEVENT');
+ // Act
+ $result = $manager->handleIMipReply($principalUri, $sender, $recipient, $calendar->serialize());
+ // Assert
+ $this->assertFalse($result);
+ }
- $this->time->expects(self::once())
- ->method('getTime')
- ->willReturn(1628374233);
+ public function testHandleImipReplyWithNoUid(): void {
+ // construct mock user calendar
+ $userCalendar = $this->createMock(ITestCalendar::class);
+ // construct mock calendar manager and returns
+ /** @var Manager&MockObject $manager */
+ $manager = $this->getMockBuilder(Manager::class)
+ ->setConstructorArgs([
+ $this->coordinator,
+ $this->container,
+ $this->logger,
+ $this->time,
+ $this->secureRandom,
+ $this->userManager,
+ $this->serverFactory,
+ ])
+ ->onlyMethods(['getCalendarsForPrincipal'])
+ ->getMock();
$manager->expects(self::once())
->method('getCalendarsForPrincipal')
- ->willReturn([]);
- $this->logger->expects(self::once())
- ->method('warning');
-
- $result = $manager->handleIMipReply($principalUri, $sender, $recipient, $calendarData->serialize());
+ ->willReturn([$userCalendar]);
+ // construct logger returns
+ $this->logger->expects(self::once())->method('warning')
+ ->with('iMip message event dose not contains a UID');
+ // construct parameters
+ $principalUri = 'principals/user/linus';
+ $sender = 'pierre@general-store.com';
+ $recipient = 'linus@stardew-tent-living.com';
+ $calendar = $this->vCalendar2a;
+ $calendar->add('METHOD', 'REPLY');
+ $calendar->VEVENT->remove('UID');
+ // Act
+ $result = $manager->handleIMipReply($principalUri, $sender, $recipient, $calendar->serialize());
+ // Assert
$this->assertFalse($result);
}
- public function testHandleImipReplyEventNotFound(): void {
- /** @var Manager | \PHPUnit\Framework\MockObject\MockObject $manager */
+ public function testHandleImipReplyWithNoOrganizer(): void {
+ // construct mock user calendar
+ $userCalendar = $this->createMock(ITestCalendar::class);
+ // construct mock calendar manager and returns
+ /** @var Manager&MockObject $manager */
$manager = $this->getMockBuilder(Manager::class)
->setConstructorArgs([
$this->coordinator,
@@ -699,31 +944,141 @@ class ManagerTest extends TestCase {
$this->userManager,
$this->serverFactory,
])
- ->setMethods([
- 'getCalendarsForPrincipal'
+ ->onlyMethods(['getCalendarsForPrincipal'])
+ ->getMock();
+ $manager->expects(self::once())
+ ->method('getCalendarsForPrincipal')
+ ->willReturn([$userCalendar]);
+ // construct logger returns
+ $this->logger->expects(self::once())->method('warning')
+ ->with('iMip message event dose not contains an organizer');
+ // construct parameters
+ $principalUri = 'principals/user/linus';
+ $sender = 'pierre@general-store.com';
+ $recipient = 'linus@stardew-tent-living.com';
+ $calendar = $this->vCalendar2a;
+ $calendar->add('METHOD', 'REPLY');
+ $calendar->VEVENT->remove('ORGANIZER');
+ // Act
+ $result = $manager->handleIMipReply($principalUri, $sender, $recipient, $calendar->serialize());
+ // Assert
+ $this->assertFalse($result);
+ }
+
+ public function testHandleImipReplyWithNoAttendee(): void {
+ // construct mock user calendar
+ $userCalendar = $this->createMock(ITestCalendar::class);
+ // construct mock calendar manager and returns
+ /** @var Manager&MockObject $manager */
+ $manager = $this->getMockBuilder(Manager::class)
+ ->setConstructorArgs([
+ $this->coordinator,
+ $this->container,
+ $this->logger,
+ $this->time,
+ $this->secureRandom,
+ $this->userManager,
+ $this->serverFactory,
])
+ ->onlyMethods(['getCalendarsForPrincipal'])
->getMock();
- $calendar = $this->createMock(ITestCalendar::class);
+ $manager->expects(self::once())
+ ->method('getCalendarsForPrincipal')
+ ->willReturn([$userCalendar]);
+ // construct logger returns
+ $this->logger->expects(self::once())->method('warning')
+ ->with('iMip message event dose not contains any attendees');
+ // construct parameters
$principalUri = 'principals/user/linus';
$sender = 'pierre@general-store.com';
$recipient = 'linus@stardew-tent-living.com';
- $calendarData = $this->getVCalendarReply();
+ $calendar = $this->vCalendar2a;
+ $calendar->add('METHOD', 'REPLY');
+ $calendar->VEVENT->remove('ATTENDEE');
+ // Act
+ $result = $manager->handleIMipReply($principalUri, $sender, $recipient, $calendar->serialize());
+ // Assert
+ $this->assertFalse($result);
+ }
- $this->time->expects(self::once())
- ->method('getTime')
- ->willReturn(1628374233);
+ public function testHandleImipReplyDateInThePast(): void {
+ // construct mock user calendar
+ $userCalendar = $this->createMock(ITestCalendar::class);
+ // construct mock calendar manager and returns
+ /** @var Manager&MockObject $manager */
+ $manager = $this->getMockBuilder(Manager::class)
+ ->setConstructorArgs([
+ $this->coordinator,
+ $this->container,
+ $this->logger,
+ $this->time,
+ $this->secureRandom,
+ $this->userManager,
+ $this->serverFactory,
+ ])
+ ->onlyMethods(['getCalendarsForPrincipal'])
+ ->getMock();
$manager->expects(self::once())
->method('getCalendarsForPrincipal')
- ->willReturn([$calendar]);
- $calendar->expects(self::once())
+ ->willReturn([$userCalendar]);
+ // construct logger and time returns
+ $this->logger->expects(self::once())->method('warning')
+ ->with('iMip message event could not be processed because the event is in the past');
+ $this->time->expects(self::once())
+ ->method('getTime')
+ ->willReturn(time());
+ // construct parameters
+ $principalUri = 'principals/user/linus';
+ $sender = 'pierre@general-store.com';
+ $recipient = 'linus@stardew-tent-living.com';
+ $calendarData = clone $this->vCalendar2a;
+ $calendarData->add('METHOD', 'REPLY');
+ $calendarData->VEVENT->DTSTART = new \DateTime('2013-04-07'); // set to in the past
+ // Act
+ $result = $manager->handleIMipReply($principalUri, $sender, $recipient, $calendarData->serialize());
+ // Assert
+ $this->assertFalse($result);
+ }
+
+ public function testHandleImipReplyEventNotFound(): void {
+ // construct mock user calendar
+ $userCalendar = $this->createMock(ITestCalendar::class);
+ $userCalendar->expects(self::once())
->method('search')
->willReturn([]);
- $this->logger->expects(self::once())
- ->method('info');
- $calendar->expects(self::never())
- ->method('handleIMipMessage');
-
+ // construct mock calendar manager and returns
+ /** @var Manager&MockObject $manager */
+ $manager = $this->getMockBuilder(Manager::class)
+ ->setConstructorArgs([
+ $this->coordinator,
+ $this->container,
+ $this->logger,
+ $this->time,
+ $this->secureRandom,
+ $this->userManager,
+ $this->serverFactory,
+ ])
+ ->onlyMethods(['getCalendarsForPrincipal'])
+ ->getMock();
+ $manager->expects(self::once())
+ ->method('getCalendarsForPrincipal')
+ ->willReturn([$userCalendar]);
+ // construct time returns
+ $this->time->expects(self::once())
+ ->method('getTime')
+ ->willReturn(1628374233);
+ // construct parameters
+ $principalUri = 'principals/user/linus';
+ $sender = 'pierre@general-store.com';
+ $recipient = 'linus@stardew-tent-living.com';
+ $calendarData = clone $this->vCalendar2a;
+ $calendarData->add('METHOD', 'REPLY');
+ // construct logger return
+ $this->logger->expects(self::once())->method('warning')
+ ->with('iMip message event could not be processed because no corresponding event was found in any calendar ' . $principalUri . 'and UID' . $calendarData->VEVENT->UID->getValue());
+ // Act
$result = $manager->handleIMipReply($principalUri, $sender, $recipient, $calendarData->serialize());
+ // Assert
$this->assertFalse($result);
}
@@ -739,7 +1094,7 @@ class ManagerTest extends TestCase {
$this->userManager,
$this->serverFactory,
])
- ->setMethods([
+ ->onlyMethods([
'getCalendarsForPrincipal'
])
->getMock();
@@ -747,7 +1102,8 @@ class ManagerTest extends TestCase {
$principalUri = 'principals/user/linus';
$sender = 'pierre@general-store.com';
$recipient = 'linus@stardew-tent-living.com';
- $calendarData = $this->getVCalendarReply();
+ $calendarData = clone $this->vCalendar2a;
+ $calendarData->add('METHOD', 'REPLY');
$this->time->expects(self::once())
->method('getTime')
@@ -761,64 +1117,305 @@ class ManagerTest extends TestCase {
$calendar->expects(self::once())
->method('handleIMipMessage')
->with('testname.ics', $calendarData->serialize());
-
+ // Act
$result = $manager->handleIMipReply($principalUri, $sender, $recipient, $calendarData->serialize());
+ // Assert
$this->assertTrue($result);
}
- public function testHandleImipCancelWrongMethod(): void {
+ public function testHandleImipCancelWithNoCalendars(): void {
+ // construct calendar manager returns
+ /** @var Manager&MockObject $manager */
+ $manager = $this->getMockBuilder(Manager::class)
+ ->setConstructorArgs([
+ $this->coordinator,
+ $this->container,
+ $this->logger,
+ $this->time,
+ $this->secureRandom,
+ $this->userManager,
+ $this->serverFactory,
+ ])
+ ->onlyMethods(['getCalendarsForPrincipal'])
+ ->getMock();
+ $manager->expects(self::once())
+ ->method('getCalendarsForPrincipal')
+ ->willReturn([]);
+ // construct logger returns
+ $this->logger->expects(self::once())->method('warning')
+ ->with('iMip message could not be processed because user has no calendars');
+ // construct parameters
$principalUri = 'principals/user/pierre';
$sender = 'linus@stardew-tent-living.com';
$recipient = 'pierre@general-store.com';
$replyTo = null;
- $calendarData = $this->getVCalendarCancel();
- $calendarData->METHOD = 'REQUEST';
-
- $this->logger->expects(self::once())
- ->method('warning');
- $this->time->expects(self::never())
- ->method('getTime');
+ $calendar = $this->vCalendar3a;
+ $calendar->add('METHOD', 'CANCEL');
+ // Act
+ $result = $manager->handleIMipCancel($principalUri, $sender, $replyTo, $recipient, $calendar->serialize());
+ // Assert
+ $this->assertFalse($result);
+ }
- $result = $this->manager->handleIMipCancel($principalUri, $sender, $replyTo, $recipient, $calendarData->serialize());
+ public function testHandleImipCancelWithInvalidData(): void {
+ // construct mock user calendar
+ $userCalendar = $this->createMock(ITestCalendar::class);
+ // construct mock calendar manager and returns
+ /** @var Manager&MockObject $manager */
+ $manager = $this->getMockBuilder(Manager::class)
+ ->setConstructorArgs([
+ $this->coordinator,
+ $this->container,
+ $this->logger,
+ $this->time,
+ $this->secureRandom,
+ $this->userManager,
+ $this->serverFactory,
+ ])
+ ->onlyMethods(['getCalendarsForPrincipal'])
+ ->getMock();
+ $manager->expects(self::once())
+ ->method('getCalendarsForPrincipal')
+ ->willReturn([$userCalendar]);
+ // construct logger returns
+ $this->logger->expects(self::once())->method('error')
+ ->with('iMip message could not be processed because an error occurred while parsing the iMip message');
+ // construct parameters
+ $principalUri = 'principals/user/attendee1';
+ $sender = 'organizer@testing.com';
+ $recipient = 'attendee1@testing.com';
+ $replyTo = null;
+ // Act
+ $result = $manager->handleIMipCancel($principalUri, $sender, $replyTo, $recipient, 'Invalid data');
+ // Assert
$this->assertFalse($result);
}
- public function testHandleImipCancelAttendeeNotRecipient(): void {
- $principalUri = '/user/admin';
+
+ public function testHandleImipCancelWithNoMethod(): void {
+ // construct mock user calendar
+ $userCalendar = $this->createMock(ITestCalendar::class);
+ // construct mock calendar manager and returns
+ /** @var Manager&MockObject $manager */
+ $manager = $this->getMockBuilder(Manager::class)
+ ->setConstructorArgs([
+ $this->coordinator,
+ $this->container,
+ $this->logger,
+ $this->time,
+ $this->secureRandom,
+ $this->userManager,
+ $this->serverFactory,
+ ])
+ ->onlyMethods(['getCalendarsForPrincipal'])
+ ->getMock();
+ $manager->expects(self::once())
+ ->method('getCalendarsForPrincipal')
+ ->willReturn([$userCalendar]);
+ // construct logger returns
+ $this->logger->expects(self::once())->method('warning')
+ ->with('iMip message contains an incorrect or invalid method');
+ // construct parameters
+ $principalUri = 'principals/user/pierre';
$sender = 'linus@stardew-tent-living.com';
- $recipient = 'leah@general-store.com';
+ $recipient = 'pierre@general-store.com';
$replyTo = null;
- $calendarData = $this->getVCalendarCancel();
+ $calendar = $this->vCalendar3a;
+ // Act
+ $result = $manager->handleIMipCancel($principalUri, $sender, $replyTo, $recipient, $calendar->serialize());
+ // Assert
+ $this->assertFalse($result);
+ }
- $this->logger->expects(self::once())
- ->method('warning');
- $this->time->expects(self::never())
- ->method('getTime');
+ public function testHandleImipCancelWithInvalidMethod(): void {
+ // construct mock user calendar
+ $userCalendar = $this->createMock(ITestCalendar::class);
+ // construct mock calendar manager and returns
+ /** @var Manager&MockObject $manager */
+ $manager = $this->getMockBuilder(Manager::class)
+ ->setConstructorArgs([
+ $this->coordinator,
+ $this->container,
+ $this->logger,
+ $this->time,
+ $this->secureRandom,
+ $this->userManager,
+ $this->serverFactory,
+ ])
+ ->onlyMethods(['getCalendarsForPrincipal'])
+ ->getMock();
+ $manager->expects(self::once())
+ ->method('getCalendarsForPrincipal')
+ ->willReturn([$userCalendar]);
+ // construct logger returns
+ $this->logger->expects(self::once())->method('warning')
+ ->with('iMip message contains an incorrect or invalid method');
+ // construct parameters
+ $principalUri = 'principals/user/pierre';
+ $sender = 'linus@stardew-tent-living.com';
+ $recipient = 'pierre@general-store.com';
+ $replyTo = null;
+ $calendar = $this->vCalendar3a;
+ $calendar->add('METHOD', 'UNKNOWN');
+ // Act
+ $result = $manager->handleIMipCancel($principalUri, $sender, $replyTo, $recipient, $calendar->serialize());
+ // Assert
+ $this->assertFalse($result);
+ }
- $result = $this->manager->handleIMipCancel($principalUri, $sender, $replyTo, $recipient, $calendarData->serialize());
+ public function testHandleImipCancelWithNoEvent(): void {
+ // construct mock user calendar
+ $userCalendar = $this->createMock(ITestCalendar::class);
+ // construct mock calendar manager and returns
+ /** @var Manager&MockObject $manager */
+ $manager = $this->getMockBuilder(Manager::class)
+ ->setConstructorArgs([
+ $this->coordinator,
+ $this->container,
+ $this->logger,
+ $this->time,
+ $this->secureRandom,
+ $this->userManager,
+ $this->serverFactory,
+ ])
+ ->onlyMethods(['getCalendarsForPrincipal'])
+ ->getMock();
+ $manager->expects(self::once())
+ ->method('getCalendarsForPrincipal')
+ ->willReturn([$userCalendar]);
+ // construct logger returns
+ $this->logger->expects(self::once())->method('warning')
+ ->with('iMip message contains no event');
+ // construct parameters
+ $principalUri = 'principals/user/pierre';
+ $sender = 'linus@stardew-tent-living.com';
+ $recipient = 'pierre@general-store.com';
+ $replyTo = null;
+ $calendar = $this->vCalendar3a;
+ $calendar->add('METHOD', 'CANCEL');
+ $calendar->remove('VEVENT');
+ // Act
+ $result = $manager->handleIMipCancel($principalUri, $sender, $replyTo, $recipient, $calendar->serialize());
+ // Assert
$this->assertFalse($result);
}
- public function testHandleImipCancelDateInThePast(): void {
+ public function testHandleImipCancelWithNoUid(): void {
+ // construct mock user calendar
+ $userCalendar = $this->createMock(ITestCalendar::class);
+ // construct mock calendar manager and returns
+ /** @var Manager&MockObject $manager */
+ $manager = $this->getMockBuilder(Manager::class)
+ ->setConstructorArgs([
+ $this->coordinator,
+ $this->container,
+ $this->logger,
+ $this->time,
+ $this->secureRandom,
+ $this->userManager,
+ $this->serverFactory,
+ ])
+ ->onlyMethods(['getCalendarsForPrincipal'])
+ ->getMock();
+ $manager->expects(self::once())
+ ->method('getCalendarsForPrincipal')
+ ->willReturn([$userCalendar]);
+ // construct logger returns
+ $this->logger->expects(self::once())->method('warning')
+ ->with('iMip message event dose not contains a UID');
+ // construct parameters
$principalUri = 'principals/user/pierre';
$sender = 'linus@stardew-tent-living.com';
$recipient = 'pierre@general-store.com';
$replyTo = null;
- $calendarData = $this->getVCalendarCancel();
- $calendarData->VEVENT->DTSTART = new \DateTime('2013-04-07'); // set to in the past
+ $calendar = $this->vCalendar3a;
+ $calendar->add('METHOD', 'CANCEL');
+ $calendar->VEVENT->remove('UID');
+ // Act
+ $result = $manager->handleIMipCancel($principalUri, $sender, $replyTo, $recipient, $calendar->serialize());
+ // Assert
+ $this->assertFalse($result);
+ }
- $this->time->expects(self::once())
- ->method('getTime')
- ->willReturn(time());
- $this->logger->expects(self::once())
- ->method('warning');
+ public function testHandleImipCancelWithNoOrganizer(): void {
+ // construct mock user calendar
+ $userCalendar = $this->createMock(ITestCalendar::class);
+ // construct mock calendar manager and returns
+ /** @var Manager&MockObject $manager */
+ $manager = $this->getMockBuilder(Manager::class)
+ ->setConstructorArgs([
+ $this->coordinator,
+ $this->container,
+ $this->logger,
+ $this->time,
+ $this->secureRandom,
+ $this->userManager,
+ $this->serverFactory,
+ ])
+ ->onlyMethods(['getCalendarsForPrincipal'])
+ ->getMock();
+ $manager->expects(self::once())
+ ->method('getCalendarsForPrincipal')
+ ->willReturn([$userCalendar]);
+ // construct logger returns
+ $this->logger->expects(self::once())->method('warning')
+ ->with('iMip message event dose not contains an organizer');
+ // construct parameters
+ $principalUri = 'principals/user/pierre';
+ $sender = 'linus@stardew-tent-living.com';
+ $recipient = 'pierre@general-store.com';
+ $replyTo = null;
+ $calendar = $this->vCalendar3a;
+ $calendar->add('METHOD', 'CANCEL');
+ $calendar->VEVENT->remove('ORGANIZER');
+ // Act
+ $result = $manager->handleIMipCancel($principalUri, $sender, $replyTo, $recipient, $calendar->serialize());
+ // Assert
+ $this->assertFalse($result);
+ }
- $result = $this->manager->handleIMipCancel($principalUri, $sender, $replyTo, $recipient, $calendarData->serialize());
+ public function testHandleImipCancelWithNoAttendee(): void {
+ // construct mock user calendar
+ $userCalendar = $this->createMock(ITestCalendar::class);
+ // construct mock calendar manager and returns
+ /** @var Manager&MockObject $manager */
+ $manager = $this->getMockBuilder(Manager::class)
+ ->setConstructorArgs([
+ $this->coordinator,
+ $this->container,
+ $this->logger,
+ $this->time,
+ $this->secureRandom,
+ $this->userManager,
+ $this->serverFactory,
+ ])
+ ->onlyMethods(['getCalendarsForPrincipal'])
+ ->getMock();
+ $manager->expects(self::once())
+ ->method('getCalendarsForPrincipal')
+ ->willReturn([$userCalendar]);
+ // construct logger returns
+ $this->logger->expects(self::once())->method('warning')
+ ->with('iMip message event dose not contains any attendees');
+ // construct parameters
+ $principalUri = 'principals/user/pierre';
+ $sender = 'pierre@general-store.com';
+ $recipient = 'linus@stardew-tent-living.com';
+ $replyTo = null;
+ $calendar = $this->vCalendar3a;
+ $calendar->add('METHOD', 'CANCEL');
+ $calendar->VEVENT->remove('ATTENDEE');
+ // Act
+ $result = $manager->handleIMipCancel($principalUri, $sender, $replyTo, $recipient, $calendar->serialize());
+ // Assert
$this->assertFalse($result);
}
- public function testHandleImipCancelNoCalendars(): void {
- /** @var Manager | \PHPUnit\Framework\MockObject\MockObject $manager */
+ public function testHandleImipCancelAttendeeNotRecipient(): void {
+ // construct mock user calendar
+ $userCalendar = $this->createMock(ITestCalendar::class);
+ // construct mock calendar manager and returns
+ /** @var Manager&MockObject $manager */
$manager = $this->getMockBuilder(Manager::class)
->setConstructorArgs([
$this->coordinator,
@@ -829,27 +1426,107 @@ class ManagerTest extends TestCase {
$this->userManager,
$this->serverFactory,
])
- ->setMethods([
- 'getCalendarsForPrincipal'
+ ->onlyMethods(['getCalendarsForPrincipal'])
+ ->getMock();
+ $manager->expects(self::once())
+ ->method('getCalendarsForPrincipal')
+ ->willReturn([$userCalendar]);
+ // construct logger returns
+ $this->logger->expects(self::once())->method('warning')
+ ->with('iMip message event could not be processed because recipient must be an ATTENDEE of this event');
+ // construct parameters
+ $principalUri = 'principals/user/pierre';
+ $sender = 'linus@stardew-tent-living.com';
+ $recipient = 'leah@general-store.com';
+ $replyTo = null;
+ $calendarData = clone $this->vCalendar3a;
+ $calendarData->add('METHOD', 'CANCEL');
+ // Act
+ $result = $manager->handleIMipCancel($principalUri, $sender, $replyTo, $recipient, $calendarData->serialize());
+ // Assert
+ $this->assertFalse($result);
+ }
+
+ public function testHandleImipCancelDateInThePast(): void {
+ // construct mock user calendar
+ $userCalendar = $this->createMock(ITestCalendar::class);
+ // construct mock calendar manager and returns
+ /** @var Manager&MockObject $manager */
+ $manager = $this->getMockBuilder(Manager::class)
+ ->setConstructorArgs([
+ $this->coordinator,
+ $this->container,
+ $this->logger,
+ $this->time,
+ $this->secureRandom,
+ $this->userManager,
+ $this->serverFactory,
])
+ ->onlyMethods(['getCalendarsForPrincipal'])
->getMock();
+ $manager->expects(self::once())
+ ->method('getCalendarsForPrincipal')
+ ->willReturn([$userCalendar]);
+ // construct logger and time returns
+ $this->logger->expects(self::once())->method('warning')
+ ->with('iMip message event could not be processed because the event is in the past');
+ $this->time->expects(self::once())
+ ->method('getTime')
+ ->willReturn(time());
+ // construct parameters
$principalUri = 'principals/user/pierre';
$sender = 'linus@stardew-tent-living.com';
$recipient = 'pierre@general-store.com';
$replyTo = null;
- $calendarData = $this->getVCalendarCancel();
+ $calendarData = clone $this->vCalendar3a;
+ $calendarData->add('METHOD', 'CANCEL');
+ $calendarData->VEVENT->DTSTART = new \DateTime('2013-04-07'); // set to in the past
+ // Act
+ $result = $manager->handleIMipCancel($principalUri, $sender, $replyTo, $recipient, $calendarData->serialize());
+ // Assert
+ $this->assertFalse($result);
+ }
+ public function testHandleImipCancelEventNotFound(): void {
+ // construct mock user calendar
+ $userCalendar = $this->createMock(ITestCalendar::class);
+ $userCalendar->expects(self::once())
+ ->method('search')
+ ->willReturn([]);
+ // construct mock calendar manager and returns
+ /** @var Manager&MockObject $manager */
+ $manager = $this->getMockBuilder(Manager::class)
+ ->setConstructorArgs([
+ $this->coordinator,
+ $this->container,
+ $this->logger,
+ $this->time,
+ $this->secureRandom,
+ $this->userManager,
+ $this->serverFactory,
+ ])
+ ->onlyMethods(['getCalendarsForPrincipal'])
+ ->getMock();
+ $manager->expects(self::once())
+ ->method('getCalendarsForPrincipal')
+ ->willReturn([$userCalendar]);
+ // construct time returns
$this->time->expects(self::once())
->method('getTime')
->willReturn(1628374233);
- $manager->expects(self::once())
- ->method('getCalendarsForPrincipal')
- ->with($principalUri)
- ->willReturn([]);
- $this->logger->expects(self::once())
- ->method('warning');
-
+ // construct parameters
+ $principalUri = 'principals/user/pierre';
+ $sender = 'linus@stardew-tent-living.com';
+ $recipient = 'pierre@general-store.com';
+ $replyTo = null;
+ $calendarData = clone $this->vCalendar3a;
+ $calendarData->add('METHOD', 'CANCEL');
+ // construct logger return
+ $this->logger->expects(self::once())->method('warning')
+ ->with('iMip message event could not be processed because no corresponding event was found in any calendar ' . $principalUri . 'and UID' . $calendarData->VEVENT->UID->getValue());
+ // Act
$result = $manager->handleIMipCancel($principalUri, $sender, $replyTo, $recipient, $calendarData->serialize());
+ // Assert
$this->assertFalse($result);
}
@@ -865,16 +1542,18 @@ class ManagerTest extends TestCase {
$this->userManager,
$this->serverFactory,
])
- ->setMethods([
+ ->onlyMethods([
'getCalendarsForPrincipal'
])
->getMock();
+
$principalUri = 'principals/user/pierre';
- $sender = 'clint@stardew-blacksmiths.com';
+ $sender = 'clint@stardew-tent-living.com';
$recipient = 'pierre@general-store.com';
$replyTo = 'linus@stardew-tent-living.com';
$calendar = $this->createMock(ITestCalendar::class);
- $calendarData = $this->getVCalendarCancel();
+ $calendarData = clone $this->vCalendar3a;
+ $calendarData->add('METHOD', 'CANCEL');
$this->time->expects(self::once())
->method('getTime')
@@ -889,7 +1568,9 @@ class ManagerTest extends TestCase {
$calendar->expects(self::once())
->method('handleIMipMessage')
->with('testname.ics', $calendarData->serialize());
+ // Act
$result = $manager->handleIMipCancel($principalUri, $sender, $replyTo, $recipient, $calendarData->serialize());
+ // Assert
$this->assertTrue($result);
}
@@ -905,7 +1586,7 @@ class ManagerTest extends TestCase {
$this->userManager,
$this->serverFactory,
])
- ->setMethods([
+ ->onlyMethods([
'getCalendarsForPrincipal'
])
->getMock();
@@ -914,7 +1595,8 @@ class ManagerTest extends TestCase {
$recipient = 'pierre@general-store.com';
$replyTo = null;
$calendar = $this->createMock(ITestCalendar::class);
- $calendarData = $this->getVCalendarCancel();
+ $calendarData = clone $this->vCalendar3a;
+ $calendarData->add('METHOD', 'CANCEL');
$this->time->expects(self::once())
->method('getTime')
@@ -929,68 +1611,12 @@ class ManagerTest extends TestCase {
$calendar->expects(self::once())
->method('handleIMipMessage')
->with('testname.ics', $calendarData->serialize());
+ // Act
$result = $manager->handleIMipCancel($principalUri, $sender, $replyTo, $recipient, $calendarData->serialize());
+ // Assert
$this->assertTrue($result);
}
- private function getVCalendarReply(): Document {
- $data = <<<EOF
-BEGIN:VCALENDAR
-PRODID:-//Nextcloud/Nextcloud CalDAV Server//EN
-VERSION:2.0
-CALSCALE:GREGORIAN
-METHOD:REPLY
-BEGIN:VEVENT
-DTSTART;VALUE=DATE:20210820
-DTEND;VALUE=DATE:20220821
-DTSTAMP:20210812T100040Z
-ORGANIZER;CN=admin:mailto:linus@stardew-tent-living.com
-UID:dcc733bf-b2b2-41f2-a8cf-550ae4b67aff
-ATTENDEE;CUTYPE=INDIVIDUAL;ROLE=REQ-PARTICIPANT;PARTSTAT=ACCEPTED;CN=pierr
- e@general-store.com;X-NUM-GUESTS=0:mailto:pierre@general-store.com
-CREATED:20220812T100021Z
-DESCRIPTION:
-LAST-MODIFIED:20220812T100040Z
-LOCATION:
-SEQUENCE:3
-STATUS:CONFIRMED
-SUMMARY:berry basket
-TRANSP:OPAQUE
-END:VEVENT
-END:VCALENDAR
-EOF;
- return Reader::read($data);
- }
-
- private function getVCalendarCancel(): Document {
- $data = <<<EOF
-BEGIN:VCALENDAR
-PRODID:-//Nextcloud/Nextcloud CalDAV Server//EN
-VERSION:2.0
-CALSCALE:GREGORIAN
-METHOD:CANCEL
-BEGIN:VEVENT
-DTSTART;VALUE=DATE:20210820
-DTEND;VALUE=DATE:20220821
-DTSTAMP:20210812T100040Z
-ORGANIZER;CN=admin:mailto:linus@stardew-tent-living.com
-UID:dcc733bf-b2b2-41f2-a8cf-550ae4b67aff
-ATTENDEE;CUTYPE=INDIVIDUAL;ROLE=REQ-PARTICIPANT;PARTSTAT=ACCEPTED;CN=pierr
- e@general-store.com;X-NUM-GUESTS=0:mailto:pierre@general-store.com
-CREATED:20220812T100021Z
-DESCRIPTION:
-LAST-MODIFIED:20220812T100040Z
-LOCATION:
-SEQUENCE:3
-STATUS:CANCELLED
-SUMMARY:berry basket
-TRANSP:OPAQUE
-END:VEVENT
-END:VCALENDAR
-EOF;
- return Reader::read($data);
- }
-
private function getFreeBusyResponse(): string {
return <<<EOF
<?xml version="1.0" encoding="utf-8"?>
@@ -1097,7 +1723,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')
@@ -1108,7 +1734,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());
@@ -1164,7 +1790,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')
@@ -1175,7 +1801,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..e5bf7b03dee 100644
--- a/tests/lib/CapabilitiesManagerTest.php
+++ b/tests/lib/CapabilitiesManagerTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -129,7 +130,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/GroupPluginTest.php b/tests/lib/Collaboration/Collaborators/GroupPluginTest.php
index 8fe71234906..a4ecd598562 100644
--- a/tests/lib/Collaboration/Collaborators/GroupPluginTest.php
+++ b/tests/lib/Collaboration/Collaborators/GroupPluginTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2017 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
@@ -417,7 +418,6 @@ class GroupPluginTest extends TestCase {
}
/**
- * @dataProvider dataGetGroups
*
* @param string $searchTerm
* @param bool $shareWithGroupOnly
@@ -430,6 +430,7 @@ class GroupPluginTest extends TestCase {
* @param bool $reachedEnd
* @param bool|IGroup $singleGroup
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataGetGroups')]
public function testSearch(
string $searchTerm,
bool $shareWithGroupOnly,
diff --git a/tests/lib/Collaboration/Collaborators/LookupPluginTest.php b/tests/lib/Collaboration/Collaborators/LookupPluginTest.php
index d74dfca3be9..ac9b196ea1e 100644
--- a/tests/lib/Collaboration/Collaborators/LookupPluginTest.php
+++ b/tests/lib/Collaboration/Collaborators/LookupPluginTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2017 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
@@ -117,9 +118,9 @@ class LookupPluginTest extends TestCase {
}
/**
- * @dataProvider searchDataProvider
* @param array $searchParams
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('searchDataProvider')]
public function testSearch(array $searchParams): void {
$type = new SearchResultType('lookup');
@@ -175,11 +176,11 @@ class LookupPluginTest extends TestCase {
/**
- * @dataProvider dataSearchEnableDisableLookupServer
* @param array $searchParams
* @param bool $GSEnabled
* @param bool $LookupEnabled
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataSearchEnableDisableLookupServer')]
public function testSearchEnableDisableLookupServer(array $searchParams, $GSEnabled, $LookupEnabled): void {
$type = new SearchResultType('lookup');
diff --git a/tests/lib/Collaboration/Collaborators/MailPluginTest.php b/tests/lib/Collaboration/Collaborators/MailPluginTest.php
index 02b1034240f..502b7844a2a 100644
--- a/tests/lib/Collaboration/Collaborators/MailPluginTest.php
+++ b/tests/lib/Collaboration/Collaborators/MailPluginTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2017 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
@@ -86,7 +87,6 @@ class MailPluginTest extends TestCase {
}
/**
- * @dataProvider dataGetEmail
*
* @param string $searchTerm
* @param array $contacts
@@ -94,6 +94,7 @@ class MailPluginTest extends TestCase {
* @param array $expected
* @param bool $reachedEnd
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataGetEmail')]
public function testSearch($searchTerm, $contacts, $shareeEnumeration, $expected, $exactIdMatch, $reachedEnd, $validEmail): void {
$this->config->expects($this->any())
->method('getAppValue')
@@ -134,7 +135,7 @@ class MailPluginTest extends TestCase {
$this->assertSame($reachedEnd, $moreResults);
}
- public function dataGetEmail() {
+ public static function dataGetEmail(): array {
return [
// data set 0
['test', [], true, ['emails' => [], 'exact' => ['emails' => []]], false, false, false],
@@ -568,7 +569,6 @@ class MailPluginTest extends TestCase {
}
/**
- * @dataProvider dataGetEmailGroupsOnly
*
* @param string $searchTerm
* @param array $contacts
@@ -577,6 +577,7 @@ class MailPluginTest extends TestCase {
* @param bool $reachedEnd
* @param array groups
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataGetEmailGroupsOnly')]
public function testSearchGroupsOnly($searchTerm, $contacts, $expected, $exactIdMatch, $reachedEnd, $userToGroupMapping, $validEmail): void {
$this->config->expects($this->any())
->method('getAppValue')
@@ -593,7 +594,7 @@ class MailPluginTest extends TestCase {
$this->instantiatePlugin();
- /** @var \OCP\IUser | \PHPUnit\Framework\MockObject\MockObject */
+ /** @var IUser|\PHPUnit\Framework\MockObject\MockObject */
$currentUser = $this->createMock('\OCP\IUser');
$currentUser->expects($this->any())
@@ -618,7 +619,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()];
});
@@ -636,7 +637,7 @@ class MailPluginTest extends TestCase {
$this->assertSame($reachedEnd, $moreResults);
}
- public function dataGetEmailGroupsOnly() {
+ public static function dataGetEmailGroupsOnly(): array {
return [
// The user `User` can share with the current user
[
diff --git a/tests/lib/Collaboration/Collaborators/RemotePluginTest.php b/tests/lib/Collaboration/Collaborators/RemotePluginTest.php
index 14894aa2df6..ea81b1cbcdc 100644
--- a/tests/lib/Collaboration/Collaborators/RemotePluginTest.php
+++ b/tests/lib/Collaboration/Collaborators/RemotePluginTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2017 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
@@ -70,7 +71,6 @@ class RemotePluginTest extends TestCase {
}
/**
- * @dataProvider dataGetRemote
*
* @param string $searchTerm
* @param array $contacts
@@ -79,6 +79,7 @@ class RemotePluginTest extends TestCase {
* @param bool $exactIdMatch
* @param bool $reachedEnd
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataGetRemote')]
public function testSearch($searchTerm, array $contacts, $shareeEnumeration, array $expected, $exactIdMatch, $reachedEnd): void {
$this->config->expects($this->any())
->method('getAppValue')
@@ -111,12 +112,12 @@ class RemotePluginTest extends TestCase {
}
/**
- * @dataProvider dataTestSplitUserRemote
*
* @param string $remote
* @param string $expectedUser
* @param string $expectedUrl
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataTestSplitUserRemote')]
public function testSplitUserRemote($remote, $expectedUser, $expectedUrl): void {
$this->instantiatePlugin();
@@ -130,10 +131,9 @@ class RemotePluginTest extends TestCase {
}
/**
- * @dataProvider dataTestSplitUserRemoteError
- *
* @param string $id
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataTestSplitUserRemoteError')]
public function testSplitUserRemoteError($id): void {
$this->expectException(\Exception::class);
@@ -141,7 +141,7 @@ class RemotePluginTest extends TestCase {
$this->plugin->splitUserRemote($id);
}
- public function dataGetRemote() {
+ public static function dataGetRemote() {
return [
['test', [], true, ['remotes' => [], 'exact' => ['remotes' => []]], false, true],
['test', [], false, ['remotes' => [], 'exact' => ['remotes' => []]], false, true],
@@ -374,7 +374,7 @@ class RemotePluginTest extends TestCase {
];
}
- public function dataTestSplitUserRemote() {
+ public static function dataTestSplitUserRemote(): array {
$userPrefix = ['user@name', 'username'];
$protocols = ['', 'http://', 'https://'];
$remotes = [
@@ -410,7 +410,7 @@ class RemotePluginTest extends TestCase {
return $testCases;
}
- public function dataTestSplitUserRemoteError() {
+ public static function dataTestSplitUserRemoteError(): array {
return [
// Invalid path
['user@'],
diff --git a/tests/lib/Collaboration/Collaborators/SearchResultTest.php b/tests/lib/Collaboration/Collaborators/SearchResultTest.php
index 6641a2caed1..687901c47a6 100644
--- a/tests/lib/Collaboration/Collaborators/SearchResultTest.php
+++ b/tests/lib/Collaboration/Collaborators/SearchResultTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2017 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
@@ -27,7 +28,7 @@ class SearchResultTest extends TestCase {
$this->search = new Search($this->container);
}
- public function dataAddResultSet() {
+ public static function dataAddResultSet(): array {
return [
[[], ['exact' => []]],
[['users' => ['exact' => null, 'loose' => []]], ['exact' => ['users' => []], 'users' => []]],
@@ -37,10 +38,10 @@ class SearchResultTest extends TestCase {
}
/**
- * @dataProvider dataAddResultSet
* @param array $toAdd
* @param array $expected
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataAddResultSet')]
public function testAddResultSet(array $toAdd, array $expected): void {
$result = new SearchResult();
@@ -51,7 +52,7 @@ class SearchResultTest extends TestCase {
$this->assertEquals($expected, $result->asArray());
}
- public function dataHasResult() {
+ public static function dataHasResult(): array {
$result = ['value' => ['shareWith' => 'l1']];
return [
[[],'users', 'n1', false],
@@ -66,12 +67,12 @@ class SearchResultTest extends TestCase {
}
/**
- * @dataProvider dataHasResult
* @param array $toAdd
* @param string $type
* @param string $id
* @param bool $expected
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataHasResult')]
public function testHasResult(array $toAdd, $type, $id, $expected): void {
$result = new SearchResult();
diff --git a/tests/lib/Collaboration/Collaborators/SearchTest.php b/tests/lib/Collaboration/Collaborators/SearchTest.php
index 3e43d6331b2..ade995ea526 100644
--- a/tests/lib/Collaboration/Collaborators/SearchTest.php
+++ b/tests/lib/Collaboration/Collaborators/SearchTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2017 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
@@ -29,9 +30,7 @@ class SearchTest extends TestCase {
$this->search = new Search($this->container);
}
- /**
- * @dataProvider dataSearchSharees
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataSearchSharees')]
public function testSearch(
string $searchTerm,
array $shareTypes,
@@ -115,7 +114,7 @@ class SearchTest extends TestCase {
$this->assertSame($expectedMoreResults, $moreResults);
}
- public function dataSearchSharees() {
+ public static function dataSearchSharees(): array {
return [
// #0
[
diff --git a/tests/lib/Collaboration/Collaborators/UserPluginTest.php b/tests/lib/Collaboration/Collaborators/UserPluginTest.php
index 453f16c6686..cb4949fb86d 100644
--- a/tests/lib/Collaboration/Collaborators/UserPluginTest.php
+++ b/tests/lib/Collaboration/Collaborators/UserPluginTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2017 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
@@ -124,7 +125,7 @@ class UserPluginTest extends TestCase {
return $group;
}
- public function dataGetUsers() {
+ public function dataGetUsers(): array {
return [
['test', false, true, [], [], [], [], true, false],
['test', false, false, [], [], [], [], true, false],
@@ -417,7 +418,6 @@ class UserPluginTest extends TestCase {
}
/**
- * @dataProvider dataGetUsers
*
* @param string $searchTerm
* @param bool $shareWithGroupOnly
@@ -430,6 +430,7 @@ class UserPluginTest extends TestCase {
* @param bool|IUser $singleUser
* @param array $users
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataGetUsers')]
public function testSearch(
$searchTerm,
$shareWithGroupOnly,
@@ -508,7 +509,7 @@ class UserPluginTest extends TestCase {
$this->assertSame($reachedEnd, $moreResults);
}
- public function takeOutCurrentUserProvider() {
+ public static function takeOutCurrentUserProvider(): array {
$inputUsers = [
'alice' => 'Alice',
'bob' => 'Bob',
@@ -534,11 +535,11 @@ class UserPluginTest extends TestCase {
}
/**
- * @dataProvider takeOutCurrentUserProvider
* @param array $users
* @param array $expectedUIDs
* @param $currentUserId
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('takeOutCurrentUserProvider')]
public function testTakeOutCurrentUser(array $users, array $expectedUIDs, $currentUserId): void {
$this->instantiatePlugin();
@@ -555,7 +556,7 @@ class UserPluginTest extends TestCase {
$this->assertSame($expectedUIDs, array_keys($users));
}
- public function dataSearchEnumeration() {
+ public static function dataSearchEnumeration(): array {
return [
[
'test',
@@ -716,9 +717,7 @@ class UserPluginTest extends TestCase {
];
}
- /**
- * @dataProvider dataSearchEnumeration
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataSearchEnumeration')]
public function testSearchEnumerationLimit($search, $userGroups, $matchingUsers, $result, $mockedSettings): void {
$this->mockConfig($mockedSettings);
diff --git a/tests/lib/Command/AsyncBusTest.php b/tests/lib/Command/AsyncBusTestCase.php
index e8d7a857129..bb47de30b11 100644
--- a/tests/lib/Command/AsyncBusTest.php
+++ b/tests/lib/Command/AsyncBusTestCase.php
@@ -15,19 +15,18 @@ use Test\TestCase;
class SimpleCommand implements ICommand {
public function handle() {
- AsyncBusTest::$lastCommand = 'SimpleCommand';
+ AsyncBusTestCase::$lastCommand = 'SimpleCommand';
}
}
class StateFullCommand implements ICommand {
- private $state;
-
- public function __construct($state) {
- $this->state = $state;
+ public function __construct(
+ private $state,
+ ) {
}
public function handle() {
- AsyncBusTest::$lastCommand = $this->state;
+ AsyncBusTestCase::$lastCommand = $this->state;
}
}
@@ -35,28 +34,28 @@ class FilesystemCommand implements ICommand {
use FileAccess;
public function handle() {
- AsyncBusTest::$lastCommand = 'FileAccess';
+ AsyncBusTestCase::$lastCommand = 'FileAccess';
}
}
function basicFunction() {
- AsyncBusTest::$lastCommand = 'function';
+ AsyncBusTestCase::$lastCommand = 'function';
}
// clean class to prevent phpunit putting closure in $this
class ThisClosureTest {
private function privateMethod() {
- AsyncBusTest::$lastCommand = 'closure-this';
+ AsyncBusTestCase::$lastCommand = 'closure-this';
}
public function test(IBus $bus) {
- $bus->push(function () {
+ $bus->push(function (): void {
$this->privateMethod();
});
}
}
-abstract class AsyncBusTest extends TestCase {
+abstract class AsyncBusTestCase extends TestCase {
/**
* Basic way to check output from a command
*
@@ -65,7 +64,7 @@ abstract class AsyncBusTest extends TestCase {
public static $lastCommand;
/**
- * @var \OCP\Command\IBus
+ * @var IBus
*/
private $bus;
@@ -107,7 +106,7 @@ abstract class AsyncBusTest extends TestCase {
}
public function testStaticCallable(): void {
- $this->getBus()->push(['\Test\Command\AsyncBusTest', 'DummyCommand']);
+ $this->getBus()->push(['\Test\Command\AsyncBusTestCase', 'DummyCommand']);
$this->runJobs();
$this->assertEquals('static', self::$lastCommand);
}
@@ -126,16 +125,16 @@ abstract class AsyncBusTest extends TestCase {
}
public function testClosure(): void {
- $this->getBus()->push(function () {
- AsyncBusTest::$lastCommand = 'closure';
+ $this->getBus()->push(function (): void {
+ AsyncBusTestCase::$lastCommand = 'closure';
});
$this->runJobs();
$this->assertEquals('closure', self::$lastCommand);
}
public function testClosureSelf(): void {
- $this->getBus()->push(function () {
- AsyncBusTest::$lastCommand = 'closure-self';
+ $this->getBus()->push(function (): void {
+ AsyncBusTestCase::$lastCommand = 'closure-self';
});
$this->runJobs();
$this->assertEquals('closure-self', self::$lastCommand);
@@ -152,8 +151,8 @@ abstract class AsyncBusTest extends TestCase {
public function testClosureBind(): void {
$state = 'bar';
- $this->getBus()->push(function () use ($state) {
- AsyncBusTest::$lastCommand = 'closure-' . $state;
+ $this->getBus()->push(function () use ($state): void {
+ AsyncBusTestCase::$lastCommand = 'closure-' . $state;
});
$this->runJobs();
$this->assertEquals('closure-bar', self::$lastCommand);
diff --git a/tests/lib/Command/BackgroundModeTest.php b/tests/lib/Command/BackgroundModeTest.php
index 941449c98bb..ab036ef87ee 100644
--- a/tests/lib/Command/BackgroundModeTest.php
+++ b/tests/lib/Command/BackgroundModeTest.php
@@ -16,6 +16,9 @@ use Symfony\Component\Console\Input\InputDefinition;
use Symfony\Component\Console\Tester\CommandTester;
use Test\TestCase;
+/**
+ * @group DB
+ */
class BackgroundModeTest extends TestCase {
private IAppConfig $appConfig;
@@ -32,9 +35,7 @@ class BackgroundModeTest extends TestCase {
$this->command->setDefinition($inputDefinition);
}
- /**
- * @dataProvider dataModeCommand
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataModeCommand')]
public function testModeCommand(string $mode): void {
$this->appConfig->expects($this->once())
->method('setValueString')
@@ -49,7 +50,7 @@ class BackgroundModeTest extends TestCase {
$this->assertStringContainsString($mode, $output);
}
- public function dataModeCommand(): array {
+ public static function dataModeCommand(): array {
return [
'ajax' => ['ajax'],
'cron' => ['cron'],
diff --git a/tests/lib/Command/CronBusTest.php b/tests/lib/Command/CronBusTest.php
index 96190f717c6..c86cdcb1da0 100644
--- a/tests/lib/Command/CronBusTest.php
+++ b/tests/lib/Command/CronBusTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2017 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
@@ -7,11 +8,15 @@
namespace Test\Command;
use OC\Command\CronBus;
+use OCP\BackgroundJob\IJobList;
use Test\BackgroundJob\DummyJobList;
-class CronBusTest extends AsyncBusTest {
+/**
+ * @group DB
+ */
+class CronBusTest extends AsyncBusTestCase {
/**
- * @var \OCP\BackgroundJob\IJobList
+ * @var IJobList
*/
private $jobList;
diff --git a/tests/lib/Command/Integrity/SignAppTest.php b/tests/lib/Command/Integrity/SignAppTest.php
index d4921c79431..237afe3a5b5 100644
--- a/tests/lib/Command/Integrity/SignAppTest.php
+++ b/tests/lib/Command/Integrity/SignAppTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -44,22 +45,28 @@ class SignAppTest extends TestCase {
$inputInterface
->expects($this->exactly(3))
->method('getOption')
- ->withConsecutive(
- ['path'],
- ['privateKey'],
- ['certificate'],
- )->willReturnOnConsecutiveCalls(
- null,
- 'PrivateKey',
- 'Certificate',
- );
-
+ ->willReturnMap([
+ ['path', null],
+ ['privateKey', 'PrivateKey'],
+ ['certificate', 'Certificate'],
+ ]);
+
+ $calls = [
+ 'This command requires the --path, --privateKey and --certificate.',
+ '*',
+ '*',
+ ];
$outputInterface
->expects($this->any())
->method('writeln')
- ->withConsecutive(
- ['This command requires the --path, --privateKey and --certificate.']
- );
+ ->willReturnCallback(function (string $message) use (&$calls): void {
+ $expected = array_shift($calls);
+ if ($expected === '*') {
+ $this->assertNotEmpty($message);
+ } else {
+ $this->assertEquals($expected, $message);
+ }
+ });
$this->assertSame(1, self::invokePrivate($this->signApp, 'execute', [$inputInterface, $outputInterface]));
}
@@ -71,22 +78,28 @@ class SignAppTest extends TestCase {
$inputInterface
->expects($this->exactly(3))
->method('getOption')
- ->withConsecutive(
- ['path'],
- ['privateKey'],
- ['certificate'],
- )->willReturnOnConsecutiveCalls(
- 'AppId',
- null,
- 'Certificate',
- );
-
+ ->willReturnMap([
+ ['path', 'AppId'],
+ ['privateKey', null],
+ ['certificate', 'Certificate'],
+ ]);
+
+ $calls = [
+ 'This command requires the --path, --privateKey and --certificate.',
+ '*',
+ '*',
+ ];
$outputInterface
->expects($this->any())
->method('writeln')
- ->withConsecutive(
- ['This command requires the --path, --privateKey and --certificate.']
- );
+ ->willReturnCallback(function (string $message) use (&$calls): void {
+ $expected = array_shift($calls);
+ if ($expected === '*') {
+ $this->assertNotEmpty($message);
+ } else {
+ $this->assertEquals($expected, $message);
+ }
+ });
$this->assertSame(1, self::invokePrivate($this->signApp, 'execute', [$inputInterface, $outputInterface]));
}
@@ -98,22 +111,28 @@ class SignAppTest extends TestCase {
$inputInterface
->expects($this->exactly(3))
->method('getOption')
- ->withConsecutive(
- ['path'],
- ['privateKey'],
- ['certificate'],
- )->willReturnOnConsecutiveCalls(
- 'AppId',
- 'privateKey',
- null,
- );
-
+ ->willReturnMap([
+ ['path', 'AppId'],
+ ['privateKey', 'PrivateKey'],
+ ['certificate', null],
+ ]);
+
+ $calls = [
+ 'This command requires the --path, --privateKey and --certificate.',
+ '*',
+ '*',
+ ];
$outputInterface
->expects($this->any())
->method('writeln')
- ->withConsecutive(
- ['This command requires the --path, --privateKey and --certificate.']
- );
+ ->willReturnCallback(function (string $message) use (&$calls): void {
+ $expected = array_shift($calls);
+ if ($expected === '*') {
+ $this->assertNotEmpty($message);
+ } else {
+ $this->assertEquals($expected, $message);
+ }
+ });
$this->assertSame(1, self::invokePrivate($this->signApp, 'execute', [$inputInterface, $outputInterface]));
}
@@ -125,29 +144,26 @@ class SignAppTest extends TestCase {
$inputInterface
->expects($this->exactly(3))
->method('getOption')
- ->withConsecutive(
- ['path'],
- ['privateKey'],
- ['certificate'],
- )->willReturnOnConsecutiveCalls(
- 'AppId',
- 'privateKey',
- 'certificate',
- );
+ ->willReturnMap([
+ ['path', 'AppId'],
+ ['privateKey', 'privateKey'],
+ ['certificate', 'certificate'],
+ ]);
$this->fileAccessHelper
->expects($this->any())
->method('file_get_contents')
- ->withConsecutive(['privateKey'])
- ->willReturnOnConsecutiveCalls(false);
+ ->willReturnMap([
+ ['privateKey', false],
+ ]);
$outputInterface
->expects($this->any())
->method('writeln')
- ->withConsecutive(
- ['Private key "privateKey" does not exists.']
- );
+ ->willReturnCallback(function (string $message): void {
+ $this->assertEquals('Private key "privateKey" does not exists.', $message);
+ });
$this->assertSame(1, self::invokePrivate($this->signApp, 'execute', [$inputInterface, $outputInterface]));
}
@@ -159,34 +175,26 @@ class SignAppTest extends TestCase {
$inputInterface
->expects($this->exactly(3))
->method('getOption')
- ->withConsecutive(
- ['path'],
- ['privateKey'],
- ['certificate'],
- )->willReturnOnConsecutiveCalls(
- 'AppId',
- 'privateKey',
- 'certificate',
- );
+ ->willReturnMap([
+ ['path', 'AppId'],
+ ['privateKey', 'privateKey'],
+ ['certificate', 'certificate'],
+ ]);
$this->fileAccessHelper
->expects($this->any())
->method('file_get_contents')
- ->withConsecutive(
- ['privateKey'],
- ['certificate'],
- )
- ->willReturnOnConsecutiveCalls(
- \OC::$SERVERROOT . '/tests/data/integritycheck/core.key',
- false
- );
+ ->willReturnMap([
+ ['privateKey', file_get_contents(\OC::$SERVERROOT . '/tests/data/integritycheck/core.key')],
+ ['certificate', false],
+ ]);
$outputInterface
->expects($this->any())
->method('writeln')
- ->withConsecutive(
- ['Certificate "certificate" does not exists.']
- );
+ ->willReturnCallback(function (string $message): void {
+ $this->assertEquals('Certificate "certificate" does not exists.', $message);
+ });
$this->assertSame(1, self::invokePrivate($this->signApp, 'execute', [$inputInterface, $outputInterface]));
}
@@ -198,27 +206,19 @@ class SignAppTest extends TestCase {
$inputInterface
->expects($this->exactly(3))
->method('getOption')
- ->withConsecutive(
- ['path'],
- ['privateKey'],
- ['certificate'],
- )->willReturnOnConsecutiveCalls(
- 'AppId',
- 'privateKey',
- 'certificate',
- );
+ ->willReturnMap([
+ ['path', 'AppId'],
+ ['privateKey', 'privateKey'],
+ ['certificate', 'certificate'],
+ ]);
$this->fileAccessHelper
->expects($this->any())
->method('file_get_contents')
- ->withConsecutive(
- ['privateKey'],
- ['certificate'],
- )
- ->willReturnOnConsecutiveCalls(
- file_get_contents(\OC::$SERVERROOT . '/tests/data/integritycheck/core.key'),
- file_get_contents(\OC::$SERVERROOT . '/tests/data/integritycheck/core.crt'),
- );
+ ->willReturnMap([
+ ['privateKey', file_get_contents(\OC::$SERVERROOT . '/tests/data/integritycheck/core.key')],
+ ['certificate', \OC::$SERVERROOT . '/tests/data/integritycheck/core.crt'],
+ ]);
$this->checker
->expects($this->once())
@@ -228,9 +228,9 @@ class SignAppTest extends TestCase {
$outputInterface
->expects($this->any())
->method('writeln')
- ->withConsecutive(
- ['Error: My error message']
- );
+ ->willReturnCallback(function (string $message): void {
+ $this->assertEquals('Error: My error message', $message);
+ });
$this->assertSame(1, self::invokePrivate($this->signApp, 'execute', [$inputInterface, $outputInterface]));
}
@@ -242,27 +242,19 @@ class SignAppTest extends TestCase {
$inputInterface
->expects($this->exactly(3))
->method('getOption')
- ->withConsecutive(
- ['path'],
- ['privateKey'],
- ['certificate'],
- )->willReturnOnConsecutiveCalls(
- 'AppId',
- 'privateKey',
- 'certificate',
- );
+ ->willReturnMap([
+ ['path', 'AppId'],
+ ['privateKey', 'privateKey'],
+ ['certificate', 'certificate'],
+ ]);
$this->fileAccessHelper
->expects($this->any())
->method('file_get_contents')
- ->withConsecutive(
- ['privateKey'],
- ['certificate'],
- )
- ->willReturnOnConsecutiveCalls(
- file_get_contents(\OC::$SERVERROOT . '/tests/data/integritycheck/core.key'),
- file_get_contents(\OC::$SERVERROOT . '/tests/data/integritycheck/core.crt'),
- );
+ ->willReturnMap([
+ ['privateKey', file_get_contents(\OC::$SERVERROOT . '/tests/data/integritycheck/core.key')],
+ ['certificate', \OC::$SERVERROOT . '/tests/data/integritycheck/core.crt'],
+ ]);
$this->checker
->expects($this->once())
@@ -271,9 +263,9 @@ class SignAppTest extends TestCase {
$outputInterface
->expects($this->any())
->method('writeln')
- ->withConsecutive(
- ['Successfully signed "AppId"']
- );
+ ->willReturnCallback(function (string $message): void {
+ $this->assertEquals('Successfully signed "AppId"', $message);
+ });
$this->assertSame(0, self::invokePrivate($this->signApp, 'execute', [$inputInterface, $outputInterface]));
}
diff --git a/tests/lib/Command/Integrity/SignCoreTest.php b/tests/lib/Command/Integrity/SignCoreTest.php
index bbb68e00a84..843084eebd9 100644
--- a/tests/lib/Command/Integrity/SignCoreTest.php
+++ b/tests/lib/Command/Integrity/SignCoreTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -39,22 +40,18 @@ class SignCoreTest extends TestCase {
$inputInterface
->expects($this->exactly(3))
->method('getOption')
- ->withConsecutive(
- ['privateKey'],
- ['certificate'],
- ['path'],
- )->willReturnOnConsecutiveCalls(
- null,
- 'certificate',
- 'certificate',
- );
+ ->willReturnMap([
+ ['privateKey', null],
+ ['certificate', 'certificate'],
+ ['path', 'certificate'],
+ ]);
$outputInterface
->expects($this->any())
->method('writeln')
- ->withConsecutive(
- ['--privateKey, --certificate and --path are required.']
- );
+ ->willReturnCallback(function (string $message): void {
+ $this->assertEquals('--privateKey, --certificate and --path are required.', $message);
+ });
$this->assertSame(1, self::invokePrivate($this->signCore, 'execute', [$inputInterface, $outputInterface]));
}
@@ -66,22 +63,18 @@ class SignCoreTest extends TestCase {
$inputInterface
->expects($this->exactly(3))
->method('getOption')
- ->withConsecutive(
- ['privateKey'],
- ['certificate'],
- ['path'],
- )->willReturnOnConsecutiveCalls(
- 'privateKey',
- null,
- 'certificate',
- );
+ ->willReturnMap([
+ ['privateKey', 'privateKey'],
+ ['certificate', null],
+ ['path', 'certificate'],
+ ]);
$outputInterface
->expects($this->any())
->method('writeln')
- ->withConsecutive(
- ['--privateKey, --certificate and --path are required.']
- );
+ ->willReturnCallback(function (string $message): void {
+ $this->assertEquals('--privateKey, --certificate and --path are required.', $message);
+ });
$this->assertSame(1, self::invokePrivate($this->signCore, 'execute', [$inputInterface, $outputInterface]));
}
@@ -93,32 +86,24 @@ class SignCoreTest extends TestCase {
$inputInterface
->expects($this->exactly(3))
->method('getOption')
- ->withConsecutive(
- ['privateKey'],
- ['certificate'],
- ['path'],
- )->willReturnOnConsecutiveCalls(
- 'privateKey',
- 'certificate',
- 'certificate',
- );
+ ->willReturnMap([
+ ['privateKey', 'privateKey'],
+ ['certificate', 'certificate'],
+ ['path', 'certificate'],
+ ]);
$this->fileAccessHelper
- ->expects($this->any())
->method('file_get_contents')
- ->withConsecutive(
- ['privateKey'],
- )
- ->willReturnOnConsecutiveCalls(
- false,
- );
+ ->willReturnMap([
+ ['privateKey', false],
+ ]);
$outputInterface
->expects($this->any())
->method('writeln')
- ->withConsecutive(
- ['Private key "privateKey" does not exists.']
- );
+ ->willReturnCallback(function (string $message): void {
+ $this->assertEquals('Private key "privateKey" does not exists.', $message);
+ });
$this->assertSame(1, self::invokePrivate($this->signCore, 'execute', [$inputInterface, $outputInterface]));
}
@@ -130,34 +115,26 @@ class SignCoreTest extends TestCase {
$inputInterface
->expects($this->exactly(3))
->method('getOption')
- ->withConsecutive(
- ['privateKey'],
- ['certificate'],
- ['path'],
- )->willReturnOnConsecutiveCalls(
- 'privateKey',
- 'certificate',
- 'certificate',
- );
+ ->willReturnMap([
+ ['privateKey', 'privateKey'],
+ ['certificate', 'certificate'],
+ ['path', 'certificate'],
+ ]);
$this->fileAccessHelper
->expects($this->any())
->method('file_get_contents')
- ->withConsecutive(
- ['privateKey'],
- ['certificate'],
- )
- ->willReturnOnConsecutiveCalls(
- file_get_contents(\OC::$SERVERROOT . '/tests/data/integritycheck/core.key'),
- false,
- );
+ ->willReturnMap([
+ ['privateKey', file_get_contents(\OC::$SERVERROOT . '/tests/data/integritycheck/core.key')],
+ ['certificate', false],
+ ]);
$outputInterface
->expects($this->any())
->method('writeln')
- ->withConsecutive(
- ['Certificate "certificate" does not exists.']
- );
+ ->willReturnCallback(function (string $message): void {
+ $this->assertEquals('Certificate "certificate" does not exists.', $message);
+ });
$this->assertSame(1, self::invokePrivate($this->signCore, 'execute', [$inputInterface, $outputInterface]));
}
@@ -169,27 +146,19 @@ class SignCoreTest extends TestCase {
$inputInterface
->expects($this->exactly(3))
->method('getOption')
- ->withConsecutive(
- ['privateKey'],
- ['certificate'],
- ['path'],
- )->willReturnOnConsecutiveCalls(
- 'privateKey',
- 'certificate',
- 'certificate',
- );
+ ->willReturnMap([
+ ['privateKey', 'privateKey'],
+ ['certificate', 'certificate'],
+ ['path', 'certificate'],
+ ]);
$this->fileAccessHelper
->expects($this->any())
->method('file_get_contents')
- ->withConsecutive(
- ['privateKey'],
- ['certificate'],
- )
- ->willReturnOnConsecutiveCalls(
- file_get_contents(\OC::$SERVERROOT . '/tests/data/integritycheck/core.key'),
- file_get_contents(\OC::$SERVERROOT . '/tests/data/integritycheck/core.crt'),
- );
+ ->willReturnMap([
+ ['privateKey', file_get_contents(\OC::$SERVERROOT . '/tests/data/integritycheck/core.key')],
+ ['certificate', file_get_contents(\OC::$SERVERROOT . '/tests/data/integritycheck/core.crt')],
+ ]);
$this->checker
->expects($this->once())
@@ -199,9 +168,9 @@ class SignCoreTest extends TestCase {
$outputInterface
->expects($this->any())
->method('writeln')
- ->withConsecutive(
- ['Error: My exception message']
- );
+ ->willReturnCallback(function (string $message): void {
+ $this->assertEquals('Error: My exception message', $message);
+ });
$this->assertEquals(1, self::invokePrivate($this->signCore, 'execute', [$inputInterface, $outputInterface]));
}
@@ -213,27 +182,19 @@ class SignCoreTest extends TestCase {
$inputInterface
->expects($this->exactly(3))
->method('getOption')
- ->withConsecutive(
- ['privateKey'],
- ['certificate'],
- ['path'],
- )->willReturnOnConsecutiveCalls(
- 'privateKey',
- 'certificate',
- 'certificate',
- );
+ ->willReturnMap([
+ ['privateKey', 'privateKey'],
+ ['certificate', 'certificate'],
+ ['path', 'certificate'],
+ ]);
$this->fileAccessHelper
->expects($this->any())
->method('file_get_contents')
- ->withConsecutive(
- ['privateKey'],
- ['certificate'],
- )
- ->willReturnOnConsecutiveCalls(
- file_get_contents(\OC::$SERVERROOT . '/tests/data/integritycheck/core.key'),
- file_get_contents(\OC::$SERVERROOT . '/tests/data/integritycheck/core.crt'),
- );
+ ->willReturnMap([
+ ['privateKey', file_get_contents(\OC::$SERVERROOT . '/tests/data/integritycheck/core.key')],
+ ['certificate', file_get_contents(\OC::$SERVERROOT . '/tests/data/integritycheck/core.crt')],
+ ]);
$this->checker
->expects($this->once())
@@ -242,9 +203,9 @@ class SignCoreTest extends TestCase {
$outputInterface
->expects($this->any())
->method('writeln')
- ->withConsecutive(
- ['Successfully signed "core"']
- );
+ ->willReturnCallback(function (string $message): void {
+ $this->assertEquals('Successfully signed "core"', $message);
+ });
$this->assertEquals(0, self::invokePrivate($this->signCore, 'execute', [$inputInterface, $outputInterface]));
}
diff --git a/tests/lib/Comments/CommentTest.php b/tests/lib/Comments/CommentTest.php
index 3cfc897b28e..4a320666c83 100644
--- a/tests/lib/Comments/CommentTest.php
+++ b/tests/lib/Comments/CommentTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -8,11 +9,13 @@ 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 {
/**
- * @throws \OCP\Comments\IllegalIDChangeException
+ * @throws IllegalIDChangeException
*/
public function testSettersValidInput(): void {
$comment = new Comment();
@@ -62,7 +65,7 @@ class CommentTest extends TestCase {
public function testSetIdIllegalInput(): void {
- $this->expectException(\OCP\Comments\IllegalIDChangeException::class);
+ $this->expectException(IllegalIDChangeException::class);
$comment = new Comment();
@@ -71,7 +74,7 @@ class CommentTest extends TestCase {
}
/**
- * @throws \OCP\Comments\IllegalIDChangeException
+ * @throws IllegalIDChangeException
*/
public function testResetId(): void {
$comment = new Comment();
@@ -81,7 +84,7 @@ class CommentTest extends TestCase {
$this->assertSame('', $comment->getId());
}
- public function simpleSetterProvider() {
+ public static function simpleSetterProvider(): array {
return [
['Id', true],
['TopmostParentId', true],
@@ -93,9 +96,7 @@ class CommentTest extends TestCase {
];
}
- /**
- * @dataProvider simpleSetterProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('simpleSetterProvider')]
public function testSimpleSetterInvalidInput($field, $input): void {
$this->expectException(\InvalidArgumentException::class);
@@ -105,7 +106,7 @@ class CommentTest extends TestCase {
$comment->$setter($input);
}
- public function roleSetterProvider() {
+ public static function roleSetterProvider(): array {
return [
['Actor', true, true],
['Actor', 'users', true],
@@ -118,9 +119,7 @@ class CommentTest extends TestCase {
];
}
- /**
- * @dataProvider roleSetterProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('roleSetterProvider')]
public function testSetRoleInvalidInput($role, $type, $id): void {
$this->expectException(\InvalidArgumentException::class);
@@ -131,14 +130,14 @@ 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');
$comment->setMessage($msg);
}
- public function mentionsProvider(): array {
+ public static function mentionsProvider(): array {
return [
[
'@alice @bob look look, a cook!',
@@ -158,11 +157,11 @@ class CommentTest extends TestCase {
/* author: */ 'alice'
],
[
- '@foobar and @barfoo you should know, @foo@bar.com is valid' .
- ' and so is @bar@foo.org@foobar.io I hope that clarifies everything.' .
- ' cc @23452-4333-54353-2342 @yolo!' .
- ' however the most important thing to know is that www.croissant.com/@oil is not valid' .
- ' and won\'t match anything at all',
+ '@foobar and @barfoo you should know, @foo@bar.com is valid'
+ . ' and so is @bar@foo.org@foobar.io I hope that clarifies everything.'
+ . ' cc @23452-4333-54353-2342 @yolo!'
+ . ' however the most important thing to know is that www.croissant.com/@oil is not valid'
+ . ' and won\'t match anything at all',
[
['type' => 'user', 'id' => 'bar@foo.org@foobar.io'],
['type' => 'user', 'id' => '23452-4333-54353-2342'],
@@ -206,12 +205,12 @@ class CommentTest extends TestCase {
}
/**
- * @dataProvider mentionsProvider
*
* @param string $message
* @param array $expectedMentions
* @param ?string $author
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('mentionsProvider')]
public function testMentions(string $message, array $expectedMentions, ?string $author = null): void {
$comment = new Comment();
$comment->setMessage($message);
diff --git a/tests/lib/Comments/FakeFactory.php b/tests/lib/Comments/FakeFactory.php
index 04604ab2b44..0c3241078d7 100644
--- a/tests/lib/Comments/FakeFactory.php
+++ b/tests/lib/Comments/FakeFactory.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -6,12 +7,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/FakeManager.php b/tests/lib/Comments/FakeManager.php
index 155bbc59dce..64a25ef46c8 100644
--- a/tests/lib/Comments/FakeManager.php
+++ b/tests/lib/Comments/FakeManager.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
diff --git a/tests/lib/Comments/ManagerTest.php b/tests/lib/Comments/ManagerTest.php
index c187f664215..bd991a5692a 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');
@@ -376,9 +376,7 @@ class ManagerTest extends TestCase {
], $amount);
}
- /**
- * @dataProvider dataGetForObjectSince
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataGetForObjectSince')]
public function testGetForObjectSince(?int $lastKnown, string $order, int $limit, int $resultFrom, int $resultTo): void {
$ids = [];
$ids[] = $this->addDatabaseEntry(0, 0);
@@ -424,9 +422,7 @@ class ManagerTest extends TestCase {
];
}
- /**
- * @dataProvider invalidCreateArgsProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('invalidCreateArgsProvider')]
public function testCreateCommentInvalidArguments(string|int $aType, string|int $aId, string|int $oType, string|int $oId): void {
$this->expectException(\InvalidArgumentException::class);
@@ -450,7 +446,7 @@ class ManagerTest extends TestCase {
public function testDelete(): void {
- $this->expectException(\OCP\Comments\NotFoundException::class);
+ $this->expectException(NotFoundException::class);
$manager = $this->getManager();
@@ -471,9 +467,7 @@ class ManagerTest extends TestCase {
$manager->get($id);
}
- /**
- * @dataProvider providerTestSave
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('providerTestSave')]
public function testSave(string $message, string $actorId, string $verb, ?string $parentId, ?string $id = ''): IComment {
$manager = $this->getManager();
$comment = new Comment();
@@ -564,7 +558,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);
}
@@ -613,9 +607,7 @@ class ManagerTest extends TestCase {
];
}
- /**
- * @dataProvider invalidActorArgsProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('invalidActorArgsProvider')]
public function testDeleteReferencesOfActorInvalidInput(string|int $type, string|int $id): void {
$this->expectException(\InvalidArgumentException::class);
@@ -652,10 +644,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.')
@@ -680,9 +672,7 @@ class ManagerTest extends TestCase {
];
}
- /**
- * @dataProvider invalidObjectArgsProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('invalidObjectArgsProvider')]
public function testDeleteCommentsAtObjectInvalidInput(string|int $type, string|int $id): void {
$this->expectException(\InvalidArgumentException::class);
@@ -1006,9 +996,7 @@ class ManagerTest extends TestCase {
}
}
- /**
- * @dataProvider providerTestReactionAddAndDelete
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('providerTestReactionAddAndDelete')]
public function testReactionAddAndDelete(array $comments, array $reactionsExpected): void {
$this->skipIfNotSupport4ByteUTF();
$manager = $this->getManager();
@@ -1073,6 +1061,7 @@ class ManagerTest extends TestCase {
* @return array<string, IComment>
*/
private function proccessComments(array $data): array {
+ $this->connection->beginTransaction();
/** @var array<string, IComment> $comments */
$comments = [];
foreach ($data as $comment) {
@@ -1088,12 +1077,11 @@ class ManagerTest extends TestCase {
$comment = $this->testSave($message, $actorId, $verb, $parentId, $id);
$comments[$comment->getMessage() . '#' . $comment->getActorId()] = $comment;
}
+ $this->connection->commit();
return $comments;
}
- /**
- * @dataProvider providerTestRetrieveAllReactions
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('providerTestRetrieveAllReactions')]
public function testRetrieveAllReactions(array $comments, array $expected): void {
$this->skipIfNotSupport4ByteUTF();
$manager = $this->getManager();
@@ -1107,6 +1095,10 @@ class ManagerTest extends TestCase {
$row->getMessage(),
];
}, $all);
+
+ usort($actual, static fn (array $a, array $b): int => $a[1] <=> $b[1]);
+ usort($expected, static fn (array $a, array $b): int => $a[1] <=> $b[1]);
+
$this->assertEqualsCanonicalizing($expected, $actual);
}
@@ -2351,9 +2343,7 @@ class ManagerTest extends TestCase {
];
}
- /**
- * @dataProvider providerTestRetrieveAllReactionsWithSpecificReaction
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('providerTestRetrieveAllReactionsWithSpecificReaction')]
public function testRetrieveAllReactionsWithSpecificReaction(array $comments, string $reaction, array $expected): void {
$this->skipIfNotSupport4ByteUTF();
$manager = $this->getManager();
@@ -2406,9 +2396,7 @@ class ManagerTest extends TestCase {
];
}
- /**
- * @dataProvider providerTestGetReactionComment
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('providerTestGetReactionComment')]
public function testGetReactionComment(array $comments, array $expected, bool $notFound): void {
$this->skipIfNotSupport4ByteUTF();
$manager = $this->getManager();
@@ -2419,7 +2407,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());
@@ -2475,9 +2463,7 @@ class ManagerTest extends TestCase {
];
}
- /**
- * @dataProvider providerTestReactionMessageSize
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('providerTestReactionMessageSize')]
public function testReactionMessageSize(string $reactionString, bool $valid): void {
$this->skipIfNotSupport4ByteUTF();
if (!$valid) {
@@ -2506,9 +2492,7 @@ class ManagerTest extends TestCase {
];
}
- /**
- * @dataProvider providerTestReactionsSummarizeOrdered
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('providerTestReactionsSummarizeOrdered')]
public function testReactionsSummarizeOrdered(array $comments, array $expected, bool $isFullMatch): void {
$this->skipIfNotSupport4ByteUTF();
$manager = $this->getManager();
diff --git a/tests/lib/Config/LexiconTest.php b/tests/lib/Config/LexiconTest.php
index 5bcd3509b22..530767a7416 100644
--- a/tests/lib/Config/LexiconTest.php
+++ b/tests/lib/Config/LexiconTest.php
@@ -10,7 +10,9 @@ namespace Tests\lib\Config;
use NCU\Config\Exceptions\TypeConflictException;
use NCU\Config\Exceptions\UnknownKeyException;
use NCU\Config\IUserConfig;
+use OC\AppConfig;
use OC\AppFramework\Bootstrap\Coordinator;
+use OC\Config\ConfigManager;
use OCP\Exceptions\AppConfigTypeConflictException;
use OCP\Exceptions\AppConfigUnknownKeyException;
use OCP\IAppConfig;
@@ -25,13 +27,15 @@ use Test\TestCase;
* @package Test
*/
class LexiconTest extends TestCase {
+ /** @var AppConfig */
private IAppConfig $appConfig;
private IUserConfig $userConfig;
+ private ConfigManager $configManager;
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);
@@ -39,6 +43,7 @@ class LexiconTest extends TestCase {
$this->appConfig = Server::get(IAppConfig::class);
$this->userConfig = Server::get(IUserConfig::class);
+ $this->configManager = Server::get(ConfigManager::class);
}
protected function tearDown(): void {
@@ -141,11 +146,61 @@ class LexiconTest extends TestCase {
public function testUserLexiconSetException() {
$this->expectException(UnknownKeyException::class);
$this->userConfig->setValueString('user1', TestConfigLexicon_E::APPID, 'key_exception', 'new_value');
- $this->assertSame('', $this->userConfig->getValueString('user1', TestConfigLexicon_E::APPID, 'key3', ''));
+ $this->assertSame('', $this->userConfig->getValueString('user1', TestConfigLexicon_E::APPID, 'key5', ''));
}
public function testUserLexiconGetException() {
$this->expectException(UnknownKeyException::class);
$this->userConfig->getValueString('user1', TestConfigLexicon_E::APPID, 'key_exception');
}
+
+ public function testAppConfigLexiconRenameSetNewValue() {
+ $this->assertSame(12345, $this->appConfig->getValueInt(TestConfigLexicon_I::APPID, 'key3', 123));
+ $this->appConfig->setValueInt(TestConfigLexicon_I::APPID, 'old_key3', 994);
+ $this->assertSame(994, $this->appConfig->getValueInt(TestConfigLexicon_I::APPID, 'key3', 123));
+ }
+
+ public function testAppConfigLexiconRenameSetOldValuePreMigration() {
+ $this->appConfig->ignoreLexiconAliases(true);
+ $this->appConfig->setValueInt(TestConfigLexicon_I::APPID, 'old_key3', 993);
+ $this->appConfig->ignoreLexiconAliases(false);
+ $this->assertSame(12345, $this->appConfig->getValueInt(TestConfigLexicon_I::APPID, 'key3', 123));
+ }
+
+ public function testAppConfigLexiconRenameSetOldValuePostMigration() {
+ $this->appConfig->ignoreLexiconAliases(true);
+ $this->appConfig->setValueInt(TestConfigLexicon_I::APPID, 'old_key3', 994);
+ $this->appConfig->ignoreLexiconAliases(false);
+ $this->configManager->migrateConfigLexiconKeys(TestConfigLexicon_I::APPID);
+ $this->assertSame(994, $this->appConfig->getValueInt(TestConfigLexicon_I::APPID, 'key3', 123));
+ }
+
+ public function testAppConfigLexiconRenameGetNewValue() {
+ $this->appConfig->setValueInt(TestConfigLexicon_I::APPID, 'key3', 981);
+ $this->assertSame(981, $this->appConfig->getValueInt(TestConfigLexicon_I::APPID, 'old_key3', 123));
+ }
+
+ public function testAppConfigLexiconRenameGetOldValuePreMigration() {
+ $this->appConfig->ignoreLexiconAliases(true);
+ $this->appConfig->setValueInt(TestConfigLexicon_I::APPID, 'key3', 984);
+ $this->assertSame(123, $this->appConfig->getValueInt(TestConfigLexicon_I::APPID, 'old_key3', 123));
+ $this->appConfig->ignoreLexiconAliases(false);
+ }
+
+ public function testAppConfigLexiconRenameGetOldValuePostMigration() {
+ $this->appConfig->ignoreLexiconAliases(true);
+ $this->appConfig->setValueInt(TestConfigLexicon_I::APPID, 'key3', 987);
+ $this->appConfig->ignoreLexiconAliases(false);
+ $this->configManager->migrateConfigLexiconKeys(TestConfigLexicon_I::APPID);
+ $this->assertSame(987, $this->appConfig->getValueInt(TestConfigLexicon_I::APPID, 'old_key3', 123));
+ }
+
+ public function testAppConfigLexiconRenameInvertBoolean() {
+ $this->appConfig->ignoreLexiconAliases(true);
+ $this->appConfig->setValueBool(TestConfigLexicon_I::APPID, 'old_key4', true);
+ $this->appConfig->ignoreLexiconAliases(false);
+ $this->assertSame(true, $this->appConfig->getValueBool(TestConfigLexicon_I::APPID, 'key4'));
+ $this->configManager->migrateConfigLexiconKeys(TestConfigLexicon_I::APPID);
+ $this->assertSame(false, $this->appConfig->getValueBool(TestConfigLexicon_I::APPID, 'key4'));
+ }
}
diff --git a/tests/lib/Config/TestConfigLexicon_I.php b/tests/lib/Config/TestConfigLexicon_I.php
index 497c62acecb..6fb7921b6e6 100644
--- a/tests/lib/Config/TestConfigLexicon_I.php
+++ b/tests/lib/Config/TestConfigLexicon_I.php
@@ -25,8 +25,9 @@ class TestConfigLexicon_I implements IConfigLexicon {
public function getAppConfigs(): array {
return [
new ConfigLexiconEntry('key1', ValueType::STRING, 'abcde', 'test key', true, IAppConfig::FLAG_SENSITIVE),
- new ConfigLexiconEntry('key2', ValueType::INT, 12345, 'test key', false)
-
+ new ConfigLexiconEntry('key2', ValueType::INT, 12345, 'test key', false),
+ new ConfigLexiconEntry('key3', ValueType::INT, 12345, 'test key', true, rename: 'old_key3'),
+ new ConfigLexiconEntry('key4', ValueType::BOOL, 12345, 'test key', true, rename: 'old_key4', options: ConfigLexiconEntry::RENAME_INVERT_BOOLEAN),
];
}
diff --git a/tests/lib/Config/UserConfigTest.php b/tests/lib/Config/UserConfigTest.php
index f9a9b5c5272..2c8222576c4 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;
@@ -35,10 +36,10 @@ class UserConfigTest extends TestCase {
/**
* @var array<string, array<string, array<array<string, string, int, bool, bool>>> [userId => [appId => prefKey, prefValue, valueType, lazy, sensitive]]]
*/
- private array $basePreferences =
- [
- 'user1' =>
- [
+ private array $basePreferences
+ = [
+ 'user1'
+ => [
'app1' => [
'key1' => ['key1', 'value1'],
'key22' => ['key22', '31'],
@@ -97,8 +98,8 @@ class UserConfigTest extends TestCase {
'key5' => ['key5', true, ValueType::BOOL, true],
]
],
- 'user2' =>
- [
+ 'user2'
+ => [
'app1' => [
'1' => ['1', 'value1'],
'2' => ['2', 'value2', ValueType::STRING, true, UserConfig::FLAG_SENSITIVE],
@@ -120,8 +121,8 @@ class UserConfigTest extends TestCase {
'key1' => ['key1', 'value1', ValueType::STRING, true, 0, true]
]
],
- 'user3' =>
- [
+ 'user3'
+ => [
'app2' => [
'key2' => ['key2', 'value2c', ValueType::MIXED, false, 0, true],
'key3' => ['key3', 'value3', ValueType::STRING, true, ],
@@ -137,8 +138,8 @@ class UserConfigTest extends TestCase {
'key3' => ['key3', 'value3', ValueType::STRING, true]
]
],
- 'user4' =>
- [
+ 'user4'
+ => [
'app2' => [
'key1' => ['key1', 'value1'],
'key2' => ['key2', 'value2A', ValueType::MIXED, false, 0, true],
@@ -152,8 +153,8 @@ class UserConfigTest extends TestCase {
'key1' => ['key1', 123, ValueType::INT, true, 0, true]
]
],
- 'user5' =>
- [
+ 'user5'
+ => [
'app1' => [
'key1' => ['key1', 'value1']
],
@@ -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,
@@ -333,10 +334,7 @@ class UserConfigTest extends TestCase {
);
}
- /**
- * @return array[]
- */
- public function providerHasKey(): array {
+ public static function providerHasKey(): array {
return [
['user1', 'app1', 'key1', false, true],
['user0', 'app1', 'key1', false, false],
@@ -350,18 +348,13 @@ class UserConfigTest extends TestCase {
];
}
- /**
- * @dataProvider providerHasKey
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('providerHasKey')]
public function testHasKey(string $userId, string $appId, string $key, ?bool $lazy, bool $result): void {
$userConfig = $this->generateUserConfig();
$this->assertEquals($result, $userConfig->hasKey($userId, $appId, $key, $lazy));
}
- /**
- * @return array[]
- */
- public function providerIsSensitive(): array {
+ public static function providerIsSensitive(): array {
return [
['user1', 'app1', 'key1', false, false, false],
['user0', 'app1', 'key1', false, false, true],
@@ -380,9 +373,7 @@ class UserConfigTest extends TestCase {
];
}
- /**
- * @dataProvider providerIsSensitive
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('providerIsSensitive')]
public function testIsSensitive(
string $userId,
string $appId,
@@ -399,10 +390,7 @@ class UserConfigTest extends TestCase {
$this->assertEquals($result, $userConfig->isSensitive($userId, $appId, $key, $lazy));
}
- /**
- * @return array[]
- */
- public function providerIsLazy(): array {
+ public static function providerIsLazy(): array {
return [
['user1', 'app1', 'key1', false, false],
['user0', 'app1', 'key1', false, true],
@@ -414,9 +402,7 @@ class UserConfigTest extends TestCase {
];
}
- /**
- * @dataProvider providerIsLazy
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('providerIsLazy')]
public function testIsLazy(
string $userId,
string $appId,
@@ -432,7 +418,7 @@ class UserConfigTest extends TestCase {
$this->assertEquals($result, $userConfig->isLazy($userId, $appId, $key));
}
- public function providerGetValues(): array {
+ public static function providerGetValues(): array {
return [
[
'user1', 'app1', '', true,
@@ -549,9 +535,7 @@ class UserConfigTest extends TestCase {
];
}
- /**
- * @dataProvider providerGetValues
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('providerGetValues')]
public function testGetValues(
string $userId,
string $appId,
@@ -565,7 +549,7 @@ class UserConfigTest extends TestCase {
);
}
- public function providerGetAllValues(): array {
+ public static function providerGetAllValues(): array {
return [
[
'user2', false,
@@ -650,9 +634,7 @@ class UserConfigTest extends TestCase {
];
}
- /**
- * @dataProvider providerGetAllValues
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('providerGetAllValues')]
public function testGetAllValues(
string $userId,
bool $filtered,
@@ -662,7 +644,7 @@ class UserConfigTest extends TestCase {
$this->assertEqualsCanonicalizing($result, $userConfig->getAllValues($userId, $filtered));
}
- public function providerSearchValuesByApps(): array {
+ public static function providerSearchValuesByApps(): array {
return [
[
'user1', 'key1', false, null,
@@ -694,9 +676,7 @@ class UserConfigTest extends TestCase {
];
}
- /**
- * @dataProvider providerSearchValuesByApps
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('providerSearchValuesByApps')]
public function testSearchValuesByApps(
string $userId,
string $key,
@@ -708,7 +688,7 @@ class UserConfigTest extends TestCase {
$this->assertEquals($result, $userConfig->getValuesByApps($userId, $key, $lazy, $typedAs));
}
- public function providerSearchValuesByUsers(): array {
+ public static function providerSearchValuesByUsers(): array {
return [
[
'app2', 'key2', null, null,
@@ -744,9 +724,7 @@ class UserConfigTest extends TestCase {
];
}
- /**
- * @dataProvider providerSearchValuesByUsers
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('providerSearchValuesByUsers')]
public function testSearchValuesByUsers(
string $app,
string $key,
@@ -760,7 +738,7 @@ class UserConfigTest extends TestCase {
);
}
- public function providerSearchValuesByValueString(): array {
+ public static function providerSearchValuesByValueString(): array {
return [
['app2', 'key2', 'value2a', false, ['user1']],
['app2', 'key2', 'value2A', false, ['user4']],
@@ -768,9 +746,7 @@ class UserConfigTest extends TestCase {
];
}
- /**
- * @dataProvider providerSearchValuesByValueString
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('providerSearchValuesByValueString')]
public function testSearchUsersByValueString(
string $app,
string $key,
@@ -782,7 +758,7 @@ class UserConfigTest extends TestCase {
$this->assertEqualsCanonicalizing($result, iterator_to_array($userConfig->searchUsersByValueString($app, $key, $value, $ci)));
}
- public function providerSearchValuesByValueInt(): array {
+ public static function providerSearchValuesByValueInt(): array {
return [
['app3', 'key8', 12, []], // sensitive value, cannot search
['app2', 'key8', 12, ['user2', 'user5']], // sensitive value, cannot search
@@ -790,9 +766,7 @@ class UserConfigTest extends TestCase {
];
}
- /**
- * @dataProvider providerSearchValuesByValueInt
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('providerSearchValuesByValueInt')]
public function testSearchUsersByValueInt(
string $app,
string $key,
@@ -803,16 +777,14 @@ class UserConfigTest extends TestCase {
$this->assertEqualsCanonicalizing($result, iterator_to_array($userConfig->searchUsersByValueInt($app, $key, $value)));
}
- public function providerSearchValuesByValues(): array {
+ public static function providerSearchValuesByValues(): array {
return [
['app2', 'key2', ['value2a', 'value2b'], ['user1', 'user2']],
['app2', 'key2', ['value2a', 'value2c'], ['user1', 'user3']],
];
}
- /**
- * @dataProvider providerSearchValuesByValues
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('providerSearchValuesByValues')]
public function testSearchUsersByValues(
string $app,
string $key,
@@ -823,16 +795,14 @@ class UserConfigTest extends TestCase {
$this->assertEqualsCanonicalizing($result, iterator_to_array($userConfig->searchUsersByValues($app, $key, $values)));
}
- public function providerSearchValuesByValueBool(): array {
+ public static function providerSearchValuesByValueBool(): array {
return [
['app3', 'key10', true, ['user1', 'user4']],
['app3', 'key10', false, ['user2']],
];
}
- /**
- * @dataProvider providerSearchValuesByValueBool
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('providerSearchValuesByValueBool')]
public function testSearchUsersByValueBool(
string $app,
string $key,
@@ -843,7 +813,7 @@ class UserConfigTest extends TestCase {
$this->assertEqualsCanonicalizing($result, iterator_to_array($userConfig->searchUsersByValueBool($app, $key, $value)));
}
- public function providerGetValueMixed(): array {
+ public static function providerGetValueMixed(): array {
return [
[
['user1'], 'user1', 'app1', 'key0', 'default_because_unknown_key', true,
@@ -911,9 +881,7 @@ class UserConfigTest extends TestCase {
];
}
- /**
- * @dataProvider providerGetValueMixed
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('providerGetValueMixed')]
public function testGetValueMixed(
?array $preload,
string $userId,
@@ -927,9 +895,7 @@ class UserConfigTest extends TestCase {
$this->assertEquals($result, $userConfig->getValueMixed($userId, $app, $key, $default, $lazy));
}
- /**
- * @dataProvider providerGetValueMixed
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('providerGetValueMixed')]
public function testGetValueString(
?array $preload,
string $userId,
@@ -943,7 +909,7 @@ class UserConfigTest extends TestCase {
$this->assertEquals($result, $userConfig->getValueString($userId, $app, $key, $default, $lazy));
}
- public function providerGetValueInt(): array {
+ public static function providerGetValueInt(): array {
return [
[['user1'], 'user1', 'app1', 'key0', 54321, true, 54321],
[null, 'user1', 'app1', 'key0', 54321, true, 54321],
@@ -969,9 +935,7 @@ class UserConfigTest extends TestCase {
];
}
- /**
- * @dataProvider providerGetValueInt
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('providerGetValueInt')]
public function testGetValueInt(
?array $preload,
string $userId,
@@ -985,7 +949,7 @@ class UserConfigTest extends TestCase {
$this->assertEquals($result, $userConfig->getValueInt($userId, $app, $key, $default, $lazy));
}
- public function providerGetValueFloat(): array {
+ public static function providerGetValueFloat(): array {
return [
[['user1'], 'user1', 'app1', 'key0', 54.321, true, 54.321],
[null, 'user1', 'app1', 'key0', 54.321, true, 54.321],
@@ -1010,9 +974,7 @@ class UserConfigTest extends TestCase {
];
}
- /**
- * @dataProvider providerGetValueFloat
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('providerGetValueFloat')]
public function testGetValueFloat(
?array $preload,
string $userId,
@@ -1026,7 +988,7 @@ class UserConfigTest extends TestCase {
$this->assertEquals($result, $userConfig->getValueFloat($userId, $app, $key, $default, $lazy));
}
- public function providerGetValueBool(): array {
+ public static function providerGetValueBool(): array {
return [
[['user1'], 'user1', 'app1', 'key0', false, true, false],
[null, 'user1', 'app1', 'key0', false, true, false],
@@ -1071,9 +1033,7 @@ class UserConfigTest extends TestCase {
];
}
- /**
- * @dataProvider providerGetValueBool
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('providerGetValueBool')]
public function testGetValueBool(
?array $preload,
string $userId,
@@ -1087,7 +1047,7 @@ class UserConfigTest extends TestCase {
$this->assertEquals($result, $userConfig->getValueBool($userId, $app, $key, $default, $lazy));
}
- public function providerGetValueArray(): array {
+ public static function providerGetValueArray(): array {
return [
[
['user1'], 'user1', 'app1', 'key0', ['default_because_unknown_key'], true,
@@ -1108,9 +1068,7 @@ class UserConfigTest extends TestCase {
];
}
- /**
- * @dataProvider providerGetValueArray
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('providerGetValueArray')]
public function testGetValueArray(
?array $preload,
string $userId,
@@ -1126,7 +1084,7 @@ class UserConfigTest extends TestCase {
);
}
- public function providerGetValueType(): array {
+ public static function providerGetValueType(): array {
return [
[null, 'user1', 'app1', 'key1', false, ValueType::MIXED],
[null, 'user1', 'app1', 'key1', true, null, UnknownKeyException::class],
@@ -1164,9 +1122,7 @@ class UserConfigTest extends TestCase {
];
}
- /**
- * @dataProvider providerGetValueType
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('providerGetValueType')]
public function testGetValueType(
?array $preload,
string $userId,
@@ -1187,7 +1143,7 @@ class UserConfigTest extends TestCase {
}
}
- public function providerSetValueMixed(): array {
+ public static function providerSetValueMixed(): array {
return [
[null, 'user1', 'app1', 'key1', 'value', false, false, true],
[null, 'user1', 'app1', 'key1', '12345', true, false, true],
@@ -1223,9 +1179,7 @@ class UserConfigTest extends TestCase {
];
}
- /**
- * @dataProvider providerSetValueMixed
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('providerSetValueMixed')]
public function testSetValueMixed(
?array $preload,
string $userId,
@@ -1249,8 +1203,21 @@ class UserConfigTest extends TestCase {
}
}
+ /**
+ * This test needs to stay! Emails are expected to be lowercase due to performance reasons.
+ * This way we can skip the expensive casing change on the database.
+ */
+ public function testSetValueMixedWithSettingsEmail(): void {
+ $userConfig = $this->generateUserConfig();
- public function providerSetValueString(): array {
+ $edited = $userConfig->setValueMixed('user1', 'settings', 'email', 'mixed.CASE@Nextcloud.com');
+ $this->assertTrue($edited);
+
+ $actual = $userConfig->getValueMixed('user1', 'settings', 'email');
+ $this->assertEquals('mixed.case@nextcloud.com', $actual);
+ }
+
+ public static function providerSetValueString(): array {
return [
[null, 'user1', 'app1', 'key1', 'value', false, false, true],
[null, 'user1', 'app1', 'key1', '12345', true, false, true],
@@ -1293,9 +1260,7 @@ class UserConfigTest extends TestCase {
];
}
- /**
- * @dataProvider providerSetValueString
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('providerSetValueString')]
public function testSetValueString(
?array $preload,
string $userId,
@@ -1325,7 +1290,7 @@ class UserConfigTest extends TestCase {
}
}
- public function providerSetValueInt(): array {
+ public static function providerSetValueInt(): array {
return [
[null, 'user1', 'app1', 'key1', 12345, false, false, true],
[null, 'user1', 'app1', 'key1', 12345, true, false, true],
@@ -1356,9 +1321,7 @@ class UserConfigTest extends TestCase {
];
}
- /**
- * @dataProvider providerSetValueInt
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('providerSetValueInt')]
public function testSetValueInt(
?array $preload,
string $userId,
@@ -1389,7 +1352,7 @@ class UserConfigTest extends TestCase {
}
}
- public function providerSetValueFloat(): array {
+ public static function providerSetValueFloat(): array {
return [
[null, 'user1', 'app1', 'key1', 12.345, false, false, true],
[null, 'user1', 'app1', 'key1', 12.345, true, false, true],
@@ -1419,9 +1382,7 @@ class UserConfigTest extends TestCase {
];
}
- /**
- * @dataProvider providerSetValueFloat
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('providerSetValueFloat')]
public function testSetValueFloat(
?array $preload,
string $userId,
@@ -1453,7 +1414,7 @@ class UserConfigTest extends TestCase {
}
- public function providerSetValueArray(): array {
+ public static function providerSetValueArray(): array {
return [
[null, 'user1', 'app1', 'key1', [], false, false, true],
[null, 'user1', 'app1', 'key1', [], true, false, true],
@@ -1483,9 +1444,7 @@ class UserConfigTest extends TestCase {
];
}
- /**
- * @dataProvider providerSetValueArray
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('providerSetValueArray')]
public function testSetValueArray(
?array $preload,
string $userId,
@@ -1520,7 +1479,7 @@ class UserConfigTest extends TestCase {
}
}
- public function providerUpdateSensitive(): array {
+ public static function providerUpdateSensitive(): array {
return [
[null, 'user1', 'app1', 'key1', false, false],
[['user1'], 'user1', 'app1', 'key1', false, false],
@@ -1529,9 +1488,7 @@ class UserConfigTest extends TestCase {
];
}
- /**
- * @dataProvider providerUpdateSensitive
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('providerUpdateSensitive')]
public function testUpdateSensitive(
?array $preload,
string $userId,
@@ -1558,21 +1515,19 @@ class UserConfigTest extends TestCase {
$this->assertEquals($sensitive, $userConfig->isSensitive($userId, $app, $key));
if ($sensitive) {
$this->assertEquals(true, str_starts_with(
- $userConfig->statusCache()['fastCache'][$userId][$app][$key] ??
- $userConfig->statusCache()['lazyCache'][$userId][$app][$key],
+ $userConfig->statusCache()['fastCache'][$userId][$app][$key]
+ ?? $userConfig->statusCache()['lazyCache'][$userId][$app][$key],
'$UserConfigEncryption$')
);
}
}
}
- public function providerUpdateGlobalSensitive(): array {
+ public static function providerUpdateGlobalSensitive(): array {
return [[true], [false]];
}
- /**
- * @dataProvider providerUpdateGlobalSensitive
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('providerUpdateGlobalSensitive')]
public function testUpdateGlobalSensitive(bool $sensitive): void {
$userConfig = $this->generateUserConfig($preload ?? []);
$app = 'app2';
@@ -1589,8 +1544,8 @@ class UserConfigTest extends TestCase {
$userConfig->getValueString($userId, $app, $key); // cache loading for userId
$this->assertEquals(
!$sensitive, str_starts_with(
- $userConfig->statusCache()['fastCache'][$userId][$app][$key] ??
- $userConfig->statusCache()['lazyCache'][$userId][$app][$key],
+ $userConfig->statusCache()['fastCache'][$userId][$app][$key]
+ ?? $userConfig->statusCache()['lazyCache'][$userId][$app][$key],
'$UserConfigEncryption$'
)
);
@@ -1603,14 +1558,14 @@ class UserConfigTest extends TestCase {
$this->assertEquals($sensitive, $userConfig->isSensitive($userId, $app, $key));
// should only work if updateGlobalSensitive drop cache
$this->assertEquals($sensitive, str_starts_with(
- $userConfig->statusCache()['fastCache'][$userId][$app][$key] ??
- $userConfig->statusCache()['lazyCache'][$userId][$app][$key],
+ $userConfig->statusCache()['fastCache'][$userId][$app][$key]
+ ?? $userConfig->statusCache()['lazyCache'][$userId][$app][$key],
'$UserConfigEncryption$')
);
}
}
- public function providerUpdateLazy(): array {
+ public static function providerUpdateLazy(): array {
return [
[null, 'user1', 'app1', 'key1', false, false],
[['user1'], 'user1', 'app1', 'key1', false, false],
@@ -1619,9 +1574,7 @@ class UserConfigTest extends TestCase {
];
}
- /**
- * @dataProvider providerUpdateLazy
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('providerUpdateLazy')]
public function testUpdateLazy(
?array $preload,
string $userId,
@@ -1649,13 +1602,11 @@ class UserConfigTest extends TestCase {
}
}
- public function providerUpdateGlobalLazy(): array {
+ public static function providerUpdateGlobalLazy(): array {
return [[true], [false]];
}
- /**
- * @dataProvider providerUpdateGlobalLazy
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('providerUpdateGlobalLazy')]
public function testUpdateGlobalLazy(bool $lazy): void {
$userConfig = $this->generateUserConfig($preload ?? []);
$app = 'app2';
@@ -1679,7 +1630,7 @@ class UserConfigTest extends TestCase {
}
}
- public function providerGetDetails(): array {
+ public static function providerGetDetails(): array {
return [
[
'user3', 'app2', 'key2',
@@ -1723,16 +1674,14 @@ class UserConfigTest extends TestCase {
];
}
- /**
- * @dataProvider providerGetDetails
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('providerGetDetails')]
public function testGetDetails(string $userId, string $app, string $key, array $result): void {
$userConfig = $this->generateUserConfig($preload ?? []);
$this->assertEqualsCanonicalizing($result, $userConfig->getDetails($userId, $app, $key));
}
- public function providerDeletePreference(): array {
+ public static function providerDeletePreference(): array {
return [
[null, 'user1', 'app1', 'key22'],
[['user1'], 'user1', 'app1', 'fast_string_sensitive'],
@@ -1743,9 +1692,7 @@ class UserConfigTest extends TestCase {
];
}
- /**
- * @dataProvider providerDeletePreference
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('providerDeletePreference')]
public function testDeletePreference(
?array $preload,
string $userId,
@@ -1763,7 +1710,7 @@ class UserConfigTest extends TestCase {
$this->assertEquals(false, $userConfig->hasKey($userId, $app, $key, $lazy));
}
- public function providerDeleteKey(): array {
+ public static function providerDeleteKey(): array {
return [
[null, 'app2', 'key3'],
[['user1'], 'app2', 'key3'],
@@ -1774,9 +1721,7 @@ class UserConfigTest extends TestCase {
];
}
- /**
- * @dataProvider providerDeleteKey
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('providerDeleteKey')]
public function testDeleteKey(
?array $preload,
string $app,
@@ -1832,7 +1777,7 @@ class UserConfigTest extends TestCase {
'fastCache' => [],
'lazyLoaded' => [],
'lazyCache' => [],
- 'valueTypes' => [],
+ 'valueDetails' => [],
],
$userConfig->statusCache()
);
diff --git a/tests/lib/ConfigTest.php b/tests/lib/ConfigTest.php
index 3be066c6839..b2a52dbd6a4 100644
--- a/tests/lib/ConfigTest.php
+++ b/tests/lib/ConfigTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -8,6 +9,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 +25,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 +36,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 {
@@ -94,8 +97,8 @@ class ConfigTest extends TestCase {
$this->assertSame('moo', $config->getValue('foo'));
$content = file_get_contents($this->configFile);
- $expected = "<?php\n\$CONFIG = array (\n 'foo' => 'moo',\n 'beers' => \n array (\n 0 => 'Appenzeller',\n " .
- " 1 => 'Guinness',\n 2 => 'Kölsch',\n ),\n 'alcohol_free' => false,\n);\n";
+ $expected = "<?php\n\$CONFIG = array (\n 'foo' => 'moo',\n 'beers' => \n array (\n 0 => 'Appenzeller',\n "
+ . " 1 => 'Guinness',\n 2 => 'Kölsch',\n ),\n 'alcohol_free' => false,\n);\n";
$this->assertEquals($expected, $content);
$config->setValue('bar', 'red');
@@ -105,9 +108,9 @@ class ConfigTest extends TestCase {
$content = file_get_contents($this->configFile);
- $expected = "<?php\n\$CONFIG = array (\n 'foo' => 'moo',\n 'beers' => \n array (\n 0 => 'Appenzeller',\n " .
- " 1 => 'Guinness',\n 2 => 'Kölsch',\n ),\n 'alcohol_free' => false,\n 'bar' => 'red',\n 'apps' => \n " .
- " array (\n 0 => 'files',\n 1 => 'gallery',\n ),\n);\n";
+ $expected = "<?php\n\$CONFIG = array (\n 'foo' => 'moo',\n 'beers' => \n array (\n 0 => 'Appenzeller',\n "
+ . " 1 => 'Guinness',\n 2 => 'Kölsch',\n ),\n 'alcohol_free' => false,\n 'bar' => 'red',\n 'apps' => \n "
+ . " array (\n 0 => 'files',\n 1 => 'gallery',\n ),\n);\n";
$this->assertEquals($expected, $content);
}
@@ -136,8 +139,8 @@ class ConfigTest extends TestCase {
$this->assertSame(null, $config->getValue('not_exists'));
$content = file_get_contents($this->configFile);
- $expected = "<?php\n\$CONFIG = array (\n 'foo' => 'moo',\n 'beers' => \n array (\n 0 => 'Appenzeller',\n " .
- " 1 => 'Guinness',\n 2 => 'Kölsch',\n ),\n);\n";
+ $expected = "<?php\n\$CONFIG = array (\n 'foo' => 'moo',\n 'beers' => \n array (\n 0 => 'Appenzeller',\n "
+ . " 1 => 'Guinness',\n 2 => 'Kölsch',\n ),\n);\n";
$this->assertEquals($expected, $content);
}
@@ -147,8 +150,8 @@ class ConfigTest extends TestCase {
$this->assertSame('this_was_clearly_not_set_before', $config->getValue('foo', 'this_was_clearly_not_set_before'));
$content = file_get_contents($this->configFile);
- $expected = "<?php\n\$CONFIG = array (\n 'beers' => \n array (\n 0 => 'Appenzeller',\n " .
- " 1 => 'Guinness',\n 2 => 'Kölsch',\n ),\n 'alcohol_free' => false,\n);\n";
+ $expected = "<?php\n\$CONFIG = array (\n 'beers' => \n array (\n 0 => 'Appenzeller',\n "
+ . " 1 => 'Guinness',\n 2 => 'Kölsch',\n ),\n 'alcohol_free' => false,\n);\n";
$this->assertEquals($expected, $content);
}
@@ -159,7 +162,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'));
@@ -167,9 +170,9 @@ class ConfigTest extends TestCase {
// Write a new value to the config
$config->setValue('CoolWebsites', ['demo.owncloud.org', 'owncloud.org', 'owncloud.com']);
- $expected = "<?php\n\$CONFIG = array (\n 'foo' => 'bar',\n 'beers' => \n array (\n 0 => 'Appenzeller',\n " .
- " 1 => 'Guinness',\n 2 => 'Kölsch',\n ),\n 'alcohol_free' => false,\n 'php53' => 'totallyOutdated',\n 'CoolWebsites' => \n array (\n " .
- " 0 => 'demo.owncloud.org',\n 1 => 'owncloud.org',\n 2 => 'owncloud.com',\n ),\n);\n";
+ $expected = "<?php\n\$CONFIG = array (\n 'foo' => 'bar',\n 'beers' => \n array (\n 0 => 'Appenzeller',\n "
+ . " 1 => 'Guinness',\n 2 => 'Kölsch',\n ),\n 'alcohol_free' => false,\n 'php53' => 'totallyOutdated',\n 'CoolWebsites' => \n array (\n "
+ . " 0 => 'demo.owncloud.org',\n 1 => 'owncloud.org',\n 2 => 'owncloud.com',\n ),\n);\n";
$this->assertEquals($expected, file_get_contents($this->configFile));
// Cleanup
diff --git a/tests/lib/Contacts/ContactsMenu/Providers/LocalTimeProviderTest.php b/tests/lib/Contacts/ContactsMenu/Providers/LocalTimeProviderTest.php
index 7b1e6249832..cc53c0bcfcf 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);
@@ -110,9 +110,7 @@ class LocalTimeProviderTest extends TestCase {
];
}
- /**
- * @dataProvider dataTestProcess
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataTestProcess')]
public function testProcess(bool $hasCurrentUser, ?string $currentUserTZ, ?string $targetUserTZ, string $expected): void {
$entry = $this->createMock(IEntry::class);
$entry->expects($this->once())
diff --git a/tests/lib/ContactsManagerTest.php b/tests/lib/ContactsManagerTest.php
index 7586b063883..d2d46ce43b4 100644
--- a/tests/lib/ContactsManagerTest.php
+++ b/tests/lib/ContactsManagerTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -6,6 +7,8 @@
*/
namespace Test;
+use OC\ContactsManager;
+use OCP\Constants;
use OCP\IAddressBook;
class ContactsManagerTest extends \Test\TestCase {
@@ -14,10 +17,10 @@ class ContactsManagerTest extends \Test\TestCase {
protected function setUp(): void {
parent::setUp();
- $this->cm = new \OC\ContactsManager();
+ $this->cm = new ContactsManager();
}
- public function searchProvider() {
+ public static function searchProvider(): array {
$search1 = [
0 => [
'N' => [0 => '', 1 => 'Jan', 2 => 'Jansen', 3 => '', 4 => '',],
@@ -62,9 +65,7 @@ class ContactsManagerTest extends \Test\TestCase {
];
}
- /**
- * @dataProvider searchProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('searchProvider')]
public function testSearch($search1, $search2, $expectedResult): void {
/** @var \PHPUnit\Framework\MockObject\MockObject|IAddressBook $addressbook */
$addressbook1 = $this->getMockBuilder('\OCP\IAddressBookEnabled')
@@ -106,9 +107,7 @@ class ContactsManagerTest extends \Test\TestCase {
$this->assertEquals($expectedResult, $result);
}
- /**
- * @dataProvider searchProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('searchProvider')]
public function testSearchDisabledAb($search1): void {
/** @var \PHPUnit\Framework\MockObject\MockObject|IAddressBookEnabled $addressbook */
$addressbook1 = $this->getMockBuilder('\OCP\IAddressBookEnabled')
@@ -153,7 +152,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 +175,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 +215,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 +238,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..394428337f1 100644
--- a/tests/lib/DB/AdapterTest.php
+++ b/tests/lib/DB/AdapterTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
@@ -6,6 +7,8 @@
namespace Test\DB;
+use OCP\IDBConnection;
+use OCP\Server;
use Test\TestCase;
class AdapterTest extends TestCase {
@@ -13,8 +16,8 @@ class AdapterTest extends TestCase {
private $connection;
public function setUp(): void {
- $this->connection = \OC::$server->getDatabaseConnection();
- $this->appId = uniqid('test_db_adapter', true);
+ $this->connection = Server::get(IDBConnection::class);
+ $this->appId = substr(uniqid('test_db_adapter', true), 0, 32);
}
public function tearDown(): void {
diff --git a/tests/lib/DB/ConnectionFactoryTest.php b/tests/lib/DB/ConnectionFactoryTest.php
index 23bde34a8fb..d09a83ca856 100644
--- a/tests/lib/DB/ConnectionFactoryTest.php
+++ b/tests/lib/DB/ConnectionFactoryTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2018 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
@@ -12,7 +13,7 @@ use OCP\ICacheFactory;
use Test\TestCase;
class ConnectionFactoryTest extends TestCase {
- public function splitHostFromPortAndSocketData() {
+ public static function splitHostFromPortAndSocketData(): array {
return [
['127.0.0.1', ['host' => '127.0.0.1']],
['db.example.org', ['host' => 'db.example.org']],
@@ -27,10 +28,10 @@ class ConnectionFactoryTest extends TestCase {
}
/**
- * @dataProvider splitHostFromPortAndSocketData
* @param string $host
* @param array $expected
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('splitHostFromPortAndSocketData')]
public function testSplitHostFromPortAndSocket($host, array $expected): void {
/** @var SystemConfig $config */
$config = $this->createMock(SystemConfig::class);
diff --git a/tests/lib/DB/Exception/DbalExceptionTest.php b/tests/lib/DB/Exception/DbalExceptionTest.php
index 470beff9080..eac74291749 100644
--- a/tests/lib/DB/Exception/DbalExceptionTest.php
+++ b/tests/lib/DB/Exception/DbalExceptionTest.php
@@ -35,16 +35,16 @@ class DbalExceptionTest extends \Test\TestCase {
}
/**
- * @dataProvider dataDriverException
* @param string $class
* @param int $reason
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataDriverException')]
public function testDriverException(string $class, int $reason): void {
$result = DbalException::wrap(new $class($this->driverException, null));
$this->assertSame($reason, $result->getReason());
}
- public function dataDriverException(): array {
+ public static function dataDriverException(): array {
return [
[LockWaitTimeoutException::class, DbalException::REASON_LOCK_WAIT_TIMEOUT],
[ForeignKeyConstraintViolationException::class, DbalException::REASON_FOREIGN_KEY_VIOLATION],
diff --git a/tests/lib/DB/MigrationsTest.php b/tests/lib/DB/MigrationsTest.php
index 57ffb91e37e..2b39b26d852 100644
--- a/tests/lib/DB/MigrationsTest.php
+++ b/tests/lib/DB/MigrationsTest.php
@@ -175,7 +175,7 @@ class MigrationsTest extends \Test\TestCase {
$this->migrationService->executeStep('20170130180000');
}
- public function dataGetMigration() {
+ public static function dataGetMigration(): array {
return [
['current', '20170130180001'],
['prev', '20170130180000'],
@@ -185,10 +185,10 @@ class MigrationsTest extends \Test\TestCase {
}
/**
- * @dataProvider dataGetMigration
* @param string $alias
* @param string $expected
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataGetMigration')]
public function testGetMigration($alias, $expected): void {
$this->migrationService = $this->getMockBuilder(MigrationService::class)
->onlyMethods(['getMigratedVersions', 'findMigrations'])
@@ -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());
});
@@ -844,11 +844,10 @@ class MigrationsTest extends \Test\TestCase {
'class' => 'OCP\\Migration\\Attributes\\CreateTable',
'table' => 'new_table',
'description' => 'Table is used to store things, but also to get more things',
- 'notes' =>
- [
- 'this is a notice',
- 'and another one, if really needed'
- ],
+ 'notes' => [
+ 'this is a notice',
+ 'and another one, if really needed'
+ ],
'columns' => []
],
[
diff --git a/tests/lib/DB/MigratorTest.php b/tests/lib/DB/MigratorTest.php
index c6afe5a053a..9d8ee6791a9 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) {
@@ -261,7 +263,7 @@ class MigratorTest extends \Test\TestCase {
$this->assertTrue($startSchema->getTable($this->tableNameTmp)->hasForeignKey($fkName));
}
- public function dataNotNullEmptyValuesFailOracle(): array {
+ public static function dataNotNullEmptyValuesFailOracle(): array {
return [
[ParameterType::BOOLEAN, true, Types::BOOLEAN, false],
[ParameterType::BOOLEAN, false, Types::BOOLEAN, true],
@@ -277,13 +279,13 @@ class MigratorTest extends \Test\TestCase {
}
/**
- * @dataProvider dataNotNullEmptyValuesFailOracle
*
* @param int $parameterType
* @param bool|int|string $value
* @param string $columnType
* @param bool $oracleThrows
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataNotNullEmptyValuesFailOracle')]
public function testNotNullEmptyValuesFailOracle(int $parameterType, $value, string $columnType, bool $oracleThrows): void {
$startSchema = new Schema([], [], $this->getSchemaConfig());
$table = $startSchema->createTable($this->tableName);
diff --git a/tests/lib/DB/OCPostgreSqlPlatformTest.php b/tests/lib/DB/OCPostgreSqlPlatformTest.php
index bea3adf29a4..af17b01fc13 100644
--- a/tests/lib/DB/OCPostgreSqlPlatformTest.php
+++ b/tests/lib/DB/OCPostgreSqlPlatformTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2017-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2017 ownCloud, Inc.
diff --git a/tests/lib/DB/QueryBuilder/ExpressionBuilderDBTest.php b/tests/lib/DB/QueryBuilder/ExpressionBuilderDBTest.php
index 392fe9ff937..153993f396e 100644
--- a/tests/lib/DB/QueryBuilder/ExpressionBuilderDBTest.php
+++ b/tests/lib/DB/QueryBuilder/ExpressionBuilderDBTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2017 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
@@ -11,6 +12,7 @@ use OC\DB\QueryBuilder\Literal;
use OCP\DB\QueryBuilder\IQueryBuilder;
use OCP\DB\Types;
use OCP\IConfig;
+use OCP\IDBConnection;
use OCP\Server;
use Test\TestCase;
@@ -18,19 +20,19 @@ use Test\TestCase;
* @group DB
*/
class ExpressionBuilderDBTest extends TestCase {
- /** @var \Doctrine\DBAL\Connection|\OCP\IDBConnection */
+ /** @var \Doctrine\DBAL\Connection|IDBConnection */
protected $connection;
protected $schemaSetup = false;
protected function setUp(): void {
parent::setUp();
- $this->connection = \OC::$server->getDatabaseConnection();
+ $this->connection = Server::get(IDBConnection::class);
$this->prepareTestingTable();
}
- public function likeProvider() {
- $connection = \OC::$server->getDatabaseConnection();
+ public static function likeProvider(): array {
+ $connection = Server::get(IDBConnection::class);
return [
['foo', 'bar', false],
@@ -46,12 +48,12 @@ class ExpressionBuilderDBTest extends TestCase {
}
/**
- * @dataProvider likeProvider
*
* @param string $param1
* @param string $param2
* @param boolean $match
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('likeProvider')]
public function testLike($param1, $param2, $match): void {
$query = $this->connection->getQueryBuilder();
@@ -65,8 +67,8 @@ class ExpressionBuilderDBTest extends TestCase {
$this->assertEquals($match, $column);
}
- public function ilikeProvider() {
- $connection = \OC::$server->getDatabaseConnection();
+ public static function ilikeProvider(): array {
+ $connection = Server::get(IDBConnection::class);
return [
['foo', 'bar', false],
@@ -83,12 +85,12 @@ class ExpressionBuilderDBTest extends TestCase {
}
/**
- * @dataProvider ilikeProvider
*
* @param string $param1
* @param string $param2
* @param boolean $match
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('ilikeProvider')]
public function testILike($param1, $param2, $match): void {
$query = $this->connection->getQueryBuilder();
diff --git a/tests/lib/DB/QueryBuilder/ExpressionBuilderTest.php b/tests/lib/DB/QueryBuilder/ExpressionBuilderTest.php
index c14c55e6d02..1f84ebfbec1 100644
--- a/tests/lib/DB/QueryBuilder/ExpressionBuilderTest.php
+++ b/tests/lib/DB/QueryBuilder/ExpressionBuilderTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -10,6 +11,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;
@@ -27,7 +30,7 @@ class ExpressionBuilderTest extends TestCase {
/** @var DoctrineExpressionBuilder */
protected $doctrineExpressionBuilder;
- /** @var \OCP\IDBConnection */
+ /** @var IDBConnection */
protected $connection;
/** @var \Doctrine\DBAL\Connection */
@@ -39,8 +42,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);
@@ -50,8 +53,8 @@ class ExpressionBuilderTest extends TestCase {
$this->doctrineExpressionBuilder = new DoctrineExpressionBuilder($this->internalConnection);
}
- public function dataComparison() {
- $valueSets = $this->dataComparisons();
+ public static function dataComparison(): array {
+ $valueSets = self::dataComparisons();
$comparisonOperators = ['=', '<>', '<', '>', '<=', '>='];
$testSets = [];
@@ -64,7 +67,6 @@ class ExpressionBuilderTest extends TestCase {
}
/**
- * @dataProvider dataComparison
*
* @param string $comparison
* @param mixed $input1
@@ -72,6 +74,7 @@ class ExpressionBuilderTest extends TestCase {
* @param mixed $input2
* @param bool $isInput2Literal
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataComparison')]
public function testComparison($comparison, $input1, $isInput1Literal, $input2, $isInput2Literal): void {
[$doctrineInput1, $ocInput1] = $this->helpWithLiteral($input1, $isInput1Literal);
[$doctrineInput2, $ocInput2] = $this->helpWithLiteral($input2, $isInput2Literal);
@@ -82,7 +85,7 @@ class ExpressionBuilderTest extends TestCase {
);
}
- public function dataComparisons() {
+ public static function dataComparisons(): array {
return [
['value', false, 'value', false],
['value', false, 'value', true],
@@ -92,13 +95,13 @@ class ExpressionBuilderTest extends TestCase {
}
/**
- * @dataProvider dataComparisons
*
* @param mixed $input1
* @param bool $isInput1Literal
* @param mixed $input2
* @param bool $isInput2Literal
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataComparisons')]
public function testEquals($input1, $isInput1Literal, $input2, $isInput2Literal): void {
[$doctrineInput1, $ocInput1] = $this->helpWithLiteral($input1, $isInput1Literal);
[$doctrineInput2, $ocInput2] = $this->helpWithLiteral($input2, $isInput2Literal);
@@ -110,13 +113,13 @@ class ExpressionBuilderTest extends TestCase {
}
/**
- * @dataProvider dataComparisons
*
* @param mixed $input1
* @param bool $isInput1Literal
* @param mixed $input2
* @param bool $isInput2Literal
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataComparisons')]
public function testNotEquals($input1, $isInput1Literal, $input2, $isInput2Literal): void {
[$doctrineInput1, $ocInput1] = $this->helpWithLiteral($input1, $isInput1Literal);
[$doctrineInput2, $ocInput2] = $this->helpWithLiteral($input2, $isInput2Literal);
@@ -128,13 +131,13 @@ class ExpressionBuilderTest extends TestCase {
}
/**
- * @dataProvider dataComparisons
*
* @param mixed $input1
* @param bool $isInput1Literal
* @param mixed $input2
* @param bool $isInput2Literal
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataComparisons')]
public function testLowerThan($input1, $isInput1Literal, $input2, $isInput2Literal): void {
[$doctrineInput1, $ocInput1] = $this->helpWithLiteral($input1, $isInput1Literal);
[$doctrineInput2, $ocInput2] = $this->helpWithLiteral($input2, $isInput2Literal);
@@ -146,13 +149,13 @@ class ExpressionBuilderTest extends TestCase {
}
/**
- * @dataProvider dataComparisons
*
* @param mixed $input1
* @param bool $isInput1Literal
* @param mixed $input2
* @param bool $isInput2Literal
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataComparisons')]
public function testLowerThanEquals($input1, $isInput1Literal, $input2, $isInput2Literal): void {
[$doctrineInput1, $ocInput1] = $this->helpWithLiteral($input1, $isInput1Literal);
[$doctrineInput2, $ocInput2] = $this->helpWithLiteral($input2, $isInput2Literal);
@@ -164,13 +167,13 @@ class ExpressionBuilderTest extends TestCase {
}
/**
- * @dataProvider dataComparisons
*
* @param mixed $input1
* @param bool $isInput1Literal
* @param mixed $input2
* @param bool $isInput2Literal
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataComparisons')]
public function testGreaterThan($input1, $isInput1Literal, $input2, $isInput2Literal): void {
[$doctrineInput1, $ocInput1] = $this->helpWithLiteral($input1, $isInput1Literal);
[$doctrineInput2, $ocInput2] = $this->helpWithLiteral($input2, $isInput2Literal);
@@ -182,13 +185,13 @@ class ExpressionBuilderTest extends TestCase {
}
/**
- * @dataProvider dataComparisons
*
* @param mixed $input1
* @param bool $isInput1Literal
* @param mixed $input2
* @param bool $isInput2Literal
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataComparisons')]
public function testGreaterThanEquals($input1, $isInput1Literal, $input2, $isInput2Literal): void {
[$doctrineInput1, $ocInput1] = $this->helpWithLiteral($input1, $isInput1Literal);
[$doctrineInput2, $ocInput2] = $this->helpWithLiteral($input2, $isInput2Literal);
@@ -213,7 +216,7 @@ class ExpressionBuilderTest extends TestCase {
);
}
- public function dataLike() {
+ public static function dataLike(): array {
return [
['value', false],
['value', true],
@@ -221,11 +224,11 @@ class ExpressionBuilderTest extends TestCase {
}
/**
- * @dataProvider dataLike
*
* @param mixed $input
* @param bool $isLiteral
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataLike')]
public function testLike($input, $isLiteral): void {
[$doctrineInput, $ocInput] = $this->helpWithLiteral($input, $isLiteral);
@@ -236,11 +239,11 @@ class ExpressionBuilderTest extends TestCase {
}
/**
- * @dataProvider dataLike
*
* @param mixed $input
* @param bool $isLiteral
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataLike')]
public function testNotLike($input, $isLiteral): void {
[$doctrineInput, $ocInput] = $this->helpWithLiteral($input, $isLiteral);
@@ -250,7 +253,7 @@ class ExpressionBuilderTest extends TestCase {
);
}
- public function dataIn() {
+ public static function dataIn(): array {
return [
['value', false],
['value', true],
@@ -260,11 +263,11 @@ class ExpressionBuilderTest extends TestCase {
}
/**
- * @dataProvider dataIn
*
* @param mixed $input
* @param bool $isLiteral
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataIn')]
public function testIn($input, $isLiteral): void {
[$doctrineInput, $ocInput] = $this->helpWithLiteral($input, $isLiteral);
@@ -275,11 +278,11 @@ class ExpressionBuilderTest extends TestCase {
}
/**
- * @dataProvider dataIn
*
* @param mixed $input
* @param bool $isLiteral
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataIn')]
public function testNotIn($input, $isLiteral): void {
[$doctrineInput, $ocInput] = $this->helpWithLiteral($input, $isLiteral);
@@ -317,7 +320,7 @@ class ExpressionBuilderTest extends TestCase {
return [$doctrineInput, $ocInput];
}
- public function dataLiteral() {
+ public static function dataLiteral(): array {
return [
['value', null],
['1', null],
@@ -329,11 +332,11 @@ class ExpressionBuilderTest extends TestCase {
}
/**
- * @dataProvider dataLiteral
*
* @param mixed $input
* @param string|null $type
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataLiteral')]
public function testLiteral($input, $type): void {
/** @var \OC\DB\QueryBuilder\Literal $actual */
$actual = $this->expressionBuilder->literal($input, $type);
@@ -345,7 +348,7 @@ class ExpressionBuilderTest extends TestCase {
);
}
- public function dataClobComparisons() {
+ public static function dataClobComparisons(): array {
return [
['eq', '5', IQueryBuilder::PARAM_STR, false, 3],
['eq', '5', IQueryBuilder::PARAM_STR, true, 1],
@@ -373,13 +376,13 @@ class ExpressionBuilderTest extends TestCase {
}
/**
- * @dataProvider dataClobComparisons
* @param string $function
* @param mixed $value
* @param mixed $type
* @param bool $compareKeyToValue
* @param int $expected
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataClobComparisons')]
public function testClobComparisons($function, $value, $type, $compareKeyToValue, $expected): void {
$appId = $this->getUniqueID('testing');
$this->createConfig($appId, 1, 4);
diff --git a/tests/lib/DB/QueryBuilder/FunctionBuilderTest.php b/tests/lib/DB/QueryBuilder/FunctionBuilderTest.php
index f3007ace85c..fc20af8a841 100644
--- a/tests/lib/DB/QueryBuilder/FunctionBuilderTest.php
+++ b/tests/lib/DB/QueryBuilder/FunctionBuilderTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2017 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-only
@@ -8,6 +9,8 @@ namespace Test\DB\QueryBuilder;
use OC\DB\QueryBuilder\Literal;
use OCP\DB\QueryBuilder\IQueryBuilder;
+use OCP\IDBConnection;
+use OCP\Server;
use Test\TestCase;
/**
@@ -18,18 +21,16 @@ use Test\TestCase;
* @package Test\DB\QueryBuilder
*/
class FunctionBuilderTest extends TestCase {
- /** @var \Doctrine\DBAL\Connection|\OCP\IDBConnection */
+ /** @var \Doctrine\DBAL\Connection|IDBConnection */
protected $connection;
protected function setUp(): void {
parent::setUp();
- $this->connection = \OC::$server->getDatabaseConnection();
+ $this->connection = Server::get(IDBConnection::class);
}
- /**
- * @dataProvider providerTestConcatString
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('providerTestConcatString')]
public function testConcatString($closure): void {
$query = $this->connection->getQueryBuilder();
[$real, $arguments, $return] = $closure($query);
@@ -49,38 +50,38 @@ class FunctionBuilderTest extends TestCase {
$this->assertEquals($return, $column);
}
- public function providerTestConcatString(): array {
+ public static function providerTestConcatString(): array {
return [
- '1 column: string param unicode' =>
- [function ($q) {
+ '1 column: string param unicode'
+ => [function ($q) {
return [false, [$q->createNamedParameter('👍')], '👍'];
}],
- '2 columns: string param and string param' =>
- [function ($q) {
+ '2 columns: string param and string param'
+ => [function ($q) {
return [false, [$q->createNamedParameter('foo'), $q->createNamedParameter('bar')], 'foobar'];
}],
- '2 columns: string param and int literal' =>
- [function ($q) {
+ '2 columns: string param and int literal'
+ => [function ($q) {
return [false, [$q->createNamedParameter('foo'), $q->expr()->literal(1)], 'foo1'];
}],
- '2 columns: string param and string literal' =>
- [function ($q) {
+ '2 columns: string param and string literal'
+ => [function ($q) {
return [false, [$q->createNamedParameter('foo'), $q->expr()->literal('bar')], 'foobar'];
}],
- '2 columns: string real and int literal' =>
- [function ($q) {
+ '2 columns: string real and int literal'
+ => [function ($q) {
return [true, ['configkey', $q->expr()->literal(2)], '12'];
}],
- '4 columns: string literal' =>
- [function ($q) {
+ '4 columns: string literal'
+ => [function ($q) {
return [false, [$q->expr()->literal('foo'), $q->expr()->literal('bar'), $q->expr()->literal('foo'), $q->expr()->literal('bar')], 'foobarfoobar'];
}],
- '4 columns: int literal' =>
- [function ($q) {
+ '4 columns: int literal'
+ => [function ($q) {
return [false, [$q->expr()->literal(1), $q->expr()->literal(2), $q->expr()->literal(3), $q->expr()->literal(4)], '1234'];
}],
- '5 columns: string param with special chars used in the function' =>
- [function ($q) {
+ '5 columns: string param with special chars used in the function'
+ => [function ($q) {
return [false, [$q->createNamedParameter('b'), $q->createNamedParameter("'"), $q->createNamedParameter('||'), $q->createNamedParameter(','), $q->createNamedParameter('a')], "b'||,a"];
}],
];
@@ -323,7 +324,7 @@ class FunctionBuilderTest extends TestCase {
$this->assertGreaterThan(1, $column);
}
- public function octetLengthProvider() {
+ public static function octetLengthProvider(): array {
return [
['', 0],
['foobar', 6],
@@ -332,9 +333,7 @@ class FunctionBuilderTest extends TestCase {
];
}
- /**
- * @dataProvider octetLengthProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('octetLengthProvider')]
public function testOctetLength(string $str, int $bytes): void {
$query = $this->connection->getQueryBuilder();
@@ -348,7 +347,7 @@ class FunctionBuilderTest extends TestCase {
$this->assertEquals($bytes, $column);
}
- public function charLengthProvider() {
+ public static function charLengthProvider(): array {
return [
['', 0],
['foobar', 6],
@@ -357,9 +356,7 @@ class FunctionBuilderTest extends TestCase {
];
}
- /**
- * @dataProvider charLengthProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('charLengthProvider')]
public function testCharLength(string $str, int $bytes): void {
$query = $this->connection->getQueryBuilder();
diff --git a/tests/lib/DB/QueryBuilder/Partitioned/JoinConditionTest.php b/tests/lib/DB/QueryBuilder/Partitioned/JoinConditionTest.php
index a8ebf11c2c2..8f84d6a0d2c 100644
--- a/tests/lib/DB/QueryBuilder/Partitioned/JoinConditionTest.php
+++ b/tests/lib/DB/QueryBuilder/Partitioned/JoinConditionTest.php
@@ -22,7 +22,7 @@ class JoinConditionTest extends TestCase {
parent::setUp();
}
- public function platformProvider(): array {
+ public static function platformProvider(): array {
return [
[IDBConnection::PLATFORM_SQLITE],
[IDBConnection::PLATFORM_POSTGRES],
@@ -41,9 +41,7 @@ class JoinConditionTest extends TestCase {
);
}
- /**
- * @dataProvider platformProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('platformProvider')]
public function testParseCondition(string $platform): void {
$query = $this->getBuilder($platform);
$param1 = $query->createNamedParameter('files');
@@ -63,9 +61,7 @@ class JoinConditionTest extends TestCase {
], $parsed->toConditions);
}
- /**
- * @dataProvider platformProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('platformProvider')]
public function testParseCastCondition(string $platform): void {
$query = $this->getBuilder($platform);
diff --git a/tests/lib/DB/QueryBuilder/Partitioned/PartitionedQueryBuilderTest.php b/tests/lib/DB/QueryBuilder/Partitioned/PartitionedQueryBuilderTest.php
index 697b3ab92c9..f99adc73aa8 100644
--- a/tests/lib/DB/QueryBuilder/Partitioned/PartitionedQueryBuilderTest.php
+++ b/tests/lib/DB/QueryBuilder/Partitioned/PartitionedQueryBuilderTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
diff --git a/tests/lib/DB/QueryBuilder/QueryBuilderTest.php b/tests/lib/DB/QueryBuilder/QueryBuilderTest.php
index 508748f13b2..990191a9ff5 100644
--- a/tests/lib/DB/QueryBuilder/QueryBuilderTest.php
+++ b/tests/lib/DB/QueryBuilder/QueryBuilderTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -17,6 +18,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 +44,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);
@@ -88,7 +90,7 @@ class QueryBuilderTest extends \Test\TestCase {
->execute();
}
- public function dataFirstResult() {
+ public static function dataFirstResult(): array {
return [
[0, [99, 98, 97, 96, 95, 94, 93, 92, 91]],
[0, [99, 98, 97, 96, 95, 94, 93, 92, 91]],
@@ -98,11 +100,11 @@ class QueryBuilderTest extends \Test\TestCase {
}
/**
- * @dataProvider dataFirstResult
*
* @param int|null $firstResult
* @param array $expectedSet
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataFirstResult')]
public function testFirstResult($firstResult, $expectedSet): void {
$this->deleteTestingRows();
$this->createTestingRows();
@@ -124,7 +126,7 @@ class QueryBuilderTest extends \Test\TestCase {
$this->deleteTestingRows();
}
- public function dataMaxResults() {
+ public static function dataMaxResults(): array {
return [
[null, [99, 98, 97, 96, 95, 94, 93, 92, 91]],
// Limit 0 gives mixed results: either all entries or none is returned
@@ -135,11 +137,11 @@ class QueryBuilderTest extends \Test\TestCase {
}
/**
- * @dataProvider dataMaxResults
*
* @param int $maxResult
* @param array $expectedSet
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataMaxResults')]
public function testMaxResults($maxResult, $expectedSet): void {
$this->deleteTestingRows();
$this->createTestingRows();
@@ -161,10 +163,10 @@ class QueryBuilderTest extends \Test\TestCase {
$this->deleteTestingRows();
}
- public function dataSelect() {
+ 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']],
@@ -187,12 +189,12 @@ class QueryBuilderTest extends \Test\TestCase {
}
/**
- * @dataProvider dataSelect
*
* @param array $selectArguments
* @param array $expected
* @param string $expectedLiteral
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataSelect')]
public function testSelect($selectArguments, $expected, $expectedLiteral = ''): void {
$this->deleteTestingRows();
$this->createTestingRows();
@@ -229,10 +231,10 @@ class QueryBuilderTest extends \Test\TestCase {
$this->deleteTestingRows();
}
- public function dataSelectAlias() {
+ 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']],
@@ -240,12 +242,12 @@ class QueryBuilderTest extends \Test\TestCase {
}
/**
- * @dataProvider dataSelectAlias
*
* @param mixed $select
* @param array $alias
* @param array $expected
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataSelectAlias')]
public function testSelectAlias($select, $alias, $expected): void {
$this->deleteTestingRows();
$this->createTestingRows();
@@ -338,10 +340,10 @@ class QueryBuilderTest extends \Test\TestCase {
$this->deleteTestingRows('testFirstResult2');
}
- public function dataAddSelect() {
+ 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']],
@@ -364,12 +366,12 @@ class QueryBuilderTest extends \Test\TestCase {
}
/**
- * @dataProvider dataAddSelect
*
* @param array $selectArguments
* @param array $expected
* @param string $expectedLiteral
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataAddSelect')]
public function testAddSelect($selectArguments, $expected, $expectedLiteral = ''): void {
$this->deleteTestingRows();
$this->createTestingRows();
@@ -408,7 +410,7 @@ class QueryBuilderTest extends \Test\TestCase {
$this->deleteTestingRows();
}
- public function dataDelete() {
+ public static function dataDelete(): array {
return [
['data', null, ['table' => '`*PREFIX*data`', 'alias' => null], '`*PREFIX*data`'],
['data', 't', ['table' => '`*PREFIX*data`', 'alias' => 't'], '`*PREFIX*data` t'],
@@ -416,13 +418,13 @@ class QueryBuilderTest extends \Test\TestCase {
}
/**
- * @dataProvider dataDelete
*
* @param string $tableName
* @param string $tableAlias
* @param array $expectedQueryPart
* @param string $expectedQuery
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataDelete')]
public function testDelete($tableName, $tableAlias, $expectedQueryPart, $expectedQuery): void {
$this->queryBuilder->delete($tableName, $tableAlias);
@@ -437,7 +439,7 @@ class QueryBuilderTest extends \Test\TestCase {
);
}
- public function dataUpdate() {
+ public static function dataUpdate(): array {
return [
['data', null, ['table' => '`*PREFIX*data`', 'alias' => null], '`*PREFIX*data`'],
['data', 't', ['table' => '`*PREFIX*data`', 'alias' => 't'], '`*PREFIX*data` t'],
@@ -445,13 +447,13 @@ class QueryBuilderTest extends \Test\TestCase {
}
/**
- * @dataProvider dataUpdate
*
* @param string $tableName
* @param string $tableAlias
* @param array $expectedQueryPart
* @param string $expectedQuery
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataUpdate')]
public function testUpdate($tableName, $tableAlias, $expectedQueryPart, $expectedQuery): void {
$this->queryBuilder->update($tableName, $tableAlias);
@@ -466,19 +468,19 @@ class QueryBuilderTest extends \Test\TestCase {
);
}
- public function dataInsert() {
+ public static function dataInsert(): array {
return [
['data', ['table' => '`*PREFIX*data`'], '`*PREFIX*data`'],
];
}
/**
- * @dataProvider dataInsert
*
* @param string $tableName
* @param array $expectedQueryPart
* @param string $expectedQuery
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataInsert')]
public function testInsert($tableName, $expectedQueryPart, $expectedQuery): void {
$this->queryBuilder->insert($tableName);
@@ -493,10 +495,10 @@ class QueryBuilderTest extends \Test\TestCase {
);
}
- public function dataFrom() {
+ 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`']
@@ -515,7 +517,6 @@ class QueryBuilderTest extends \Test\TestCase {
}
/**
- * @dataProvider dataFrom
*
* @param string|IQueryFunction $table1Name
* @param string $table1Alias
@@ -524,6 +525,7 @@ class QueryBuilderTest extends \Test\TestCase {
* @param array $expectedQueryPart
* @param string $expectedQuery
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataFrom')]
public function testFrom($table1Name, $table1Alias, $table2Name, $table2Alias, $expectedQueryPart, $expectedQuery): void {
$this->queryBuilder->from($table1Name, $table1Alias);
if ($table2Name !== null) {
@@ -541,7 +543,7 @@ class QueryBuilderTest extends \Test\TestCase {
);
}
- public function dataJoin() {
+ public static function dataJoin(): array {
return [
[
'd1', 'data2', null, null,
@@ -563,7 +565,6 @@ class QueryBuilderTest extends \Test\TestCase {
}
/**
- * @dataProvider dataJoin
*
* @param string $fromAlias
* @param string $tableName
@@ -572,6 +573,7 @@ class QueryBuilderTest extends \Test\TestCase {
* @param array $expectedQueryPart
* @param string $expectedQuery
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataJoin')]
public function testJoin($fromAlias, $tableName, $tableAlias, $condition, $expectedQueryPart, $expectedQuery): void {
$this->queryBuilder->from('data1', 'd1');
$this->queryBuilder->join(
@@ -593,7 +595,6 @@ class QueryBuilderTest extends \Test\TestCase {
}
/**
- * @dataProvider dataJoin
*
* @param string $fromAlias
* @param string $tableName
@@ -602,6 +603,7 @@ class QueryBuilderTest extends \Test\TestCase {
* @param array $expectedQueryPart
* @param string $expectedQuery
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataJoin')]
public function testInnerJoin($fromAlias, $tableName, $tableAlias, $condition, $expectedQueryPart, $expectedQuery): void {
$this->queryBuilder->from('data1', 'd1');
$this->queryBuilder->innerJoin(
@@ -622,7 +624,7 @@ class QueryBuilderTest extends \Test\TestCase {
);
}
- public function dataLeftJoin() {
+ public static function dataLeftJoin(): array {
return [
[
'd1', 'data2', null, null,
@@ -643,7 +645,6 @@ class QueryBuilderTest extends \Test\TestCase {
}
/**
- * @dataProvider dataLeftJoin
*
* @param string $fromAlias
* @param string $tableName
@@ -652,6 +653,7 @@ class QueryBuilderTest extends \Test\TestCase {
* @param array $expectedQueryPart
* @param string $expectedQuery
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataLeftJoin')]
public function testLeftJoin($fromAlias, $tableName, $tableAlias, $condition, $expectedQueryPart, $expectedQuery): void {
$this->queryBuilder->from('data1', 'd1');
$this->queryBuilder->leftJoin(
@@ -672,7 +674,7 @@ class QueryBuilderTest extends \Test\TestCase {
);
}
- public function dataRightJoin() {
+ public static function dataRightJoin(): array {
return [
[
'd1', 'data2', null, null,
@@ -693,7 +695,6 @@ class QueryBuilderTest extends \Test\TestCase {
}
/**
- * @dataProvider dataRightJoin
*
* @param string $fromAlias
* @param string $tableName
@@ -702,6 +703,7 @@ class QueryBuilderTest extends \Test\TestCase {
* @param array $expectedQueryPart
* @param string $expectedQuery
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataRightJoin')]
public function testRightJoin($fromAlias, $tableName, $tableAlias, $condition, $expectedQueryPart, $expectedQuery): void {
$this->queryBuilder->from('data1', 'd1');
$this->queryBuilder->rightJoin(
@@ -722,7 +724,7 @@ class QueryBuilderTest extends \Test\TestCase {
);
}
- public function dataSet() {
+ public static function dataSet(): array {
return [
['column1', new Literal('value'), null, null, ['`column1` = value'], '`column1` = value'],
['column1', new Parameter(':param'), null, null, ['`column1` = :param'], '`column1` = :param'],
@@ -732,7 +734,6 @@ class QueryBuilderTest extends \Test\TestCase {
}
/**
- * @dataProvider dataSet
*
* @param string $partOne1
* @param string $partOne2
@@ -741,6 +742,7 @@ class QueryBuilderTest extends \Test\TestCase {
* @param array $expectedQueryPart
* @param string $expectedQuery
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataSet')]
public function testSet($partOne1, $partOne2, $partTwo1, $partTwo2, $expectedQueryPart, $expectedQuery): void {
$this->queryBuilder->update('data');
$this->queryBuilder->set($partOne1, $partOne2);
@@ -759,7 +761,7 @@ class QueryBuilderTest extends \Test\TestCase {
);
}
- public function dataWhere() {
+ public static function dataWhere(): array {
return [
[['where1'], new CompositeExpression('AND', ['where1']), 'where1'],
[['where1', 'where2'], new CompositeExpression('AND', ['where1', 'where2']), '(where1) AND (where2)'],
@@ -767,12 +769,12 @@ class QueryBuilderTest extends \Test\TestCase {
}
/**
- * @dataProvider dataWhere
*
* @param array $whereArguments
* @param array $expectedQueryPart
* @param string $expectedQuery
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataWhere')]
public function testWhere($whereArguments, $expectedQueryPart, $expectedQuery): void {
$this->queryBuilder->select('column');
call_user_func_array(
@@ -792,12 +794,12 @@ class QueryBuilderTest extends \Test\TestCase {
}
/**
- * @dataProvider dataWhere
*
* @param array $whereArguments
* @param array $expectedQueryPart
* @param string $expectedQuery
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataWhere')]
public function testAndWhere($whereArguments, $expectedQueryPart, $expectedQuery): void {
$this->queryBuilder->select('column');
call_user_func_array(
@@ -816,7 +818,7 @@ class QueryBuilderTest extends \Test\TestCase {
);
}
- public function dataOrWhere() {
+ public static function dataOrWhere(): array {
return [
[['where1'], new CompositeExpression('OR', ['where1']), 'where1'],
[['where1', 'where2'], new CompositeExpression('OR', ['where1', 'where2']), '(where1) OR (where2)'],
@@ -824,12 +826,12 @@ class QueryBuilderTest extends \Test\TestCase {
}
/**
- * @dataProvider dataOrWhere
*
* @param array $whereArguments
* @param array $expectedQueryPart
* @param string $expectedQuery
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataOrWhere')]
public function testOrWhere($whereArguments, $expectedQueryPart, $expectedQuery): void {
$this->queryBuilder->select('column');
call_user_func_array(
@@ -848,7 +850,7 @@ class QueryBuilderTest extends \Test\TestCase {
);
}
- public function dataGroupBy() {
+ public static function dataGroupBy(): array {
return [
[['column1'], ['`column1`'], '`column1`'],
[['column1', 'column2'], ['`column1`', '`column2`'], '`column1`, `column2`'],
@@ -856,12 +858,12 @@ class QueryBuilderTest extends \Test\TestCase {
}
/**
- * @dataProvider dataGroupBy
*
* @param array $groupByArguments
* @param array $expectedQueryPart
* @param string $expectedQuery
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataGroupBy')]
public function testGroupBy($groupByArguments, $expectedQueryPart, $expectedQuery): void {
$this->queryBuilder->select('column');
call_user_func_array(
@@ -880,7 +882,7 @@ class QueryBuilderTest extends \Test\TestCase {
);
}
- public function dataAddGroupBy() {
+ public static function dataAddGroupBy(): array {
return [
[['column2'], ['`column1`', '`column2`'], '`column1`, `column2`'],
[['column2', 'column3'], ['`column1`', '`column2`', '`column3`'], '`column1`, `column2`, `column3`'],
@@ -888,12 +890,12 @@ class QueryBuilderTest extends \Test\TestCase {
}
/**
- * @dataProvider dataAddGroupBy
*
* @param array $groupByArguments
* @param array $expectedQueryPart
* @param string $expectedQuery
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataAddGroupBy')]
public function testAddGroupBy($groupByArguments, $expectedQueryPart, $expectedQuery): void {
$this->queryBuilder->select('column');
$this->queryBuilder->groupBy('column1');
@@ -913,20 +915,20 @@ class QueryBuilderTest extends \Test\TestCase {
);
}
- public function dataSetValue() {
+ public static function dataSetValue(): array {
return [
['column', 'value', ['`column`' => 'value'], '(`column`) VALUES(value)'],
];
}
/**
- * @dataProvider dataSetValue
*
* @param string $column
* @param string $value
* @param array $expectedQueryPart
* @param string $expectedQuery
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataSetValue')]
public function testSetValue($column, $value, $expectedQueryPart, $expectedQuery): void {
$this->queryBuilder->insert('data');
$this->queryBuilder->setValue($column, $value);
@@ -943,13 +945,13 @@ class QueryBuilderTest extends \Test\TestCase {
}
/**
- * @dataProvider dataSetValue
*
* @param string $column
* @param string $value
* @param array $expectedQueryPart
* @param string $expectedQuery
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataSetValue')]
public function testValues($column, $value, $expectedQueryPart, $expectedQuery): void {
$this->queryBuilder->insert('data');
$this->queryBuilder->values([
@@ -967,7 +969,7 @@ class QueryBuilderTest extends \Test\TestCase {
);
}
- public function dataHaving() {
+ public static function dataHaving(): array {
return [
[['condition1'], new CompositeExpression('AND', ['condition1']), 'HAVING condition1'],
[['condition1', 'condition2'], new CompositeExpression('AND', ['condition1', 'condition2']), 'HAVING (condition1) AND (condition2)'],
@@ -985,12 +987,12 @@ class QueryBuilderTest extends \Test\TestCase {
}
/**
- * @dataProvider dataHaving
*
* @param array $havingArguments
* @param array $expectedQueryPart
* @param string $expectedQuery
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataHaving')]
public function testHaving($havingArguments, $expectedQueryPart, $expectedQuery): void {
call_user_func_array(
[$this->queryBuilder, 'having'],
@@ -1008,7 +1010,7 @@ class QueryBuilderTest extends \Test\TestCase {
);
}
- public function dataAndHaving() {
+ public static function dataAndHaving(): array {
return [
[['condition2'], new CompositeExpression('AND', ['condition1', 'condition2']), 'HAVING (condition1) AND (condition2)'],
[['condition2', 'condition3'], new CompositeExpression('AND', ['condition1', 'condition2', 'condition3']), 'HAVING (condition1) AND (condition2) AND (condition3)'],
@@ -1026,12 +1028,12 @@ class QueryBuilderTest extends \Test\TestCase {
}
/**
- * @dataProvider dataAndHaving
*
* @param array $havingArguments
* @param array $expectedQueryPart
* @param string $expectedQuery
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataAndHaving')]
public function testAndHaving($havingArguments, $expectedQueryPart, $expectedQuery): void {
$this->queryBuilder->having('condition1');
call_user_func_array(
@@ -1050,7 +1052,7 @@ class QueryBuilderTest extends \Test\TestCase {
);
}
- public function dataOrHaving() {
+ public static function dataOrHaving(): array {
return [
[['condition2'], new CompositeExpression('OR', ['condition1', 'condition2']), 'HAVING (condition1) OR (condition2)'],
[['condition2', 'condition3'], new CompositeExpression('OR', ['condition1', 'condition2', 'condition3']), 'HAVING (condition1) OR (condition2) OR (condition3)'],
@@ -1068,12 +1070,12 @@ class QueryBuilderTest extends \Test\TestCase {
}
/**
- * @dataProvider dataOrHaving
*
* @param array $havingArguments
* @param array $expectedQueryPart
* @param string $expectedQuery
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataOrHaving')]
public function testOrHaving($havingArguments, $expectedQueryPart, $expectedQuery): void {
$this->queryBuilder->having('condition1');
call_user_func_array(
@@ -1092,7 +1094,7 @@ class QueryBuilderTest extends \Test\TestCase {
);
}
- public function dataOrderBy() {
+ public static function dataOrderBy(): array {
return [
['column', null, ['`column` ASC'], 'ORDER BY `column` ASC'],
['column', 'ASC', ['`column` ASC'], 'ORDER BY `column` ASC'],
@@ -1101,13 +1103,13 @@ class QueryBuilderTest extends \Test\TestCase {
}
/**
- * @dataProvider dataOrderBy
*
* @param string $sort
* @param string $order
* @param array $expectedQueryPart
* @param string $expectedQuery
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataOrderBy')]
public function testOrderBy($sort, $order, $expectedQueryPart, $expectedQuery): void {
$this->queryBuilder->orderBy($sort, $order);
@@ -1122,7 +1124,7 @@ class QueryBuilderTest extends \Test\TestCase {
);
}
- public function dataAddOrderBy() {
+ public static function dataAddOrderBy(): array {
return [
['column2', null, null, ['`column1` ASC', '`column2` ASC'], 'ORDER BY `column1` ASC, `column2` ASC'],
['column2', null, 'ASC', ['`column1` ASC', '`column2` ASC'], 'ORDER BY `column1` ASC, `column2` ASC'],
@@ -1137,7 +1139,6 @@ class QueryBuilderTest extends \Test\TestCase {
}
/**
- * @dataProvider dataAddOrderBy
*
* @param string $sort2
* @param string $order2
@@ -1145,6 +1146,7 @@ class QueryBuilderTest extends \Test\TestCase {
* @param array $expectedQueryPart
* @param string $expectedQuery
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataAddOrderBy')]
public function testAddOrderBy($sort2, $order2, $order1, $expectedQueryPart, $expectedQuery): void {
$this->queryBuilder->orderBy('column1', $order1);
$this->queryBuilder->addOrderBy($sort2, $order2);
@@ -1197,10 +1199,10 @@ class QueryBuilderTest extends \Test\TestCase {
}
}
- public function dataGetTableName() {
+ 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`'],
@@ -1217,12 +1219,12 @@ class QueryBuilderTest extends \Test\TestCase {
}
/**
- * @dataProvider dataGetTableName
*
* @param string|IQueryFunction $tableName
* @param bool $automatic
* @param string $expected
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataGetTableName')]
public function testGetTableName($tableName, $automatic, $expected): void {
if ($automatic !== null) {
$this->queryBuilder->automaticTablePrefix($automatic);
@@ -1234,7 +1236,7 @@ class QueryBuilderTest extends \Test\TestCase {
);
}
- public function dataGetColumnName() {
+ public static function dataGetColumnName(): array {
return [
['column', '', '`column`'],
['column', 'a', '`a`.`column`'],
@@ -1242,11 +1244,11 @@ class QueryBuilderTest extends \Test\TestCase {
}
/**
- * @dataProvider dataGetColumnName
* @param string $column
* @param string $prefix
* @param string $expected
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataGetColumnName')]
public function testGetColumnName($column, $prefix, $expected): void {
$this->assertSame(
$expected,
@@ -1427,7 +1429,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 +1464,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/DB/QueryBuilder/QuoteHelperTest.php b/tests/lib/DB/QueryBuilder/QuoteHelperTest.php
index 3c2e33c28ea..6efb55708a1 100644
--- a/tests/lib/DB/QueryBuilder/QuoteHelperTest.php
+++ b/tests/lib/DB/QueryBuilder/QuoteHelperTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2017-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -23,7 +24,7 @@ class QuoteHelperTest extends \Test\TestCase {
$this->helper = new QuoteHelper();
}
- public function dataQuoteColumnName() {
+ public static function dataQuoteColumnName(): array {
return [
['column', '`column`'],
[new Literal('literal'), 'literal'],
@@ -37,10 +38,10 @@ class QuoteHelperTest extends \Test\TestCase {
}
/**
- * @dataProvider dataQuoteColumnName
* @param mixed $input
* @param string $expected
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataQuoteColumnName')]
public function testQuoteColumnName($input, $expected): void {
$this->assertSame(
$expected,
@@ -48,7 +49,7 @@ class QuoteHelperTest extends \Test\TestCase {
);
}
- public function dataQuoteColumnNames() {
+ public static function dataQuoteColumnNames(): array {
return [
// Single case
['d.column', '`d`.`column`'],
@@ -72,10 +73,10 @@ class QuoteHelperTest extends \Test\TestCase {
}
/**
- * @dataProvider dataQuoteColumnNames
* @param mixed $input
* @param string $expected
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataQuoteColumnNames')]
public function testQuoteColumnNames($input, $expected): void {
$this->assertSame(
$expected,
diff --git a/tests/lib/DateTimeFormatterTest.php b/tests/lib/DateTimeFormatterTest.php
index 924cac9d399..dce6692f9cb 100644
--- a/tests/lib/DateTimeFormatterTest.php
+++ b/tests/lib/DateTimeFormatterTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -7,6 +8,9 @@
namespace Test;
+use OC\DateTimeFormatter;
+use OCP\Util;
+
class DateTimeFormatterTest extends TestCase {
/** @var \OC\DateTimeFormatter */
protected $formatter;
@@ -33,26 +37,26 @@ 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 function getTimestampAgo($time, $seconds = 0, $minutes = 0, $hours = 0, $days = 0, $years = 0) {
+ protected static function getTimestampAgo($time, $seconds = 0, $minutes = 0, $hours = 0, $days = 0, $years = 0) {
return $time - $seconds - $minutes * 60 - $hours * 3600 - $days * 24 * 3600 - $years * 365 * 24 * 3600;
}
- public function formatTimeSpanData() {
+ 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],
- ['1 minute ago', $this->getTimestampAgo($time, 30, 1), $time],
- ['15 minutes ago', $this->getTimestampAgo($time, 30, 15), $time],
- ['in 15 minutes', $time, $this->getTimestampAgo($time, 30, 15)],
- ['1 hour ago', $this->getTimestampAgo($time, 30, 15, 1), $time],
- ['3 hours ago', $this->getTimestampAgo($time, 30, 15, 3), $time],
- ['in 3 hours', $time, $this->getTimestampAgo($time, 30, 15, 3)],
- ['4 days ago', $this->getTimestampAgo($time, 30, 15, 3, 4), $time],
+ ['1 minute ago', self::getTimestampAgo($time, 30, 1), $time],
+ ['15 minutes ago', self::getTimestampAgo($time, 30, 15), $time],
+ ['in 15 minutes', $time, self::getTimestampAgo($time, 30, 15)],
+ ['1 hour ago', self::getTimestampAgo($time, 30, 15, 1), $time],
+ ['3 hours ago', self::getTimestampAgo($time, 30, 15, 3), $time],
+ ['in 3 hours', $time, self::getTimestampAgo($time, 30, 15, 3)],
+ ['4 days ago', self::getTimestampAgo($time, 30, 15, 3, 4), $time],
['seconds ago', new \DateTime('Wed, 02 Oct 2013 23:59:58 +0000'), new \DateTime('Wed, 02 Oct 2013 23:59:59 +0000')],
['seconds ago', new \DateTime('Wed, 02 Oct 2013 23:59:00 +0000'), new \DateTime('Wed, 02 Oct 2013 23:59:59 +0000')],
@@ -74,36 +78,34 @@ class DateTimeFormatterTest extends TestCase {
];
}
- /**
- * @dataProvider formatTimeSpanData
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('formatTimeSpanData')]
public function testFormatTimeSpan($expected, $timestamp, $compare, $locale = null): void {
$this->assertEquals((string)$expected, (string)$this->formatter->formatTimeSpan($timestamp, $compare, $locale));
}
- public function formatDateSpanData() {
+ 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', $this->getTimestampAgo($time, 30, 15), $time],
- ['yesterday', $this->getTimestampAgo($time, 0, 0, 0, 1), $time],
- ['tomorrow', $time, $this->getTimestampAgo($time, 0, 0, 0, 1)],
- ['4 days ago', $this->getTimestampAgo($time, 0, 0, 0, 4), $time],
- ['in 4 days', $time, $this->getTimestampAgo($time, 0, 0, 0, 4)],
- ['5 months ago', $this->getTimestampAgo($time, 0, 0, 0, 155), $time],
- ['next month', $time, $this->getTimestampAgo($time, 0, 0, 0, 32)],
- ['in 5 months', $time, $this->getTimestampAgo($time, 0, 0, 0, 155)],
- ['2 years ago', $this->getTimestampAgo($time, 0, 0, 0, 0, 2), $time],
- ['next year', $time, $this->getTimestampAgo($time, 0, 0, 0, 0, 1)],
- ['in 2 years', $time, $this->getTimestampAgo($time, 0, 0, 0, 0, 2)],
+ ['today', self::getTimestampAgo($time, 30, 15), $time],
+ ['yesterday', self::getTimestampAgo($time, 0, 0, 0, 1), $time],
+ ['tomorrow', $time, self::getTimestampAgo($time, 0, 0, 0, 1)],
+ ['4 days ago', self::getTimestampAgo($time, 0, 0, 0, 4), $time],
+ ['in 4 days', $time, self::getTimestampAgo($time, 0, 0, 0, 4)],
+ ['5 months ago', self::getTimestampAgo($time, 0, 0, 0, 155), $time],
+ ['next month', $time, self::getTimestampAgo($time, 0, 0, 0, 32)],
+ ['in 5 months', $time, self::getTimestampAgo($time, 0, 0, 0, 155)],
+ ['2 years ago', self::getTimestampAgo($time, 0, 0, 0, 0, 2), $time],
+ ['next year', $time, self::getTimestampAgo($time, 0, 0, 0, 0, 1)],
+ ['in 2 years', $time, self::getTimestampAgo($time, 0, 0, 0, 0, 2)],
// Test with compare timestamp
- ['today', $this->getTimestampAgo($time, 0, 0, 0, 0, 1), $this->getTimestampAgo($time, 0, 0, 0, 0, 1)],
- ['yesterday', $this->getTimestampAgo($time, 30, 15, 3, 1, 1), $this->getTimestampAgo($time, 0, 0, 0, 0, 1)],
- ['4 days ago', $this->getTimestampAgo($time, 30, 15, 3, 4, 1), $this->getTimestampAgo($time, 0, 0, 0, 0, 1)],
- ['5 months ago', $this->getTimestampAgo($time, 30, 15, 3, 155, 1), $this->getTimestampAgo($time, 0, 0, 0, 0, 1)],
- ['2 years ago', $this->getTimestampAgo($time, 30, 15, 3, 35, 3), $this->getTimestampAgo($time, 0, 0, 0, 0, 1)],
+ ['today', self::getTimestampAgo($time, 0, 0, 0, 0, 1), self::getTimestampAgo($time, 0, 0, 0, 0, 1)],
+ ['yesterday', self::getTimestampAgo($time, 30, 15, 3, 1, 1), self::getTimestampAgo($time, 0, 0, 0, 0, 1)],
+ ['4 days ago', self::getTimestampAgo($time, 30, 15, 3, 4, 1), self::getTimestampAgo($time, 0, 0, 0, 0, 1)],
+ ['5 months ago', self::getTimestampAgo($time, 30, 15, 3, 155, 1), self::getTimestampAgo($time, 0, 0, 0, 0, 1)],
+ ['2 years ago', self::getTimestampAgo($time, 30, 15, 3, 35, 3), self::getTimestampAgo($time, 0, 0, 0, 0, 1)],
// Test translations
[$deL10N->t('today'), new \DateTime('Wed, 02 Oct 2013 12:00:00 +0000'), new \DateTime('Wed, 02 Oct 2013 23:59:59 +0000'), $deL10N],
@@ -140,36 +142,30 @@ class DateTimeFormatterTest extends TestCase {
];
}
- /**
- * @dataProvider formatDateSpanData
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('formatDateSpanData')]
public function testFormatDateSpan($expected, $timestamp, $compare = null, $locale = null): void {
$this->assertEquals((string)$expected, (string)$this->formatter->formatDateSpan($timestamp, $compare, $locale));
}
- public function formatDateData() {
+ public static function formatDateData(): array {
return [
[1102831200, 'December 12, 2004'],
];
}
- /**
- * @dataProvider formatDateData
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('formatDateData')]
public function testFormatDate($timestamp, $expected): void {
$this->assertEquals($expected, (string)$this->formatter->formatDate($timestamp));
}
- public function formatDateTimeData() {
+ public static function formatDateTimeData(): array {
return [
[1350129205, null, "October 13, 2012, 11:53:25\xE2\x80\xAFAM UTC"],
[1350129205, new \DateTimeZone('Europe/Berlin'), "October 13, 2012, 1:53:25\xE2\x80\xAFPM GMT+2"],
];
}
- /**
- * @dataProvider formatDateTimeData
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('formatDateTimeData')]
public function testFormatDateTime($timestamp, $timeZone, $expected): void {
$this->assertEquals($expected, (string)$this->formatter->formatDateTime($timestamp, 'long', 'long', $timeZone));
}
diff --git a/tests/lib/Diagnostics/EventLoggerTest.php b/tests/lib/Diagnostics/EventLoggerTest.php
index 3ad13702679..ea9e95f80b3 100644
--- a/tests/lib/Diagnostics/EventLoggerTest.php
+++ b/tests/lib/Diagnostics/EventLoggerTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2017 ownCloud, Inc.
diff --git a/tests/lib/Diagnostics/QueryLoggerTest.php b/tests/lib/Diagnostics/QueryLoggerTest.php
index 6450c153b39..e54775a777f 100644
--- a/tests/lib/Diagnostics/QueryLoggerTest.php
+++ b/tests/lib/Diagnostics/QueryLoggerTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2017 ownCloud, Inc.
@@ -13,7 +14,7 @@ use Test\TestCase;
class QueryLoggerTest extends TestCase {
/** @var \OC\Diagnostics\QueryLogger */
private $logger;
-
+
protected function setUp(): void {
parent::setUp();
diff --git a/tests/lib/DirectEditing/ManagerTest.php b/tests/lib/DirectEditing/ManagerTest.php
index e09a87e448e..2ad7f98df49 100644
--- a/tests/lib/DirectEditing/ManagerTest.php
+++ b/tests/lib/DirectEditing/ManagerTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
@@ -22,6 +23,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 +126,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/EmojiHelperTest.php b/tests/lib/EmojiHelperTest.php
index 9ad56b32472..9a89a4b299e 100644
--- a/tests/lib/EmojiHelperTest.php
+++ b/tests/lib/EmojiHelperTest.php
@@ -27,9 +27,8 @@ class EmojiHelperTest extends TestCase {
/**
* @param bool $supports4ByteText
* @param bool $expected
- *
- * @dataProvider doesPlatformSupportEmojiDataProvider
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('doesPlatformSupportEmojiDataProvider')]
public function testDoesPlatformSupportEmoji(bool $supports4ByteText, bool $expected): void {
$this->db->expects($this->once())
->method('supports4ByteText')
@@ -38,10 +37,7 @@ class EmojiHelperTest extends TestCase {
$this->assertEquals($expected, $this->helper->doesPlatformSupportEmoji());
}
- /**
- * @return array
- */
- public function doesPlatformSupportEmojiDataProvider(): array {
+ public static function doesPlatformSupportEmojiDataProvider(): array {
return [
[true, true],
[false, false],
@@ -51,16 +47,15 @@ class EmojiHelperTest extends TestCase {
/**
* @param string $emoji
* @param bool $expected
- *
- * @dataProvider isValidSingleEmojiDataProvider
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('isValidSingleEmojiDataProvider')]
public function testIsValidSingleEmoji(string $emoji, bool $expected): void {
$actual = $this->helper->isValidSingleEmoji($emoji);
$this->assertEquals($expected, $actual);
}
- public function isValidSingleEmojiDataProvider(): array {
+ public static function isValidSingleEmojiDataProvider(): array {
return [
['📱📠', false],
['a', false],
diff --git a/tests/lib/Encryption/DecryptAllTest.php b/tests/lib/Encryption/DecryptAllTest.php
index 7385ff03785..979e12e03b3 100644
--- a/tests/lib/Encryption/DecryptAllTest.php
+++ b/tests/lib/Encryption/DecryptAllTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -44,7 +45,7 @@ class DecryptAllTest extends TestCase {
/** @var \PHPUnit\Framework\MockObject\MockObject | \Symfony\Component\Console\Output\OutputInterface */
protected $outputInterface;
- /** @var \PHPUnit\Framework\MockObject\MockObject | \OCP\UserInterface */
+ /** @var \PHPUnit\Framework\MockObject\MockObject|UserInterface */
protected $userInterface;
/** @var DecryptAll */
@@ -93,11 +94,11 @@ class DecryptAllTest extends TestCase {
}
/**
- * @dataProvider dataDecryptAll
* @param bool $prepareResult
* @param string $user
* @param bool $userExistsChecked
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataDecryptAll')]
public function testDecryptAll($prepareResult, $user, $userExistsChecked): void {
if ($userExistsChecked) {
$this->userManager->expects($this->once())->method('userExists')->willReturn(true);
@@ -153,9 +154,9 @@ class DecryptAllTest extends TestCase {
}
/**
- * @dataProvider dataTrueFalse
* @param bool $success
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataTrueFalse')]
public function testPrepareEncryptionModules($success): void {
$user = 'user1';
@@ -185,9 +186,7 @@ class DecryptAllTest extends TestCase {
);
}
- /**
- * @dataProvider dataTestDecryptAllUsersFiles
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataTestDecryptAllUsersFiles')]
public function testDecryptAllUsersFiles($user): void {
/** @var DecryptAll | \PHPUnit\Framework\MockObject\MockObject | $instance */
$instance = $this->getMockBuilder('OC\Encryption\DecryptAll')
@@ -217,7 +216,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 +296,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);
});
@@ -317,9 +316,7 @@ class DecryptAllTest extends TestCase {
$this->invokePrivate($instance, 'decryptUsersFiles', ['user1', $progressBar, '']);
}
- /**
- * @dataProvider dataTrueFalse
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataTrueFalse')]
public function testDecryptFile($isEncrypted): void {
$path = 'test.txt';
@@ -387,7 +384,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/EncryptionWrapperTest.php b/tests/lib/Encryption/EncryptionWrapperTest.php
index 1ac7342a3d8..58bf5aff005 100644
--- a/tests/lib/Encryption/EncryptionWrapperTest.php
+++ b/tests/lib/Encryption/EncryptionWrapperTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -9,7 +10,10 @@ namespace Test\Encryption;
use OC\Encryption\EncryptionWrapper;
use OC\Encryption\Manager;
+use OC\Files\Storage\Wrapper\Encryption;
use OC\Memcache\ArrayCache;
+use OCA\Files_Trashbin\Storage;
+use OCP\Files\Mount\IMountPoint;
use OCP\Files\Storage\IDisableEncryptionStorage;
use OCP\Files\Storage\IStorage;
use Psr\Log\LoggerInterface;
@@ -25,7 +29,7 @@ class EncryptionWrapperTest extends TestCase {
/** @var \PHPUnit\Framework\MockObject\MockObject | \OC\Encryption\Manager */
private $manager;
- /** @var \PHPUnit\Framework\MockObject\MockObject | \OC\Memcache\ArrayCache */
+ /** @var \PHPUnit\Framework\MockObject\MockObject|ArrayCache */
private $arrayCache;
protected function setUp(): void {
@@ -39,9 +43,7 @@ class EncryptionWrapperTest extends TestCase {
}
- /**
- * @dataProvider provideWrapStorage
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('provideWrapStorage')]
public function testWrapStorage($expectedWrapped, $wrappedStorages): void {
$storage = $this->getMockBuilder(IStorage::class)
->disableOriginalConstructor()
@@ -55,7 +57,7 @@ class EncryptionWrapperTest extends TestCase {
]);
}
- $mount = $this->getMockBuilder('OCP\Files\Mount\IMountPoint')
+ $mount = $this->getMockBuilder(IMountPoint::class)
->disableOriginalConstructor()
->getMock();
@@ -63,16 +65,16 @@ class EncryptionWrapperTest extends TestCase {
$this->assertEquals(
$expectedWrapped,
- $returnedStorage->instanceOfStorage('OC\Files\Storage\Wrapper\Encryption'),
+ $returnedStorage->instanceOfStorage(Encryption::class),
'Asserted that the storage is (not) wrapped with encryption'
);
}
- public function provideWrapStorage() {
+ public static function provideWrapStorage(): array {
return [
// Wrap when not wrapped or not wrapped with storage
[true, []],
- [true, ['OCA\Files_Trashbin\Storage']],
+ [true, [Storage::class]],
// Do not wrap shared storages
[false, [IDisableEncryptionStorage::class]],
diff --git a/tests/lib/Encryption/Keys/StorageTest.php b/tests/lib/Encryption/Keys/StorageTest.php
index bc79c5771ca..333d8d8ce21 100644
--- a/tests/lib/Encryption/Keys/StorageTest.php
+++ b/tests/lib/Encryption/Keys/StorageTest.php
@@ -124,13 +124,13 @@ class StorageTest extends TestCase {
}
/**
- * @dataProvider dataTestGetFileKey
*
* @param string $path
* @param string $strippedPartialName
* @param bool $originalKeyExists
* @param string $expectedKeyContent
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataTestGetFileKey')]
public function testGetFileKey($path, $strippedPartialName, $originalKeyExists, $expectedKeyContent): void {
$this->config->method('getSystemValueString')
->with('version')
@@ -408,9 +408,7 @@ class StorageTest extends TestCase {
);
}
- /**
- * @dataProvider dataProviderCopyRename
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataProviderCopyRename')]
public function testRenameKeys($source, $target, $systemWideMountSource, $systemWideMountTarget, $expectedSource, $expectedTarget): void {
$this->view->expects($this->any())
->method('file_exists')
@@ -439,9 +437,7 @@ class StorageTest extends TestCase {
$this->storage->renameKeys($source, $target);
}
- /**
- * @dataProvider dataProviderCopyRename
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataProviderCopyRename')]
public function testCopyKeys($source, $target, $systemWideMountSource, $systemWideMountTarget, $expectedSource, $expectedTarget): void {
$this->view->expects($this->any())
->method('file_exists')
@@ -510,13 +506,13 @@ class StorageTest extends TestCase {
}
/**
- * @dataProvider dataTestGetPathToKeys
*
* @param string $path
* @param boolean $systemWideMountPoint
* @param string $storageRoot
* @param string $expected
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataTestGetPathToKeys')]
public function testGetPathToKeys($path, $systemWideMountPoint, $storageRoot, $expected): void {
$this->invokePrivate($this->storage, 'root_dir', [$storageRoot]);
@@ -569,9 +565,9 @@ class StorageTest extends TestCase {
/**
- * @dataProvider dataTestBackupUserKeys
* @param bool $createBackupDir
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataTestBackupUserKeys')]
public function testBackupUserKeys($createBackupDir): void {
$storage = $this->getMockBuilder('OC\Encryption\Keys\Storage')
->setConstructorArgs([$this->view, $this->util, $this->crypto, $this->config])
@@ -589,7 +585,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..e9b6ddae8a0 100644
--- a/tests/lib/Encryption/ManagerTest.php
+++ b/tests/lib/Encryption/ManagerTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -6,6 +7,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 +91,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 +108,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);
@@ -263,7 +266,7 @@ class ManagerTest extends TestCase {
$encryptionModule->expects($this->any())
->method('getDisplayName')
->willReturn('TestDummyModule' . $id);
- /** @var \OCP\Encryption\IEncryptionModule $encryptionModule */
+ /** @var IEncryptionModule $encryptionModule */
$manager->registerEncryptionModule('ID' . $id, 'TestDummyModule' . $id, function () use ($encryptionModule) {
return $encryptionModule;
});
diff --git a/tests/lib/Encryption/UpdateTest.php b/tests/lib/Encryption/UpdateTest.php
index 2627e18601d..04ca224c0a1 100644
--- a/tests/lib/Encryption/UpdateTest.php
+++ b/tests/lib/Encryption/UpdateTest.php
@@ -1,4 +1,7 @@
<?php
+
+declare(strict_types=1);
+
/**
* SPDX-FileCopyrightText: 2017-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -10,84 +13,93 @@ namespace Test\Encryption;
use OC\Encryption\File;
use OC\Encryption\Update;
use OC\Encryption\Util;
-use OC\Files\Mount\Manager;
use OC\Files\View;
use OCP\Encryption\IEncryptionModule;
+use OCP\Files\File as OCPFile;
+use OCP\Files\Folder;
+use OCP\IUser;
+use PHPUnit\Framework\MockObject\MockObject;
use Psr\Log\LoggerInterface;
use Test\TestCase;
class UpdateTest extends TestCase {
- /** @var \OC\Encryption\Update */
- private $update;
-
- /** @var string */
- private $uid;
-
- /** @var \OC\Files\View | \PHPUnit\Framework\MockObject\MockObject */
- private $view;
-
- /** @var Util | \PHPUnit\Framework\MockObject\MockObject */
- private $util;
-
- /** @var \OC\Files\Mount\Manager | \PHPUnit\Framework\MockObject\MockObject */
- private $mountManager;
-
- /** @var \OC\Encryption\Manager | \PHPUnit\Framework\MockObject\MockObject */
- private $encryptionManager;
-
- /** @var \OCP\Encryption\IEncryptionModule | \PHPUnit\Framework\MockObject\MockObject */
- private $encryptionModule;
-
- /** @var \OC\Encryption\File | \PHPUnit\Framework\MockObject\MockObject */
- private $fileHelper;
-
- /** @var \PHPUnit\Framework\MockObject\MockObject|LoggerInterface */
- private $logger;
+ private string $uid;
+ private View&MockObject $view;
+ private Util&MockObject $util;
+ private \OC\Encryption\Manager&MockObject $encryptionManager;
+ private IEncryptionModule&MockObject $encryptionModule;
+ private File&MockObject $fileHelper;
+ private LoggerInterface&MockObject $logger;
protected function setUp(): void {
parent::setUp();
$this->view = $this->createMock(View::class);
$this->util = $this->createMock(Util::class);
- $this->mountManager = $this->createMock(Manager::class);
$this->encryptionManager = $this->createMock(\OC\Encryption\Manager::class);
$this->fileHelper = $this->createMock(File::class);
$this->encryptionModule = $this->createMock(IEncryptionModule::class);
$this->logger = $this->createMock(LoggerInterface::class);
$this->uid = 'testUser1';
+ }
- $this->update = new Update(
- $this->view,
- $this->util,
- $this->mountManager,
- $this->encryptionManager,
- $this->fileHelper,
- $this->logger,
- $this->uid);
+ private function getUserMock(string $uid): IUser&MockObject {
+ $user = $this->createMock(IUser::class);
+ $user->expects(self::any())
+ ->method('getUID')
+ ->willReturn($uid);
+ return $user;
+ }
+
+ private function getFileMock(string $path, string $owner): OCPFile&MockObject {
+ $node = $this->createMock(OCPFile::class);
+ $node->expects(self::atLeastOnce())
+ ->method('getPath')
+ ->willReturn($path);
+ $node->expects(self::any())
+ ->method('getOwner')
+ ->willReturn($this->getUserMock($owner));
+
+ return $node;
+ }
+
+ private function getFolderMock(string $path, string $owner): Folder&MockObject {
+ $node = $this->createMock(Folder::class);
+ $node->expects(self::atLeastOnce())
+ ->method('getPath')
+ ->willReturn($path);
+ $node->expects(self::any())
+ ->method('getOwner')
+ ->willReturn($this->getUserMock($owner));
+
+ return $node;
}
/**
- * @dataProvider dataTestUpdate
*
* @param string $path
* @param boolean $isDir
* @param array $allFiles
* @param integer $numberOfFiles
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataTestUpdate')]
public function testUpdate($path, $isDir, $allFiles, $numberOfFiles): void {
+ $updateMock = $this->getUpdateMock(['getOwnerPath']);
+ $updateMock->expects($this->once())->method('getOwnerPath')
+ ->willReturnCallback(fn (OCPFile|Folder $node) => '/user/' . $node->getPath());
+
$this->encryptionManager->expects($this->once())
->method('getEncryptionModule')
->willReturn($this->encryptionModule);
- $this->view->expects($this->once())
- ->method('is_dir')
- ->willReturn($isDir);
-
if ($isDir) {
$this->util->expects($this->once())
->method('getAllFiles')
->willReturn($allFiles);
+ $node = $this->getFolderMock($path, 'user');
+ } else {
+ $node = $this->getFileMock($path, 'user');
}
$this->fileHelper->expects($this->exactly($numberOfFiles))
@@ -98,15 +110,10 @@ class UpdateTest extends TestCase {
->method('update')
->willReturn(true);
- $this->update->update($path);
+ $updateMock->update($node);
}
- /**
- * data provider for testUpdate()
- *
- * @return array
- */
- public function dataTestUpdate() {
+ public static function dataTestUpdate(): array {
return [
['/user/files/foo', true, ['/user/files/foo/file1.txt', '/user/files/foo/file1.txt'], 2],
['/user/files/test.txt', false, [], 1],
@@ -114,106 +121,70 @@ class UpdateTest extends TestCase {
}
/**
- * @dataProvider dataTestPostRename
*
* @param string $source
* @param string $target
- * @param boolean $encryptionEnabled
*/
- public function testPostRename($source, $target, $encryptionEnabled): void {
- $updateMock = $this->getUpdateMock(['update', 'getOwnerPath']);
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataTestPostRename')]
+ public function testPostRename($source, $target): void {
+ $updateMock = $this->getUpdateMock(['update','getOwnerPath']);
- $this->encryptionManager->expects($this->once())
- ->method('isEnabled')
- ->willReturn($encryptionEnabled);
+ $sourceNode = $this->getFileMock($source, 'user');
+ $targetNode = $this->getFileMock($target, 'user');
- if (dirname($source) === dirname($target) || $encryptionEnabled === false) {
+ if (dirname($source) === dirname($target)) {
$updateMock->expects($this->never())->method('getOwnerPath');
$updateMock->expects($this->never())->method('update');
} else {
- $updateMock->expects($this->once())
- ->method('getOwnerPath')
- ->willReturnCallback(function ($path) use ($target) {
- $this->assertSame(
- $target,
- $path,
- 'update needs to be executed for the target destination');
- return ['owner', $path];
- });
- $updateMock->expects($this->once())->method('update');
+ $updateMock->expects($this->once())->method('update')
+ ->willReturnCallback(fn (OCPFile|Folder $node) => $this->assertSame(
+ $target,
+ $node->getPath(),
+ 'update needs to be executed for the target destination'
+ ));
}
- $updateMock->postRename(['oldpath' => $source, 'newpath' => $target]);
+ $updateMock->postRename($sourceNode, $targetNode);
}
- /**
- * test data for testPostRename()
- *
- * @return array
- */
- public function dataTestPostRename() {
+ public static function dataTestPostRename(): array {
return [
- ['/test.txt', '/testNew.txt', true],
- ['/test.txt', '/testNew.txt', false],
- ['/folder/test.txt', '/testNew.txt', true],
- ['/folder/test.txt', '/testNew.txt', false],
- ['/folder/test.txt', '/testNew.txt', true],
- ['/test.txt', '/folder/testNew.txt', false],
+ ['/test.txt', '/testNew.txt'],
+ ['/folder/test.txt', '/testNew.txt'],
+ ['/test.txt', '/folder/testNew.txt'],
];
}
-
- /**
- * @dataProvider dataTestPostRestore
- *
- * @param boolean $encryptionEnabled
- */
- public function testPostRestore($encryptionEnabled): void {
+ public function testPostRestore(): void {
$updateMock = $this->getUpdateMock(['update']);
- $this->encryptionManager->expects($this->once())
- ->method('isEnabled')
- ->willReturn($encryptionEnabled);
+ $updateMock->expects($this->once())->method('update')
+ ->willReturnCallback(fn (OCPFile|Folder $node) => $this->assertSame(
+ '/folder/test.txt',
+ $node->getPath(),
+ 'update needs to be executed for the target destination'
+ ));
- if ($encryptionEnabled) {
- $updateMock->expects($this->once())->method('update');
- } else {
- $updateMock->expects($this->never())->method('update');
- }
-
- $updateMock->postRestore(['filePath' => '/folder/test.txt']);
- }
-
- /**
- * test data for testPostRestore()
- *
- * @return array
- */
- public function dataTestPostRestore() {
- return [
- [true],
- [false],
- ];
+ $updateMock->postRestore($this->getFileMock('/folder/test.txt', 'user'));
}
/**
* create mock of the update method
*
* @param array $methods methods which should be set
- * @return \OC\Encryption\Update | \PHPUnit\Framework\MockObject\MockObject
*/
- protected function getUpdateMock($methods) {
- return $this->getMockBuilder('\OC\Encryption\Update')
+ protected function getUpdateMock(array $methods): Update&MockObject {
+ return $this->getMockBuilder(Update::class)
->setConstructorArgs(
[
- $this->view,
$this->util,
- $this->mountManager,
$this->encryptionManager,
$this->fileHelper,
$this->logger,
$this->uid
]
- )->setMethods($methods)->getMock();
+ )
+ ->onlyMethods($methods)
+ ->getMock();
}
}
diff --git a/tests/lib/Encryption/UtilTest.php b/tests/lib/Encryption/UtilTest.php
index 62ef809a867..d1fefee872a 100644
--- a/tests/lib/Encryption/UtilTest.php
+++ b/tests/lib/Encryption/UtilTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -6,6 +7,7 @@
*/
namespace Test\Encryption;
+use OC\Encryption\Exceptions\EncryptionHeaderKeyExistsException;
use OC\Encryption\Util;
use OC\Files\View;
use OCP\Encryption\IEncryptionModule;
@@ -20,7 +22,7 @@ class UtilTest extends TestCase {
*
* @see https://bugs.php.net/bug.php?id=21641
*/
- protected int $headerSize = 8192;
+ protected static int $headerSize = 8192;
/** @var \PHPUnit\Framework\MockObject\MockObject */
protected $view;
@@ -53,15 +55,13 @@ class UtilTest extends TestCase {
);
}
- /**
- * @dataProvider providesHeadersForEncryptionModule
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('providesHeadersForEncryptionModule')]
public function testGetEncryptionModuleId($expected, $header): void {
$id = $this->util->getEncryptionModuleId($header);
$this->assertEquals($expected, $id);
}
- public function providesHeadersForEncryptionModule() {
+ public static function providesHeadersForEncryptionModule(): array {
return [
['', []],
['', ['1']],
@@ -69,9 +69,7 @@ class UtilTest extends TestCase {
];
}
- /**
- * @dataProvider providesHeaders
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('providesHeaders')]
public function testCreateHeader($expected, $header, $moduleId): void {
$em = $this->createMock(IEncryptionModule::class);
$em->expects($this->any())->method('getId')->willReturn($moduleId);
@@ -80,18 +78,18 @@ class UtilTest extends TestCase {
$this->assertEquals($expected, $result);
}
- public function providesHeaders() {
+ public static function providesHeaders(): array {
return [
- [str_pad('HBEGIN:oc_encryption_module:0:HEND', $this->headerSize, '-', STR_PAD_RIGHT)
+ [str_pad('HBEGIN:oc_encryption_module:0:HEND', self::$headerSize, '-', STR_PAD_RIGHT)
, [], '0'],
- [str_pad('HBEGIN:oc_encryption_module:0:custom_header:foo:HEND', $this->headerSize, '-', STR_PAD_RIGHT)
+ [str_pad('HBEGIN:oc_encryption_module:0:custom_header:foo:HEND', self::$headerSize, '-', STR_PAD_RIGHT)
, ['custom_header' => 'foo'], '0'],
];
}
public function testCreateHeaderFailed(): void {
- $this->expectException(\OC\Encryption\Exceptions\EncryptionHeaderKeyExistsException::class);
+ $this->expectException(EncryptionHeaderKeyExistsException::class);
$header = ['header1' => 1, 'header2' => 2, 'oc_encryption_module' => 'foo'];
@@ -102,9 +100,7 @@ class UtilTest extends TestCase {
$this->util->createHeader($header, $em);
}
- /**
- * @dataProvider providePathsForTestIsExcluded
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('providePathsForTestIsExcluded')]
public function testIsExcluded($path, $keyStorageRoot, $expected): void {
$this->config->expects($this->once())
->method('getAppValue')
@@ -120,7 +116,7 @@ class UtilTest extends TestCase {
);
}
- public function providePathsForTestIsExcluded() {
+ public static function providePathsForTestIsExcluded(): array {
return [
['/files_encryption', '', true],
['files_encryption/foo.txt', '', true],
@@ -143,16 +139,14 @@ class UtilTest extends TestCase {
return false;
}
- /**
- * @dataProvider dataTestIsFile
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataTestIsFile')]
public function testIsFile($path, $expected): void {
$this->assertSame($expected,
$this->util->isFile($path)
);
}
- public function dataTestIsFile() {
+ public static function dataTestIsFile(): array {
return [
['/user/files/test.txt', true],
['/user/files', true],
@@ -165,17 +159,17 @@ class UtilTest extends TestCase {
}
/**
- * @dataProvider dataTestStripPartialFileExtension
*
* @param string $path
* @param string $expected
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataTestStripPartialFileExtension')]
public function testStripPartialFileExtension($path, $expected): void {
$this->assertSame($expected,
$this->util->stripPartialFileExtension($path));
}
- public function dataTestStripPartialFileExtension() {
+ public static function dataTestStripPartialFileExtension(): array {
return [
['/foo/test.txt', '/foo/test.txt'],
['/foo/test.txt.part', '/foo/test.txt'],
@@ -184,9 +178,7 @@ class UtilTest extends TestCase {
];
}
- /**
- * @dataProvider dataTestParseRawHeader
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataTestParseRawHeader')]
public function testParseRawHeader($rawHeader, $expected): void {
$result = $this->util->parseRawHeader($rawHeader);
$this->assertSameSize($expected, $result);
@@ -196,28 +188,28 @@ class UtilTest extends TestCase {
}
}
- public function dataTestParseRawHeader() {
+ public static function dataTestParseRawHeader(): array {
return [
- [str_pad('HBEGIN:oc_encryption_module:0:HEND', $this->headerSize, '-', STR_PAD_RIGHT)
+ [str_pad('HBEGIN:oc_encryption_module:0:HEND', self::$headerSize, '-', STR_PAD_RIGHT)
, [Util::HEADER_ENCRYPTION_MODULE_KEY => '0']],
- [str_pad('HBEGIN:oc_encryption_module:0:custom_header:foo:HEND', $this->headerSize, '-', STR_PAD_RIGHT)
+ [str_pad('HBEGIN:oc_encryption_module:0:custom_header:foo:HEND', self::$headerSize, '-', STR_PAD_RIGHT)
, ['custom_header' => 'foo', Util::HEADER_ENCRYPTION_MODULE_KEY => '0']],
- [str_pad('HelloWorld', $this->headerSize, '-', STR_PAD_RIGHT), []],
+ [str_pad('HelloWorld', self::$headerSize, '-', STR_PAD_RIGHT), []],
['', []],
- [str_pad('HBEGIN:oc_encryption_module:0', $this->headerSize, '-', STR_PAD_RIGHT)
+ [str_pad('HBEGIN:oc_encryption_module:0', self::$headerSize, '-', STR_PAD_RIGHT)
, []],
- [str_pad('oc_encryption_module:0:HEND', $this->headerSize, '-', STR_PAD_RIGHT)
+ [str_pad('oc_encryption_module:0:HEND', self::$headerSize, '-', STR_PAD_RIGHT)
, []],
];
}
/**
- * @dataProvider dataTestGetFileKeyDir
*
* @param bool $isSystemWideMountPoint
* @param string $storageRoot
* @param string $expected
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataTestGetFileKeyDir')]
public function testGetFileKeyDir($isSystemWideMountPoint, $storageRoot, $expected): void {
$path = '/user1/files/foo/bar.txt';
$owner = 'user1';
@@ -245,7 +237,7 @@ class UtilTest extends TestCase {
);
}
- public function dataTestGetFileKeyDir() {
+ public static function dataTestGetFileKeyDir(): array {
return [
[false, '', '/user1/files_encryption/keys/foo/bar.txt/OC_DEFAULT_MODULE/'],
[true, '', '/files_encryption/keys/foo/bar.txt/OC_DEFAULT_MODULE/'],
diff --git a/tests/lib/ErrorHandlerTest.php b/tests/lib/ErrorHandlerTest.php
index b45525e7962..0bec3445d34 100644
--- a/tests/lib/ErrorHandlerTest.php
+++ b/tests/lib/ErrorHandlerTest.php
@@ -16,10 +16,9 @@ use PHPUnit\Framework\MockObject\MockObject;
use Psr\Log\LoggerInterface;
class ErrorHandlerTest extends TestCase {
- /** @var MockObject */
- private LoggerInterface $logger;
-
+ private LoggerInterface&MockObject $logger;
private ErrorHandler $errorHandler;
+ private int $errorReporting;
protected function setUp(): void {
parent::setUp();
@@ -28,13 +27,20 @@ class ErrorHandlerTest extends TestCase {
$this->errorHandler = new ErrorHandler(
$this->logger
);
+
+ $this->errorReporting = error_reporting(E_ALL);
+ }
+
+ protected function tearDown(): void {
+ error_reporting($this->errorReporting);
+ parent::tearDown();
}
/**
* provide username, password combinations for testRemovePassword
* @return array
*/
- public function passwordProvider() {
+ public static function passwordProvider(): array {
return [
['us:er', 'pass@word'],
['us:er', 'password'],
@@ -49,10 +55,10 @@ class ErrorHandlerTest extends TestCase {
}
/**
- * @dataProvider passwordProvider
* @param string $username
* @param string $password
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('passwordProvider')]
public function testRemovePasswordFromError($username, $password): void {
$url = 'http://' . $username . ':' . $password . '@owncloud.org';
$expectedResult = 'http://xxx:xxx@owncloud.org';
diff --git a/tests/lib/EventSourceFactoryTest.php b/tests/lib/EventSourceFactoryTest.php
index c5e22a8fe34..96d6e6e770a 100644
--- a/tests/lib/EventSourceFactoryTest.php
+++ b/tests/lib/EventSourceFactoryTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2023 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
diff --git a/tests/lib/Federation/CloudIdManagerTest.php b/tests/lib/Federation/CloudIdManagerTest.php
index 7019cd202db..3bd3cf6149d 100644
--- a/tests/lib/Federation/CloudIdManagerTest.php
+++ b/tests/lib/Federation/CloudIdManagerTest.php
@@ -56,7 +56,7 @@ class CloudIdManagerTest extends TestCase {
$this->overwriteService(ICloudIdManager::class, $this->cloudIdManager);
}
- public function dataGetDisplayNameFromContact(): array {
+ public static function dataGetDisplayNameFromContact(): array {
return [
['test1@example.tld', 'test', 'test'],
['test2@example.tld', null, null],
@@ -65,9 +65,7 @@ class CloudIdManagerTest extends TestCase {
];
}
- /**
- * @dataProvider dataGetDisplayNameFromContact
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataGetDisplayNameFromContact')]
public function testGetDisplayNameFromContact(string $cloudId, ?string $displayName, ?string $expected): void {
$returnedContact = [
'CLOUD' => [$cloudId],
@@ -84,7 +82,7 @@ class CloudIdManagerTest extends TestCase {
$this->assertEquals($expected, $this->cloudIdManager->getDisplayNameFromContact($cloudId));
}
- public function cloudIdProvider(): array {
+ public static function cloudIdProvider(): array {
return [
['test@example.com', 'test', 'example.com', 'test@example.com'],
['test@example.com/cloud', 'test', 'example.com/cloud', 'test@example.com/cloud'],
@@ -98,9 +96,7 @@ class CloudIdManagerTest extends TestCase {
];
}
- /**
- * @dataProvider cloudIdProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('cloudIdProvider')]
public function testResolveCloudId(string $cloudId, string $user, string $noProtocolRemote, string $cleanId): void {
$displayName = 'Ample Ex';
@@ -122,7 +118,7 @@ class CloudIdManagerTest extends TestCase {
$this->assertEquals($displayName . '@' . $noProtocolRemote, $cloudId->getDisplayId());
}
- public function invalidCloudIdProvider(): array {
+ public static function invalidCloudIdProvider(): array {
return [
['example.com'],
['test:foo@example.com'],
@@ -130,9 +126,7 @@ class CloudIdManagerTest extends TestCase {
];
}
- /**
- * @dataProvider invalidCloudIdProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('invalidCloudIdProvider')]
public function testInvalidCloudId(string $cloudId): void {
$this->expectException(\InvalidArgumentException::class);
@@ -142,7 +136,7 @@ class CloudIdManagerTest extends TestCase {
$this->cloudIdManager->resolveCloudId($cloudId);
}
- public function getCloudIdProvider(): array {
+ public static function getCloudIdProvider(): array {
return [
['test', 'example.com', 'test@example.com', null, 'https://example.com', 'https://example.com'],
['test', 'http://example.com', 'test@http://example.com', 'test@example.com'],
@@ -154,9 +148,7 @@ class CloudIdManagerTest extends TestCase {
];
}
- /**
- * @dataProvider getCloudIdProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('getCloudIdProvider')]
public function testGetCloudId(string $user, ?string $remote, string $id, ?string $searchCloudId = null, ?string $localHost = 'https://example.com', ?string $expectedRemoteId = null): void {
if ($remote !== null) {
$this->contactsManager->expects($this->any())
diff --git a/tests/lib/Federation/CloudIdTest.php b/tests/lib/Federation/CloudIdTest.php
index ca949d163c7..67683861e40 100644
--- a/tests/lib/Federation/CloudIdTest.php
+++ b/tests/lib/Federation/CloudIdTest.php
@@ -28,7 +28,7 @@ class CloudIdTest extends TestCase {
$this->overwriteService(ICloudIdManager::class, $this->cloudIdManager);
}
- public function dataGetDisplayCloudId(): array {
+ public static function dataGetDisplayCloudId(): array {
return [
['test@example.com', 'test', 'example.com', 'test@example.com'],
['test@http://example.com', 'test', 'http://example.com', 'test@example.com'],
@@ -37,9 +37,7 @@ class CloudIdTest extends TestCase {
];
}
- /**
- * @dataProvider dataGetDisplayCloudId
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataGetDisplayCloudId')]
public function testGetDisplayCloudId(string $id, string $user, string $remote, string $display, ?string $addressbookName = null): void {
$this->cloudIdManager->expects($this->once())
->method('getDisplayNameFromContact')
diff --git a/tests/lib/Files/AppData/AppDataTest.php b/tests/lib/Files/AppData/AppDataTest.php
index 494096d1ac3..ed006622504 100644
--- a/tests/lib/Files/AppData/AppDataTest.php
+++ b/tests/lib/Files/AppData/AppDataTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
diff --git a/tests/lib/Files/AppData/FactoryTest.php b/tests/lib/Files/AppData/FactoryTest.php
index dff999d8b48..6092c931091 100644
--- a/tests/lib/Files/AppData/FactoryTest.php
+++ b/tests/lib/Files/AppData/FactoryTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
diff --git a/tests/lib/Files/Cache/CacheTest.php b/tests/lib/Files/Cache/CacheTest.php
index 204f87d6a18..383962b7224 100644
--- a/tests/lib/Files/Cache/CacheTest.php
+++ b/tests/lib/Files/Cache/CacheTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -11,13 +12,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();
}
@@ -32,23 +38,42 @@ class LongId extends \OC\Files\Storage\Temporary {
*/
class CacheTest extends \Test\TestCase {
/**
- * @var \OC\Files\Storage\Temporary $storage ;
+ * @var Temporary $storage ;
*/
protected $storage;
/**
- * @var \OC\Files\Storage\Temporary $storage2 ;
+ * @var Temporary $storage2 ;
*/
protected $storage2;
/**
- * @var \OC\Files\Cache\Cache $cache
+ * @var Cache $cache
*/
protected $cache;
/**
- * @var \OC\Files\Cache\Cache $cache2
+ * @var Cache $cache2
*/
protected $cache2;
+ protected function setUp(): void {
+ parent::setUp();
+
+ $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]);
+ }
+
+ protected function tearDown(): void {
+ if ($this->cache) {
+ $this->cache->clear();
+ }
+
+ parent::tearDown();
+ }
+
public function testGetNumericId(): void {
$this->assertNotNull($this->cache->getNumericStorageId());
}
@@ -137,14 +162,12 @@ class CacheTest extends \Test\TestCase {
$this->assertEquals(new CacheEntry(['size' => 12, 'mtime' => 15]), $this->cache->get($file1));
}
- /**
- * @dataProvider folderDataProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('folderDataProvider')]
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');
}
}
@@ -208,7 +231,7 @@ class CacheTest extends \Test\TestCase {
}
}
- public function folderDataProvider() {
+ public static function folderDataProvider(): array {
return [
['folder'],
// that was too easy, try something harder
@@ -292,16 +315,16 @@ 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 function putWithAllKindOfQuotesData() {
+ public static function putWithAllKindOfQuotesData(): array {
return [
['`backtick`'],
['´forward´'],
@@ -310,11 +333,11 @@ class CacheTest extends \Test\TestCase {
}
/**
- * @dataProvider putWithAllKindOfQuotesData
* @param $fileName
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('putWithAllKindOfQuotesData')]
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);
@@ -352,9 +375,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';
@@ -374,7 +397,7 @@ class CacheTest extends \Test\TestCase {
$id4 = $this->cache->put($file4, $fileData['foo2']);
$id5 = $this->cache->put($file5, $fileData['foo3']);
- $tagManager = \OC::$server->getTagManager()->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'));
@@ -399,7 +422,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();
@@ -437,7 +460,7 @@ class CacheTest extends \Test\TestCase {
new SearchComparison(ISearchComparison::COMPARE_GREATER_THAN_EQUAL, 'size', 100), 10, 0, [], $user)));
}
- public function movePathProvider() {
+ public static function movePathProvider(): array {
return [
['folder/foo', 'folder/foobar', ['1', '2']],
['folder/foo', 'foo', ['1', '2']],
@@ -445,9 +468,7 @@ class CacheTest extends \Test\TestCase {
];
}
- /**
- * @dataProvider movePathProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('movePathProvider')]
public function testMove($sourceFolder, $targetFolder, $children): void {
$data = ['size' => 100, 'mtime' => 50, 'mimetype' => 'foo/bar'];
$folderData = ['size' => 100, 'mtime' => 50, 'mimetype' => ICacheEntry::DIRECTORY_MIMETYPE];
@@ -531,7 +552,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 {
@@ -558,7 +579,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));
}
/**
@@ -572,10 +593,10 @@ class CacheTest extends \Test\TestCase {
$folderWith0308 = "\x53\x63\x68\x6f\xcc\x88\x6e";
/**
- * @var \OC\Files\Cache\Cache | \PHPUnit\Framework\MockObject\MockObject $cacheMock
+ * @var Cache|\PHPUnit\Framework\MockObject\MockObject $cacheMock
*/
$cacheMock = $this->getMockBuilder(Cache::class)
- ->setMethods(['normalize'])
+ ->onlyMethods(['normalize'])
->setConstructorArgs([$this->storage])
->getMock();
@@ -646,7 +667,7 @@ class CacheTest extends \Test\TestCase {
$this->assertEquals(1, count($this->cache->getFolderContents('folder')));
}
- public function bogusPathNamesProvider() {
+ public static function bogusPathNamesProvider(): array {
return [
['/bogus.txt', 'bogus.txt'],
['//bogus.txt', 'bogus.txt'],
@@ -657,9 +678,8 @@ class CacheTest extends \Test\TestCase {
/**
* Test bogus paths with leading or doubled slashes
- *
- * @dataProvider bogusPathNamesProvider
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('bogusPathNamesProvider')]
public function testBogusPaths($bogusPath, $fixedBogusPath): void {
$data = ['size' => 100, 'mtime' => 50, 'mimetype' => ICacheEntry::DIRECTORY_MIMETYPE];
$parentId = $this->cache->getId('');
@@ -691,7 +711,7 @@ class CacheTest extends \Test\TestCase {
$this->assertNotEquals($fileId, $fileId2);
}
- public function escapingProvider() {
+ public static function escapingProvider(): array {
return [
['foo'],
['o%'],
@@ -701,8 +721,8 @@ class CacheTest extends \Test\TestCase {
/**
* @param string $name
- * @dataProvider escapingProvider
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('escapingProvider')]
public function testEscaping($name): void {
$data = ['size' => 100, 'mtime' => 50, 'mimetype' => 'text/plain'];
$this->cache->put($name, $data);
@@ -807,23 +827,4 @@ class CacheTest extends \Test\TestCase {
$this->cache->remove('sub');
}
-
- protected function tearDown(): void {
- if ($this->cache) {
- $this->cache->clear();
- }
-
- parent::tearDown();
- }
-
- 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->cache->insert('', ['size' => 0, 'mtime' => 0, 'mimetype' => ICacheEntry::DIRECTORY_MIMETYPE]);
- $this->cache2->insert('', ['size' => 0, 'mtime' => 0, 'mimetype' => ICacheEntry::DIRECTORY_MIMETYPE]);
- }
}
diff --git a/tests/lib/Files/Cache/HomeCacheTest.php b/tests/lib/Files/Cache/HomeCacheTest.php
index ad069de1fef..86fda615fd7 100644
--- a/tests/lib/Files/Cache/HomeCacheTest.php
+++ b/tests/lib/Files/Cache/HomeCacheTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -7,24 +8,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,
+ ) {
}
/**
@@ -61,15 +58,15 @@ class HomeCacheTest extends \Test\TestCase {
private $cache;
/**
- * @var \OC\User\User $user
+ * @var User $user
*/
private $user;
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..d580cdca4b9 100644
--- a/tests/lib/Files/Cache/MoveFromCacheTraitTest.php
+++ b/tests/lib/Files/Cache/MoveFromCacheTraitTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -7,10 +8,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 +26,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/PropagatorTest.php b/tests/lib/Files/Cache/PropagatorTest.php
index e88816dfccc..2ab213e9567 100644
--- a/tests/lib/Files/Cache/PropagatorTest.php
+++ b/tests/lib/Files/Cache/PropagatorTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
diff --git a/tests/lib/Files/Cache/ScannerTest.php b/tests/lib/Files/Cache/ScannerTest.php
index d78b7100d43..123c13893f7 100644
--- a/tests/lib/Files/Cache/ScannerTest.php
+++ b/tests/lib/Files/Cache/ScannerTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -14,6 +15,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 +70,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 +340,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 +366,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();
@@ -383,18 +386,18 @@ class ScannerTest extends TestCase {
}
/**
- * @dataProvider dataTestIsPartialFile
*
* @param string $path
* @param bool $expected
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataTestIsPartialFile')]
public function testIsPartialFile($path, $expected): void {
$this->assertSame($expected,
$this->scanner->isPartialFile($path)
);
}
- public function dataTestIsPartialFile() {
+ public static function dataTestIsPartialFile(): array {
return [
['foo.txt.part', true],
['/sub/folder/foo.txt.part', true],
diff --git a/tests/lib/Files/Cache/SearchBuilderTest.php b/tests/lib/Files/Cache/SearchBuilderTest.php
index 17285d44209..ee097044e3b 100644
--- a/tests/lib/Files/Cache/SearchBuilderTest.php
+++ b/tests/lib/Files/Cache/SearchBuilderTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2017 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
@@ -16,6 +17,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 +42,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 +79,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 +112,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) {
@@ -134,7 +137,7 @@ class SearchBuilderTest extends TestCase {
return $rows;
}
- public function comparisonProvider() {
+ public static function comparisonProvider(): array {
return [
[new SearchComparison(ISearchComparison::COMPARE_GREATER_THAN, 'mtime', 125), [1]],
[new SearchComparison(ISearchComparison::COMPARE_LESS_THAN, 'mtime', 125), [0]],
@@ -175,11 +178,11 @@ class SearchBuilderTest extends TestCase {
}
/**
- * @dataProvider comparisonProvider
*
* @param ISearchOperator $operator
* @param array $fileIds
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('comparisonProvider')]
public function testComparison(ISearchOperator $operator, array $fileIds): void {
$fileId = [];
$fileId[] = $this->addCacheEntry([
diff --git a/tests/lib/Files/Cache/UpdaterLegacyTest.php b/tests/lib/Files/Cache/UpdaterLegacyTest.php
index 0f7e9d78d77..c71fac2d2dc 100644
--- a/tests/lib/Files/Cache/UpdaterLegacyTest.php
+++ b/tests/lib/Files/Cache/UpdaterLegacyTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -7,9 +8,15 @@
namespace Test\Files\Cache;
+use OC\Files\Cache\Cache;
+use OC\Files\Cache\Scanner;
use OC\Files\Filesystem as Filesystem;
+use OC\Files\Storage\Storage;
+use OC\Files\Storage\Temporary;
use OC\Files\View;
use OCP\Files\Mount\IMountManager;
+use OCP\IUserManager;
+use OCP\Server;
/**
* Class UpdaterLegacyTest
@@ -20,17 +27,17 @@ use OCP\Files\Mount\IMountManager;
*/
class UpdaterLegacyTest extends \Test\TestCase {
/**
- * @var \OC\Files\Storage\Storage $storage
+ * @var Storage $storage
*/
private $storage;
/**
- * @var \OC\Files\Cache\Scanner $scanner
+ * @var Scanner $scanner
*/
private $scanner;
/**
- * @var \OC\Files\Cache\Cache $cache
+ * @var Cache $cache
*/
private $cache;
@@ -39,7 +46,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 +63,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 +83,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 +129,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 +190,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 +246,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/UpdaterTest.php b/tests/lib/Files/Cache/UpdaterTest.php
index ab46bdd4141..65c47cb9ae6 100644
--- a/tests/lib/Files/Cache/UpdaterTest.php
+++ b/tests/lib/Files/Cache/UpdaterTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -7,10 +8,13 @@
namespace Test\Files\Cache;
+use OC\Files\Cache\Cache;
use OC\Files\Filesystem;
use OC\Files\ObjectStore\ObjectStoreStorage;
use OC\Files\ObjectStore\StorageObjectStore;
+use OC\Files\Storage\Storage;
use OC\Files\Storage\Temporary;
+use OC\Files\View;
use OCP\Files\Storage\IStorage;
/**
@@ -22,17 +26,17 @@ use OCP\Files\Storage\IStorage;
*/
class UpdaterTest extends \Test\TestCase {
/**
- * @var \OC\Files\Storage\Storage
+ * @var Storage
*/
protected $storage;
/**
- * @var \OC\Files\Cache\Cache
+ * @var Cache
*/
protected $cache;
/**
- * @var \OC\Files\View
+ * @var View
*/
protected $view;
@@ -305,16 +309,14 @@ class UpdaterTest extends \Test\TestCase {
}
}
- public function changeExtensionProvider(): array {
+ public static function changeExtensionProvider(): array {
return [
[new Temporary()],
[new ObjectStoreStorage(['objectstore' => new StorageObjectStore(new Temporary())])]
];
}
- /**
- * @dataProvider changeExtensionProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('changeExtensionProvider')]
public function testChangeExtension(IStorage $storage) {
$updater = $storage->getUpdater();
$cache = $storage->getCache();
diff --git a/tests/lib/Files/Cache/WatcherTest.php b/tests/lib/Files/Cache/WatcherTest.php
index 7319aa9b68d..6d0a8e0886b 100644
--- a/tests/lib/Files/Cache/WatcherTest.php
+++ b/tests/lib/Files/Cache/WatcherTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2018-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -7,6 +8,10 @@
namespace Test\Files\Cache;
+use OC\Files\Cache\Watcher;
+use OC\Files\Storage\Storage;
+use OC\Files\Storage\Temporary;
+
/**
* Class WatcherTest
*
@@ -16,7 +21,7 @@ namespace Test\Files\Cache;
*/
class WatcherTest extends \Test\TestCase {
/**
- * @var \OC\Files\Storage\Storage[] $storages
+ * @var Storage[] $storages
*/
private $storages = [];
@@ -44,7 +49,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 +90,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 +107,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 +129,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 +147,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 +165,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'));
@@ -172,10 +177,10 @@ class WatcherTest extends \Test\TestCase {
/**
* @param bool $scan
- * @return \OC\Files\Storage\Storage
+ * @return 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 aed13c41ac0..8ac3492fbd2 100644
--- a/tests/lib/Files/Cache/Wrapper/CacheJailTest.php
+++ b/tests/lib/Files/Cache/Wrapper/CacheJailTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -7,7 +8,9 @@
namespace Test\Files\Cache\Wrapper;
+use OC\Files\Cache\Cache;
use OC\Files\Cache\Wrapper\CacheJail;
+use OC\Files\Cache\Wrapper\CacheWrapper;
use OC\Files\Search\SearchComparison;
use OC\Files\Search\SearchQuery;
use OC\Files\Storage\Wrapper\Jail;
@@ -26,7 +29,7 @@ use Test\Files\Cache\CacheTest;
*/
class CacheJailTest extends CacheTest {
/**
- * @var \OC\Files\Cache\Cache $sourceCache
+ * @var Cache $sourceCache
*/
protected $sourceCache;
@@ -34,7 +37,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]);
}
@@ -129,7 +132,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);
}
@@ -199,7 +202,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);
@@ -217,7 +220,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);
@@ -252,4 +255,14 @@ class CacheJailTest extends CacheTest {
$storage->getWatcher()->update('bar', ['mimetype' => 'text/plain']);
$this->assertTrue($this->cache->inCache('bar'));
}
+
+ public function testUnJailedRoot(): void {
+ $jail1 = new CacheJail($this->sourceCache, 'foo');
+ $jail2 = new CacheJail($jail1, 'bar');
+ $this->assertEquals('foo/bar', $jail2->getGetUnjailedRoot());
+
+ $middleWrapper = new CacheWrapper($jail1);
+ $jail3 = new CacheJail($middleWrapper, 'bar');
+ $this->assertEquals('foo/bar', $jail3->getGetUnjailedRoot());
+ }
}
diff --git a/tests/lib/Files/Cache/Wrapper/CachePermissionsMaskTest.php b/tests/lib/Files/Cache/Wrapper/CachePermissionsMaskTest.php
index afb5c6a5d4d..4fbeafc9270 100644
--- a/tests/lib/Files/Cache/Wrapper/CachePermissionsMaskTest.php
+++ b/tests/lib/Files/Cache/Wrapper/CachePermissionsMaskTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -7,6 +8,8 @@
namespace Test\Files\Cache\Wrapper;
+use OC\Files\Cache\Cache;
+use OC\Files\Cache\Wrapper\CachePermissionsMask;
use OCP\Constants;
use Test\Files\Cache\CacheTest;
@@ -19,7 +22,7 @@ use Test\Files\Cache\CacheTest;
*/
class CachePermissionsMaskTest extends CacheTest {
/**
- * @var \OC\Files\Cache\Cache $sourceCache
+ * @var Cache $sourceCache
*/
protected $sourceCache;
@@ -31,10 +34,10 @@ 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 function maskProvider() {
+ public static function maskProvider(): array {
return [
[Constants::PERMISSION_ALL],
[Constants::PERMISSION_ALL - Constants::PERMISSION_SHARE],
@@ -44,9 +47,9 @@ class CachePermissionsMaskTest extends CacheTest {
}
/**
- * @dataProvider maskProvider
* @param int $mask
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('maskProvider')]
public function testGetMasked($mask): void {
$cache = $this->getMaskedCached($mask);
$data = ['size' => 100, 'mtime' => 50, 'mimetype' => 'text/plain', 'permissions' => Constants::PERMISSION_ALL];
@@ -61,9 +64,9 @@ class CachePermissionsMaskTest extends CacheTest {
}
/**
- * @dataProvider maskProvider
* @param int $mask
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('maskProvider')]
public function testGetFolderContentMasked($mask): void {
$this->storage->mkdir('foo');
$this->storage->file_put_contents('foo/bar', 'asd');
@@ -80,9 +83,9 @@ class CachePermissionsMaskTest extends CacheTest {
}
/**
- * @dataProvider maskProvider
* @param int $mask
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('maskProvider')]
public function testSearchMasked($mask): void {
$this->storage->mkdir('foo');
$this->storage->file_put_contents('foo/bar', 'asd');
diff --git a/tests/lib/Files/Config/UserMountCacheTest.php b/tests/lib/Files/Config/UserMountCacheTest.php
index 1efc56c1908..6a3dc6a6d7e 100644
--- a/tests/lib/Files/Config/UserMountCacheTest.php
+++ b/tests/lib/Files/Config/UserMountCacheTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -9,6 +10,8 @@ namespace Test\Files\Config;
use OC\DB\Exceptions\DbalException;
use OC\DB\QueryBuilder\Literal;
+use OC\Files\Cache\Cache;
+use OC\Files\Config\UserMountCache;
use OC\Files\Mount\MountPoint;
use OC\Files\Storage\Storage;
use OC\User\Manager;
@@ -16,11 +19,15 @@ use OCP\Cache\CappedMemoryCache;
use OCP\DB\QueryBuilder\IQueryBuilder;
use OCP\Diagnostics\IEventLogger;
use OCP\EventDispatcher\IEventDispatcher;
+use OCP\Files\Config\Event\UserMountAddedEvent;
+use OCP\Files\Config\Event\UserMountRemovedEvent;
+use OCP\Files\Config\Event\UserMountUpdatedEvent;
use OCP\Files\Config\ICachedMountInfo;
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;
@@ -29,28 +36,19 @@ use Test\Util\User\Dummy;
* @group DB
*/
class UserMountCacheTest extends TestCase {
- /**
- * @var IDBConnection
- */
- private $connection;
-
- /**
- * @var IUserManager
- */
- private $userManager;
-
- /**
- * @var \OC\Files\Config\UserMountCache
- */
- private $cache;
-
- private $fileIds = [];
+ private IDBConnection $connection;
+ private IUserManager $userManager;
+ private IEventDispatcher $eventDispatcher;
+ private UserMountCache $cache;
+ private array $fileIds = [];
protected function setUp(): void {
parent::setUp();
$this->fileIds = [];
- $this->connection = \OC::$server->getDatabaseConnection();
+
+ $this->connection = Server::get(IDBConnection::class);
+
$config = $this->getMockBuilder(IConfig::class)
->disableOriginalConstructor()
->getMock();
@@ -62,13 +60,22 @@ class UserMountCacheTest extends TestCase {
->expects($this->any())
->method('getAppValue')
->willReturnArgument(2);
+
$this->userManager = new Manager($config, $this->createMock(ICacheFactory::class), $this->createMock(IEventDispatcher::class), $this->createMock(LoggerInterface::class));
$userBackend = new Dummy();
$userBackend->createUser('u1', '');
$userBackend->createUser('u2', '');
$userBackend->createUser('u3', '');
$this->userManager->registerBackend($userBackend);
- $this->cache = new \OC\Files\Config\UserMountCache($this->connection, $this->userManager, $this->createMock(LoggerInterface::class), $this->createMock(IEventLogger::class));
+
+ $this->eventDispatcher = $this->createMock(IEventDispatcher::class);
+
+ $this->cache = new UserMountCache($this->connection,
+ $this->userManager,
+ $this->createMock(LoggerInterface::class),
+ $this->createMock(IEventLogger::class),
+ $this->eventDispatcher,
+ );
}
protected function tearDown(): void {
@@ -88,25 +95,19 @@ class UserMountCacheTest extends TestCase {
private function getStorage($storageId, $rootInternalPath = '') {
$rootId = $this->createCacheEntry($rootInternalPath, $storageId);
- $storageCache = $this->getMockBuilder('\OC\Files\Cache\Storage')
- ->disableOriginalConstructor()
- ->getMock();
+ $storageCache = $this->createMock(\OC\Files\Cache\Storage::class);
$storageCache->expects($this->any())
->method('getNumericId')
->willReturn($storageId);
- $cache = $this->getMockBuilder('\OC\Files\Cache\Cache')
- ->disableOriginalConstructor()
- ->getMock();
+ $cache = $this->createMock(Cache::class);
$cache->expects($this->any())
->method('getId')
->willReturn($rootId);
$cache->method('getNumericStorageId')
->willReturn($storageId);
- $storage = $this->getMockBuilder('\OC\Files\Storage\Storage')
- ->disableOriginalConstructor()
- ->getMock();
+ $storage = $this->createMock(Storage::class);
$storage->expects($this->any())
->method('getStorageCache')
->willReturn($storageCache);
@@ -126,6 +127,11 @@ class UserMountCacheTest extends TestCase {
}
public function testNewMounts(): void {
+ $this->eventDispatcher
+ ->expects($this->once())
+ ->method('dispatchTyped')
+ ->with($this->callback(fn (UserMountAddedEvent $event) => $event->mountPoint->getMountPoint() === '/asd/'));
+
$user = $this->userManager->get('u1');
[$storage] = $this->getStorage(10);
@@ -146,6 +152,11 @@ class UserMountCacheTest extends TestCase {
}
public function testSameMounts(): void {
+ $this->eventDispatcher
+ ->expects($this->once())
+ ->method('dispatchTyped')
+ ->with($this->callback(fn (UserMountAddedEvent $event) => $event->mountPoint->getMountPoint() === '/asd/'));
+
$user = $this->userManager->get('u1');
[$storage] = $this->getStorage(10);
@@ -170,6 +181,18 @@ class UserMountCacheTest extends TestCase {
}
public function testRemoveMounts(): void {
+ $operation = 0;
+ $this->eventDispatcher
+ ->expects($this->exactly(2))
+ ->method('dispatchTyped')
+ ->with($this->callback(function (UserMountAddedEvent|UserMountRemovedEvent $event) use (&$operation) {
+ return match(++$operation) {
+ 1 => $event instanceof UserMountAddedEvent && $event->mountPoint->getMountPoint() === '/asd/',
+ 2 => $event instanceof UserMountRemovedEvent && $event->mountPoint->getMountPoint() === '/asd/',
+ default => false,
+ };
+ }));
+
$user = $this->userManager->get('u1');
[$storage] = $this->getStorage(10);
@@ -189,6 +212,19 @@ class UserMountCacheTest extends TestCase {
}
public function testChangeMounts(): void {
+ $operation = 0;
+ $this->eventDispatcher
+ ->expects($this->exactly(3))
+ ->method('dispatchTyped')
+ ->with($this->callback(function (UserMountAddedEvent|UserMountRemovedEvent $event) use (&$operation) {
+ return match(++$operation) {
+ 1 => $event instanceof UserMountAddedEvent && $event->mountPoint->getMountPoint() === '/bar/',
+ 2 => $event instanceof UserMountAddedEvent && $event->mountPoint->getMountPoint() === '/foo/',
+ 3 => $event instanceof UserMountRemovedEvent && $event->mountPoint->getMountPoint() === '/bar/',
+ default => false,
+ };
+ }));
+
$user = $this->userManager->get('u1');
[$storage] = $this->getStorage(10);
@@ -212,6 +248,18 @@ class UserMountCacheTest extends TestCase {
}
public function testChangeMountId(): void {
+ $operation = 0;
+ $this->eventDispatcher
+ ->expects($this->exactly(2))
+ ->method('dispatchTyped')
+ ->with($this->callback(function (UserMountAddedEvent|UserMountUpdatedEvent $event) use (&$operation) {
+ return match(++$operation) {
+ 1 => $event instanceof UserMountAddedEvent && $event->mountPoint->getMountPoint() === '/foo/',
+ 2 => $event instanceof UserMountUpdatedEvent && $event->oldMountPoint->getMountId() === null && $event->newMountPoint->getMountId() === 1,
+ default => false,
+ };
+ }));
+
$user = $this->userManager->get('u1');
[$storage] = $this->getStorage(10);
@@ -427,9 +475,9 @@ class UserMountCacheTest extends TestCase {
$fileId = $this->createCacheEntry('/foo/bar', 2);
- $mount1 = $this->getMockBuilder('\OC\Files\Mount\MountPoint')
+ $mount1 = $this->getMockBuilder(MountPoint::class)
->setConstructorArgs([$storage1, '/'])
- ->setMethods(['getStorageRootId'])
+ ->onlyMethods(['getStorageRootId'])
->getMock();
$mount1->expects($this->any())
@@ -460,9 +508,9 @@ class UserMountCacheTest extends TestCase {
$folderId = $this->createCacheEntry('/foo', 2);
$fileId = $this->createCacheEntry('/bar/asd', 2);
- $mount1 = $this->getMockBuilder('\OC\Files\Mount\MountPoint')
+ $mount1 = $this->getMockBuilder(MountPoint::class)
->setConstructorArgs([$storage1, '/foo/'])
- ->setMethods(['getStorageRootId'])
+ ->onlyMethods(['getStorageRootId'])
->getMock();
$mount1->expects($this->any())
@@ -509,7 +557,7 @@ class UserMountCacheTest extends TestCase {
$mount1 = $this->getMockBuilder(MountPoint::class)
->setConstructorArgs([$storage1, '/u1/'])
- ->setMethods(['getStorageRootId', 'getNumericStorageId'])
+ ->onlyMethods(['getStorageRootId', 'getNumericStorageId'])
->getMock();
$mount1->expects($this->any())
diff --git a/tests/lib/Files/EtagTest.php b/tests/lib/Files/EtagTest.php
index b0cdff16f4d..d1b344ee997 100644
--- a/tests/lib/Files/EtagTest.php
+++ b/tests/lib/Files/EtagTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -8,8 +9,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 +44,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 +57,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 +77,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/FileInfoTest.php b/tests/lib/Files/FileInfoTest.php
index 2979252f78a..b3d3c9f0fec 100644
--- a/tests/lib/Files/FileInfoTest.php
+++ b/tests/lib/Files/FileInfoTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
diff --git a/tests/lib/Files/FilenameValidatorTest.php b/tests/lib/Files/FilenameValidatorTest.php
index 45f681bd453..162275a2cf8 100644
--- a/tests/lib/Files/FilenameValidatorTest.php
+++ b/tests/lib/Files/FilenameValidatorTest.php
@@ -48,9 +48,7 @@ class FilenameValidatorTest extends TestCase {
$this->database->method('supports4ByteText')->willReturn(true);
}
- /**
- * @dataProvider dataValidateFilename
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataValidateFilename')]
public function testValidateFilename(
string $filename,
array $forbiddenNames,
@@ -87,9 +85,7 @@ class FilenameValidatorTest extends TestCase {
$validator->validateFilename($filename);
}
- /**
- * @dataProvider dataValidateFilename
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataValidateFilename')]
public function testIsFilenameValid(
string $filename,
array $forbiddenNames,
@@ -122,7 +118,7 @@ class FilenameValidatorTest extends TestCase {
$this->assertEquals($exception === null, $validator->isFilenameValid($filename));
}
- public function dataValidateFilename(): array {
+ public static function dataValidateFilename(): array {
return [
'valid name' => [
'a: b.txt', ['.htaccess'], [], [], [], null
@@ -189,9 +185,7 @@ class FilenameValidatorTest extends TestCase {
];
}
- /**
- * @dataProvider data4ByteUnicode
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('data4ByteUnicode')]
public function testDatabaseDoesNotSupport4ByteText($filename): void {
$database = $this->createMock(IDBConnection::class);
$database->expects($this->once())
@@ -202,23 +196,21 @@ class FilenameValidatorTest extends TestCase {
$validator->validateFilename($filename);
}
- public function data4ByteUnicode(): array {
+ public static function data4ByteUnicode(): array {
return [
['plane 1 𐪅'],
['emoji 😶‍🌫️'],
];
}
- /**
- * @dataProvider dataInvalidAsciiCharacters
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataInvalidAsciiCharacters')]
public function testInvalidAsciiCharactersAreAlwaysForbidden(string $filename): void {
$this->expectException(InvalidPathException::class);
$validator = new FilenameValidator($this->l10n, $this->database, $this->config, $this->logger);
$validator->validateFilename($filename);
}
- public function dataInvalidAsciiCharacters(): array {
+ public static function dataInvalidAsciiCharacters(): array {
return [
[\chr(0)],
[\chr(1)],
@@ -255,9 +247,7 @@ class FilenameValidatorTest extends TestCase {
];
}
- /**
- * @dataProvider dataIsForbidden
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataIsForbidden')]
public function testIsForbidden(string $filename, array $forbiddenNames, bool $expected): void {
/** @var FilenameValidator&MockObject */
$validator = $this->getMockBuilder(FilenameValidator::class)
@@ -271,7 +261,7 @@ class FilenameValidatorTest extends TestCase {
$this->assertEquals($expected, $validator->isForbidden($filename));
}
- public function dataIsForbidden(): array {
+ public static function dataIsForbidden(): array {
return [
'valid name' => [
'a: b.txt', ['.htaccess'], false
@@ -291,9 +281,7 @@ class FilenameValidatorTest extends TestCase {
];
}
- /**
- * @dataProvider dataGetForbiddenExtensions
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataGetForbiddenExtensions')]
public function testGetForbiddenExtensions(array $configValue, array $expectedValue): void {
$validator = new FilenameValidator($this->l10n, $this->database, $this->config, $this->logger);
$this->config
@@ -317,9 +305,7 @@ class FilenameValidatorTest extends TestCase {
];
}
- /**
- * @dataProvider dataGetForbiddenFilenames
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataGetForbiddenFilenames')]
public function testGetForbiddenFilenames(array $configValue, array $legacyValue, array $expectedValue): void {
$validator = new FilenameValidator($this->l10n, $this->database, $this->config, $this->logger);
$this->config
@@ -349,9 +335,7 @@ class FilenameValidatorTest extends TestCase {
];
}
- /**
- * @dataProvider dataGetForbiddenBasenames
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataGetForbiddenBasenames')]
public function testGetForbiddenBasenames(array $configValue, array $expectedValue): void {
$validator = new FilenameValidator($this->l10n, $this->database, $this->config, $this->logger);
$this->config
@@ -374,4 +358,134 @@ class FilenameValidatorTest extends TestCase {
[['AuX', 'COM1'], ['aux', 'com1']],
];
}
+
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataSanitizeFilename')]
+ public function testSanitizeFilename(
+ string $filename,
+ array $forbiddenNames,
+ array $forbiddenBasenames,
+ array $forbiddenExtensions,
+ array $forbiddenCharacters,
+ string $expected,
+ ): void {
+ /** @var FilenameValidator&MockObject */
+ $validator = $this->getMockBuilder(FilenameValidator::class)
+ ->onlyMethods([
+ 'getForbiddenBasenames',
+ 'getForbiddenExtensions',
+ 'getForbiddenFilenames',
+ 'getForbiddenCharacters',
+ ])
+ ->setConstructorArgs([$this->l10n, $this->database, $this->config, $this->logger])
+ ->getMock();
+
+ $validator->method('getForbiddenBasenames')
+ ->willReturn($forbiddenBasenames);
+ $validator->method('getForbiddenCharacters')
+ ->willReturn($forbiddenCharacters);
+ $validator->method('getForbiddenExtensions')
+ ->willReturn($forbiddenExtensions);
+ $validator->method('getForbiddenFilenames')
+ ->willReturn($forbiddenNames);
+
+ $this->assertEquals($expected, $validator->sanitizeFilename($filename));
+ }
+
+ public static function dataSanitizeFilename(): array {
+ return [
+ 'valid name' => [
+ 'a * b.txt', ['.htaccess'], [], [], [], 'a * b.txt'
+ ],
+ 'forbidden name in the middle is ok' => [
+ 'a.htaccess.txt', ['.htaccess'], [], [], [], 'a.htaccess.txt'
+ ],
+ 'forbidden name on the beginning' => [
+ '.htaccess.sample', ['.htaccess'], [], [], [], '.htaccess.sample'
+ ],
+ 'forbidden name' => [
+ '.htaccess', ['.htaccess'], [], [], [], '.htaccess (renamed)'
+ ],
+ 'forbidden name - name is case insensitive' => [
+ 'COM1', ['.htaccess', 'com1'], [], [], [], 'COM1 (renamed)'
+ ],
+ 'forbidden basename' => [
+ 'com1.suffix', ['.htaccess'], ['com1'], [], [], 'com1 (renamed).suffix'
+ ],
+ 'forbidden basename case insensitive' => [
+ // needed for Windows namespaces
+ 'COM1.suffix', ['.htaccess'], ['com1'], [], [], 'COM1 (renamed).suffix'
+ ],
+ 'forbidden basename for hidden files' => [
+ // needed for Windows namespaces
+ '.thumbs.db', ['.htaccess'], ['.thumbs'], [], [], '.thumbs (renamed).db'
+ ],
+ 'invalid character' => [
+ 'a: b.txt', ['.htaccess'], [], [], [':'], 'a_ b.txt',
+ ],
+ 'invalid extension' => [
+ 'a: b.txt', ['.htaccess'], [], ['.txt'], [], 'a: b'
+ ],
+ 'invalid extension case insensitive' => [
+ 'a: b.TXT', ['.htaccess'], [], ['.txt'], [], 'a: b'
+ ],
+ 'empty filename' => [
+ '', [], [], [], [], 'renamed file'
+ ],
+ ];
+ }
+
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataSanitizeFilenameCharacterReplacement')]
+ public function testSanitizeFilenameCharacterReplacement(
+ string $filename,
+ array $forbiddenCharacters,
+ ?string $characterReplacement,
+ ?string $expected,
+ ): void {
+ /** @var FilenameValidator&MockObject */
+ $validator = $this->getMockBuilder(FilenameValidator::class)
+ ->onlyMethods([
+ 'getForbiddenBasenames',
+ 'getForbiddenExtensions',
+ 'getForbiddenFilenames',
+ 'getForbiddenCharacters',
+ ])
+ ->setConstructorArgs([$this->l10n, $this->database, $this->config, $this->logger])
+ ->getMock();
+
+ $validator->method('getForbiddenBasenames')
+ ->willReturn([]);
+ $validator->method('getForbiddenCharacters')
+ ->willReturn($forbiddenCharacters);
+ $validator->method('getForbiddenExtensions')
+ ->willReturn([]);
+ $validator->method('getForbiddenFilenames')
+ ->willReturn([]);
+
+ if ($expected === null) {
+ $this->expectException(\InvalidArgumentException::class);
+ $validator->sanitizeFilename($filename, $characterReplacement);
+ } else {
+ $this->assertEquals($expected, $validator->sanitizeFilename($filename, $characterReplacement));
+ }
+ }
+
+ public static function dataSanitizeFilenameCharacterReplacement(): array {
+ return [
+ 'default' => [
+ 'foo*bar', ['*'], null, 'foo_bar'
+ ],
+ 'default - underscore not allowed' => [
+ 'foo*bar', ['*', '_'], null, 'foo-bar'
+ ],
+ 'default - dash and underscore not allowed' => [
+ 'foo*bar', ['*', '-', '_'], null, 'foo bar'
+ ],
+ 'default - no replacement' => [
+ 'foo*bar', ['*', ' ', '_', '-'], null, null
+ ],
+ 'custom replacement' => [
+ 'foo*bar', ['*'], 'x', 'fooxbar'
+ ],
+ ];
+ }
}
diff --git a/tests/lib/Files/FilesystemTest.php b/tests/lib/Files/FilesystemTest.php
index a920dc662da..a819acb1620 100644
--- a/tests/lib/Files/FilesystemTest.php
+++ b/tests/lib/Files/FilesystemTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -7,23 +8,30 @@
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\Mount\IMountPoint;
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,
+ ) {
}
/**
@@ -31,7 +39,7 @@ class DummyMountProvider implements IMountProvider {
*
* @param IUser $user
* @param IStorageFactory $loader
- * @return \OCP\Files\Mount\IMountPoint[]
+ * @return IMountPoint[]
*/
public function getMountsForUser(IUser $user, IStorageFactory $loader) {
return isset($this->mounts[$user->getUID()]) ? $this->mounts[$user->getUID()] : [];
@@ -58,7 +66,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];
}
@@ -68,13 +76,13 @@ 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();
}
protected function tearDown(): void {
foreach ($this->tmpDirs as $dir) {
- \OC_Helper::rmdirr($dir);
+ Files::rmdirr($dir);
}
$this->logout();
@@ -83,24 +91,24 @@ 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);
}
- public function normalizePathData() {
+ public static function normalizePathData(): array {
return [
['/', ''],
['/', '/'],
@@ -194,14 +202,12 @@ class FilesystemTest extends \Test\TestCase {
];
}
- /**
- * @dataProvider normalizePathData
- */
+ #[\PHPUnit\Framework\Attributes\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 function normalizePathKeepUnicodeData() {
+ public static function normalizePathKeepUnicodeData(): array {
$nfdName = 'ümlaut';
$nfcName = 'ümlaut';
return [
@@ -212,22 +218,20 @@ class FilesystemTest extends \Test\TestCase {
];
}
- /**
- * @dataProvider normalizePathKeepUnicodeData
- */
+ #[\PHPUnit\Framework\Attributes\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 function isValidPathData() {
+ public static function isValidPathData(): array {
return [
['/', true],
['/path', true],
@@ -253,14 +257,12 @@ class FilesystemTest extends \Test\TestCase {
];
}
- /**
- * @dataProvider isValidPathData
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('isValidPathData')]
public function testIsValidPath($path, $expected): void {
- $this->assertSame($expected, \OC\Files\Filesystem::isValidPath($path));
+ $this->assertSame($expected, Filesystem::isValidPath($path));
}
- public function isFileBlacklistedData() {
+ public static function isFileBlacklistedData(): array {
return [
['/etc/foo/bar/foo.txt', false],
['\etc\foo/bar\foo.txt', false],
@@ -275,11 +277,9 @@ class FilesystemTest extends \Test\TestCase {
];
}
- /**
- * @dataProvider isFileBlacklistedData
- */
+ #[\PHPUnit\Framework\Attributes\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 {
@@ -287,36 +287,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);
@@ -327,29 +327,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++;
}
@@ -364,13 +364,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++;
}
@@ -384,11 +384,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')) {
@@ -397,7 +397,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();
}
@@ -405,7 +405,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
}
/**
@@ -413,22 +413,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();
}
@@ -443,23 +443,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();
}
@@ -468,11 +468,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]]);
- \OC::$server->getMountProviderCollection()->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..e6cf3348664 100644
--- a/tests/lib/Files/Mount/ManagerTest.php
+++ b/tests/lib/Files/Mount/ManagerTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -7,6 +8,7 @@
namespace Test\Files\Mount;
+use OC\Files\Mount\MountPoint;
use OC\Files\SetupManagerFactory;
use OC\Files\Storage\Temporary;
@@ -28,33 +30,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..bcbcc96e3a3 100644
--- a/tests/lib/Files/Mount/MountPointTest.php
+++ b/tests/lib/Files/Mount/MountPointTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -7,6 +8,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 +25,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 +45,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..05c8a7d58e7 100644
--- a/tests/lib/Files/Mount/MountTest.php
+++ b/tests/lib/Files/Mount/MountTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2020-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -7,6 +8,7 @@
namespace Test\Files\Mount;
+use OC\Files\Mount\MountPoint;
use OC\Files\Storage\StorageFactory;
use OC\Files\Storage\Wrapper\Wrapper;
@@ -15,12 +17,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 +40,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 3daf82461cb..dd696279b86 100644
--- a/tests/lib/Files/Mount/ObjectHomeMountProviderTest.php
+++ b/tests/lib/Files/Mount/ObjectHomeMountProviderTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -7,6 +8,9 @@
namespace Test\Files\Mount;
use OC\Files\Mount\ObjectHomeMountProvider;
+use OC\Files\ObjectStore\PrimaryObjectStoreConfig;
+use OCP\App\IAppManager;
+use OCP\Files\ObjectStore\IObjectStore;
use OCP\Files\Storage\IStorageFactory;
use OCP\IConfig;
use OCP\IUser;
@@ -31,51 +35,54 @@ class ObjectHomeMountProviderTest extends \Test\TestCase {
$this->user = $this->createMock(IUser::class);
$this->loader = $this->createMock(IStorageFactory::class);
- $this->provider = new ObjectHomeMountProvider($this->config);
+ $objectStoreConfig = new PrimaryObjectStoreConfig($this->config, $this->createMock(IAppManager::class));
+ $this->provider = new ObjectHomeMountProvider($objectStoreConfig);
}
public function testSingleBucket(): void {
- $this->config->expects($this->once())
- ->method('getSystemValue')
- ->with($this->equalTo('objectstore'), '')
- ->willReturn([
- 'class' => 'Test\Files\Mount\FakeObjectStore',
- ]);
+ $this->config->method('getSystemValue')
+ ->willReturnCallback(function ($key, $default) {
+ if ($key === 'objectstore') {
+ return [
+ 'class' => 'Test\Files\Mount\FakeObjectStore',
+ 'arguments' => [
+ 'foo' => 'bar'
+ ],
+ ];
+ } else {
+ return $default;
+ }
+ });
- $this->user->expects($this->never())->method($this->anything());
- $this->loader->expects($this->never())->method($this->anything());
-
- $config = $this->invokePrivate($this->provider, 'getSingleBucketObjectStoreConfig', [$this->user, $this->loader]);
+ $mount = $this->provider->getHomeMountForUser($this->user, $this->loader);
+ $arguments = $this->invokePrivate($mount, 'arguments');
- $this->assertArrayHasKey('class', $config);
- $this->assertEquals($config['class'], 'Test\Files\Mount\FakeObjectStore');
- $this->assertArrayHasKey('arguments', $config);
- $this->assertArrayHasKey('user', $config['arguments']);
- $this->assertSame($this->user, $config['arguments']['user']);
- $this->assertArrayHasKey('objectstore', $config['arguments']);
- $this->assertInstanceOf('Test\Files\Mount\FakeObjectStore', $config['arguments']['objectstore']);
+ $objectStore = $arguments['objectstore'];
+ $this->assertInstanceOf(FakeObjectStore::class, $objectStore);
+ $this->assertEquals(['foo' => 'bar', 'multibucket' => false], $objectStore->getArguments());
}
public function testMultiBucket(): void {
- $this->config->expects($this->exactly(2))
- ->method('getSystemValue')
- ->with($this->equalTo('objectstore_multibucket'), '')
- ->willReturn([
- 'class' => 'Test\Files\Mount\FakeObjectStore',
- ]);
+ $this->config->method('getSystemValue')
+ ->willReturnCallback(function ($key, $default) {
+ if ($key === 'objectstore_multibucket') {
+ return [
+ 'class' => 'Test\Files\Mount\FakeObjectStore',
+ 'arguments' => [
+ 'foo' => 'bar'
+ ],
+ ];
+ } else {
+ return $default;
+ }
+ });
$this->user->method('getUID')
->willReturn('uid');
$this->loader->expects($this->never())->method($this->anything());
- $this->config->expects($this->once())
- ->method('getUserValue')
- ->with(
- $this->equalTo('uid'),
- $this->equalTo('homeobjectstore'),
- $this->equalTo('bucket'),
- $this->equalTo(null)
- )->willReturn(null);
+ $this->config->method('getUserValue')
+ ->willReturn(null);
$this->config->expects($this->once())
->method('setUserValue')
@@ -87,42 +94,37 @@ class ObjectHomeMountProviderTest extends \Test\TestCase {
$this->equalTo(null)
);
- $config = $this->invokePrivate($this->provider, 'getMultiBucketObjectStoreConfig', [$this->user, $this->loader]);
+ $mount = $this->provider->getHomeMountForUser($this->user, $this->loader);
+ $arguments = $this->invokePrivate($mount, 'arguments');
- $this->assertArrayHasKey('class', $config);
- $this->assertEquals($config['class'], 'Test\Files\Mount\FakeObjectStore');
- $this->assertArrayHasKey('arguments', $config);
- $this->assertArrayHasKey('user', $config['arguments']);
- $this->assertSame($this->user, $config['arguments']['user']);
- $this->assertArrayHasKey('objectstore', $config['arguments']);
- $this->assertInstanceOf('Test\Files\Mount\FakeObjectStore', $config['arguments']['objectstore']);
- $this->assertArrayHasKey('bucket', $config['arguments']);
- $this->assertEquals('49', $config['arguments']['bucket']);
+ $objectStore = $arguments['objectstore'];
+ $this->assertInstanceOf(FakeObjectStore::class, $objectStore);
+ $this->assertEquals(['foo' => 'bar', 'bucket' => 49, 'multibucket' => true], $objectStore->getArguments());
}
public function testMultiBucketWithPrefix(): void {
- $this->config->expects($this->exactly(2))
- ->method('getSystemValue')
- ->with('objectstore_multibucket')
- ->willReturn([
- 'class' => 'Test\Files\Mount\FakeObjectStore',
- 'arguments' => [
- 'bucket' => 'myBucketPrefix',
- ],
- ]);
+ $this->config->method('getSystemValue')
+ ->willReturnCallback(function ($key, $default) {
+ if ($key === 'objectstore_multibucket') {
+ return [
+ 'class' => 'Test\Files\Mount\FakeObjectStore',
+ 'arguments' => [
+ 'foo' => 'bar',
+ 'bucket' => 'myBucketPrefix',
+ ],
+ ];
+ } else {
+ return $default;
+ }
+ });
$this->user->method('getUID')
->willReturn('uid');
$this->loader->expects($this->never())->method($this->anything());
- $this->config->expects($this->once())
+ $this->config
->method('getUserValue')
- ->with(
- $this->equalTo('uid'),
- $this->equalTo('homeobjectstore'),
- $this->equalTo('bucket'),
- $this->equalTo(null)
- )->willReturn(null);
+ ->willReturn(null);
$this->config->expects($this->once())
->method('setUserValue')
@@ -134,66 +136,70 @@ class ObjectHomeMountProviderTest extends \Test\TestCase {
$this->equalTo(null)
);
- $config = $this->invokePrivate($this->provider, 'getMultiBucketObjectStoreConfig', [$this->user, $this->loader]);
+ $mount = $this->provider->getHomeMountForUser($this->user, $this->loader);
+ $arguments = $this->invokePrivate($mount, 'arguments');
- $this->assertArrayHasKey('class', $config);
- $this->assertEquals($config['class'], 'Test\Files\Mount\FakeObjectStore');
- $this->assertArrayHasKey('arguments', $config);
- $this->assertArrayHasKey('user', $config['arguments']);
- $this->assertSame($this->user, $config['arguments']['user']);
- $this->assertArrayHasKey('objectstore', $config['arguments']);
- $this->assertInstanceOf('Test\Files\Mount\FakeObjectStore', $config['arguments']['objectstore']);
- $this->assertArrayHasKey('bucket', $config['arguments']);
- $this->assertEquals('myBucketPrefix49', $config['arguments']['bucket']);
+ $objectStore = $arguments['objectstore'];
+ $this->assertInstanceOf(FakeObjectStore::class, $objectStore);
+ $this->assertEquals(['foo' => 'bar', 'bucket' => 'myBucketPrefix49', 'multibucket' => true], $objectStore->getArguments());
}
public function testMultiBucketBucketAlreadySet(): void {
- $this->config->expects($this->once())
- ->method('getSystemValue')
- ->with('objectstore_multibucket')
- ->willReturn([
- 'class' => 'Test\Files\Mount\FakeObjectStore',
- 'arguments' => [
- 'bucket' => 'myBucketPrefix',
- ],
- ]);
+ $this->config->method('getSystemValue')
+ ->willReturnCallback(function ($key, $default) {
+ if ($key === 'objectstore_multibucket') {
+ return [
+ 'class' => 'Test\Files\Mount\FakeObjectStore',
+ 'arguments' => [
+ 'foo' => 'bar',
+ 'bucket' => 'myBucketPrefix',
+ ],
+ ];
+ } else {
+ return $default;
+ }
+ });
$this->user->method('getUID')
->willReturn('uid');
$this->loader->expects($this->never())->method($this->anything());
- $this->config->expects($this->once())
+ $this->config
->method('getUserValue')
- ->with(
- $this->equalTo('uid'),
- $this->equalTo('homeobjectstore'),
- $this->equalTo('bucket'),
- $this->equalTo(null)
- )->willReturn('awesomeBucket1');
+ ->willReturnCallback(function ($uid, $app, $key, $default) {
+ if ($uid === 'uid' && $app === 'homeobjectstore' && $key === 'bucket') {
+ return 'awesomeBucket1';
+ } else {
+ return $default;
+ }
+ });
$this->config->expects($this->never())
->method('setUserValue');
- $config = $this->invokePrivate($this->provider, 'getMultiBucketObjectStoreConfig', [$this->user, $this->loader]);
+ $mount = $this->provider->getHomeMountForUser($this->user, $this->loader);
+ $arguments = $this->invokePrivate($mount, 'arguments');
- $this->assertArrayHasKey('class', $config);
- $this->assertEquals($config['class'], 'Test\Files\Mount\FakeObjectStore');
- $this->assertArrayHasKey('arguments', $config);
- $this->assertArrayHasKey('user', $config['arguments']);
- $this->assertSame($this->user, $config['arguments']['user']);
- $this->assertArrayHasKey('objectstore', $config['arguments']);
- $this->assertInstanceOf('Test\Files\Mount\FakeObjectStore', $config['arguments']['objectstore']);
- $this->assertArrayHasKey('bucket', $config['arguments']);
- $this->assertEquals('awesomeBucket1', $config['arguments']['bucket']);
+ $objectStore = $arguments['objectstore'];
+ $this->assertInstanceOf(FakeObjectStore::class, $objectStore);
+ $this->assertEquals(['foo' => 'bar', 'bucket' => 'awesomeBucket1', 'multibucket' => true], $objectStore->getArguments());
}
public function testMultiBucketConfigFirst(): void {
- $this->config->expects($this->exactly(2))
- ->method('getSystemValue')
- ->with('objectstore_multibucket')
- ->willReturn([
- 'class' => 'Test\Files\Mount\FakeObjectStore',
- ]);
+ $this->config->method('getSystemValue')
+ ->willReturnCallback(function ($key, $default) {
+ if ($key === 'objectstore_multibucket') {
+ return [
+ 'class' => 'Test\Files\Mount\FakeObjectStore',
+ 'arguments' => [
+ 'foo' => 'bar',
+ 'bucket' => 'myBucketPrefix',
+ ],
+ ];
+ } else {
+ return $default;
+ }
+ });
$this->user->method('getUID')
->willReturn('uid');
@@ -204,11 +210,15 @@ class ObjectHomeMountProviderTest extends \Test\TestCase {
}
public function testMultiBucketConfigFirstFallBackSingle(): void {
- $this->config->expects($this->exactly(2))
+ $this->config
->method('getSystemValue')->willReturnMap([
- ['objectstore_multibucket', '', ''],
- ['objectstore', '', [
+ ['objectstore_multibucket', null, null],
+ ['objectstore', null, [
'class' => 'Test\Files\Mount\FakeObjectStore',
+ 'arguments' => [
+ 'foo' => 'bar',
+ 'bucket' => 'myBucketPrefix',
+ ],
]],
]);
@@ -221,23 +231,41 @@ class ObjectHomeMountProviderTest extends \Test\TestCase {
}
public function testNoObjectStore(): void {
- $this->config->expects($this->exactly(2))
- ->method('getSystemValue')
- ->willReturn('');
+ $this->config->method('getSystemValue')
+ ->willReturnCallback(function ($key, $default) {
+ return $default;
+ });
$mount = $this->provider->getHomeMountForUser($this->user, $this->loader);
$this->assertNull($mount);
}
}
-class FakeObjectStore {
- private $arguments;
-
- public function __construct(array $arguments) {
- $this->arguments = $arguments;
+class FakeObjectStore implements IObjectStore {
+ public function __construct(
+ private array $arguments,
+ ) {
}
public function getArguments() {
return $this->arguments;
}
+
+ public function getStorageId() {
+ }
+
+ public function readObject($urn) {
+ }
+
+ public function writeObject($urn, $stream, ?string $mimetype = null) {
+ }
+
+ public function deleteObject($urn) {
+ }
+
+ public function objectExists($urn) {
+ }
+
+ public function copyObject($from, $to) {
+ }
}
diff --git a/tests/lib/Files/Mount/RootMountProviderTest.php b/tests/lib/Files/Mount/RootMountProviderTest.php
index 2613cfd4b7b..bf29bfa070a 100644
--- a/tests/lib/Files/Mount/RootMountProviderTest.php
+++ b/tests/lib/Files/Mount/RootMountProviderTest.php
@@ -10,11 +10,12 @@ namespace Test\Files\Mount;
use OC\Files\Mount\RootMountProvider;
use OC\Files\ObjectStore\ObjectStoreStorage;
+use OC\Files\ObjectStore\PrimaryObjectStoreConfig;
use OC\Files\ObjectStore\S3;
use OC\Files\Storage\LocalRootStorage;
use OC\Files\Storage\StorageFactory;
+use OCP\App\IAppManager;
use OCP\IConfig;
-use Psr\Log\LoggerInterface;
use Test\TestCase;
/**
@@ -40,8 +41,8 @@ class RootMountProviderTest extends TestCase {
private function getProvider(array $systemConfig): RootMountProvider {
$config = $this->getConfig($systemConfig);
- $provider = new RootMountProvider($config, $this->createMock(LoggerInterface::class));
- return $provider;
+ $objectStoreConfig = new PrimaryObjectStoreConfig($config, $this->createMock(IAppManager::class));
+ return new RootMountProvider($objectStoreConfig, $config);
}
public function testLocal(): void {
diff --git a/tests/lib/Files/Node/FileTest.php b/tests/lib/Files/Node/FileTest.php
index a67c9433663..eec34d156ad 100644
--- a/tests/lib/Files/Node/FileTest.php
+++ b/tests/lib/Files/Node/FileTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -7,6 +8,11 @@
namespace Test\Files\Node;
+use OC\Files\Node\File;
+use OC\Files\Node\Root;
+use OCP\Constants;
+use OCP\Files\NotPermittedException;
+
/**
* Class FileTest
*
@@ -14,12 +20,12 @@ namespace Test\Files\Node;
*
* @package Test\Files\Node
*/
-class FileTest extends NodeTest {
+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);
}
}
@@ -37,11 +43,11 @@ class FileTest extends NodeTest {
public function testGetContent(): void {
/** @var \OC\Files\Node\Root|\PHPUnit\Framework\MockObject\MockObject $root */
- $root = $this->getMockBuilder('\OC\Files\Node\Root')
+ $root = $this->getMockBuilder(Root::class)
->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');
};
@@ -56,18 +62,18 @@ class FileTest extends NodeTest {
$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('\OC\Files\Node\Root')
+ $root = $this->getMockBuilder(Root::class)
->setConstructorArgs([$this->manager, $this->view, $this->user, $this->userMountCache, $this->logger, $this->userManager, $this->eventDispatcher, $this->cacheFactory])
->getMock();
@@ -80,13 +86,13 @@ class FileTest extends NodeTest {
->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();
}
public function testPutContent(): void {
/** @var \OC\Files\Node\Root|\PHPUnit\Framework\MockObject\MockObject $root */
- $root = $this->getMockBuilder('\OC\Files\Node\Root')
+ $root = $this->getMockBuilder(Root::class)
->setConstructorArgs([$this->manager, $this->view, $this->user, $this->userMountCache, $this->logger, $this->userManager, $this->eventDispatcher, $this->cacheFactory])
->getMock();
@@ -97,38 +103,38 @@ class FileTest extends NodeTest {
$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('\OC\Files\Node\Root')
+ $root = $this->getMockBuilder(Root::class)
->setConstructorArgs([$this->manager, $this->view, $this->user, $this->userMountCache, $this->logger, $this->userManager, $this->eventDispatcher, $this->cacheFactory])
->getMock();
$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');
}
public function testGetMimeType(): void {
/** @var \OC\Files\Node\Root|\PHPUnit\Framework\MockObject\MockObject $root */
- $root = $this->getMockBuilder('\OC\Files\Node\Root')
+ $root = $this->getMockBuilder(Root::class)
->setConstructorArgs([$this->manager, $this->view, $this->user, $this->userMountCache, $this->logger, $this->userManager, $this->eventDispatcher, $this->cacheFactory])
->getMock();
@@ -137,7 +143,7 @@ class FileTest extends NodeTest {
->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());
}
@@ -146,7 +152,7 @@ class FileTest extends NodeTest {
fwrite($stream, 'bar');
rewind($stream);
- $root = new \OC\Files\Node\Root(
+ $root = new Root(
$this->manager,
$this->view,
$this->user,
@@ -157,7 +163,7 @@ class FileTest extends NodeTest {
$this->cacheFactory,
);
- $hook = function ($file) {
+ $hook = function ($file): void {
throw new \Exception('Hooks are not supposed to be called');
};
@@ -172,9 +178,9 @@ class FileTest extends NodeTest {
$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));
@@ -183,7 +189,7 @@ class FileTest extends NodeTest {
public function testFOpenWrite(): void {
$stream = fopen('php://memory', 'w+');
- $root = new \OC\Files\Node\Root(
+ $root = new Root(
$this->manager,
$this->view,
$this->user,
@@ -194,7 +200,7 @@ class FileTest extends NodeTest {
$this->cacheFactory,
);
$hooksCalled = 0;
- $hook = function ($file) use (&$hooksCalled) {
+ $hook = function ($file) use (&$hooksCalled): void {
$hooksCalled++;
};
@@ -209,9 +215,9 @@ class FileTest extends NodeTest {
$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');
@@ -222,9 +228,9 @@ class FileTest extends NodeTest {
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,
@@ -234,7 +240,7 @@ class FileTest extends NodeTest {
$this->eventDispatcher,
$this->cacheFactory,
);
- $hook = function ($file) {
+ $hook = function ($file): void {
throw new \Exception('Hooks are not supposed to be called');
};
@@ -243,15 +249,15 @@ class FileTest extends NodeTest {
->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,
@@ -261,24 +267,24 @@ class FileTest extends NodeTest {
$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,
@@ -288,16 +294,16 @@ class FileTest extends NodeTest {
$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 e3edf202f8e..439535cf2c1 100644
--- a/tests/lib/Files/Node/FolderTest.php
+++ b/tests/lib/Files/Node/FolderTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -21,12 +22,17 @@ 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 OC\Files\View;
+use OCP\Constants;
use OCP\Files\Cache\ICacheEntry;
+use OCP\Files\InvalidPathException;
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;
@@ -40,7 +46,7 @@ use PHPUnit\Framework\MockObject\MockObject;
*
* @package Test\Files\Node
*/
-class FolderTest extends NodeTest {
+class FolderTest extends NodeTestCase {
protected function createTestNode($root, $view, $path, array $data = [], $internalPath = '', $storage = null) {
$view->expects($this->any())
->method('getRoot')
@@ -67,7 +73,7 @@ class FolderTest extends NodeTest {
public function testGetDirectoryContent(): void {
$manager = $this->createMock(Manager::class);
/**
- * @var \OC\Files\View | \PHPUnit\Framework\MockObject\MockObject $view
+ * @var View|\PHPUnit\Framework\MockObject\MockObject $view
*/
$root = $this->getMockBuilder(Root::class)
->setConstructorArgs([$manager, $this->view, $this->user, $this->userMountCache, $this->logger, $this->userManager, $this->eventDispatcher, $this->cacheFactory])
@@ -150,7 +156,7 @@ class FolderTest extends NodeTest {
$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 +174,7 @@ class FolderTest extends NodeTest {
$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 +198,7 @@ class FolderTest extends NodeTest {
$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 +212,7 @@ class FolderTest extends NodeTest {
public function testNewFolderNotPermitted(): void {
- $this->expectException(\OCP\Files\NotPermittedException::class);
+ $this->expectException(NotPermittedException::class);
$manager = $this->createMock(Manager::class);
$view = $this->getRootViewMock();
@@ -218,7 +224,7 @@ class FolderTest extends NodeTest {
$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 +242,21 @@ class FolderTest extends NodeTest {
$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 +268,7 @@ class FolderTest extends NodeTest {
$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');
@@ -337,7 +343,7 @@ class FolderTest extends NodeTest {
$manager = $this->createMock(Manager::class);
$view = $this->getRootViewMock();
$root = $this->getMockBuilder(Root::class)
- ->setMethods(['getUser', 'getMountsIn', 'getMount'])
+ ->onlyMethods(['getUser', 'getMountsIn', 'getMount'])
->setConstructorArgs([$manager, $view, $this->user, $this->userMountCache, $this->logger, $this->userManager, $this->eventDispatcher, $this->cacheFactory])
->getMock();
$root->expects($this->any())
@@ -499,10 +505,10 @@ class FolderTest extends NodeTest {
$manager = $this->createMock(Manager::class);
$view = $this->getRootViewMock();
$root = $this->getMockBuilder(Root::class)
- ->setMethods(['getMountsIn', 'getMount'])
+ ->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();
@@ -548,10 +554,10 @@ class FolderTest extends NodeTest {
$manager = $this->createMock(Manager::class);
$view = $this->getRootViewMock();
$root = $this->getMockBuilder(Root::class)
- ->setMethods(['getMountsIn', 'getMount'])
+ ->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();
@@ -593,10 +599,10 @@ class FolderTest extends NodeTest {
$manager = $this->createMock(Manager::class);
$view = $this->getRootViewMock();
$root = $this->getMockBuilder(Root::class)
- ->setMethods(['getMountsIn', 'getMount'])
+ ->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();
@@ -637,10 +643,10 @@ class FolderTest extends NodeTest {
$manager = $this->createMock(Manager::class);
$view = $this->getRootViewMock();
$root = $this->getMockBuilder(Root::class)
- ->setMethods(['getMountsIn', 'getMount'])
+ ->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('');
@@ -681,7 +687,7 @@ class FolderTest extends NodeTest {
$this->assertEquals('/bar/foo/asd/foo/qwerty', $result[1]->getPath());
}
- public function uniqueNameProvider() {
+ public static function uniqueNameProvider(): array {
return [
// input, existing, expected
['foo', [], 'foo'],
@@ -690,15 +696,13 @@ class FolderTest extends NodeTest {
];
}
- /**
- * @dataProvider uniqueNameProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('uniqueNameProvider')]
public function testGetUniqueName($name, $existingFiles, $expected): void {
$manager = $this->createMock(Manager::class);
$folderPath = '/bar/foo';
$view = $this->getRootViewMock();
$root = $this->getMockBuilder(Root::class)
- ->setMethods(['getUser', 'getMountsIn', 'getMount'])
+ ->onlyMethods(['getUser', 'getMountsIn', 'getMount'])
->setConstructorArgs([$manager, $view, $this->user, $this->userMountCache, $this->logger, $this->userManager, $this->eventDispatcher, $this->cacheFactory])
->getMock();
@@ -723,10 +727,10 @@ class FolderTest extends NodeTest {
$view = $this->getRootViewMock();
/** @var \PHPUnit\Framework\MockObject\MockObject|\OC\Files\Node\Root $root */
$root = $this->getMockBuilder(Root::class)
- ->setMethods(['getUser', 'getMountsIn', 'getMount'])
+ ->onlyMethods(['getUser', 'getMountsIn', 'getMount'])
->setConstructorArgs([$manager, $view, $this->user, $this->userMountCache, $this->logger, $this->userManager, $this->eventDispatcher, $this->cacheFactory])
->getMock();
- /** @var \PHPUnit\Framework\MockObject\MockObject|\OC\Files\FileInfo $folderInfo */
+ /** @var \PHPUnit\Framework\MockObject\MockObject|FileInfo $folderInfo */
$folderInfo = $this->getMockBuilder(FileInfo::class)
->disableOriginalConstructor()->getMock();
@@ -753,14 +757,14 @@ class FolderTest extends NodeTest {
'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 +777,7 @@ class FolderTest extends NodeTest {
'mtime' => $baseTime - 600,
'mimetype' => 'text/plain',
'size' => 3,
- 'permissions' => \OCP\Constants::PERMISSION_ALL,
+ 'permissions' => Constants::PERMISSION_ALL,
]);
$node = new Folder($root, $view, $folderPath, $folderInfo);
@@ -792,10 +796,10 @@ class FolderTest extends NodeTest {
$view = $this->getRootViewMock();
/** @var \PHPUnit\Framework\MockObject\MockObject|\OC\Files\Node\Root $root */
$root = $this->getMockBuilder(Root::class)
- ->setMethods(['getUser', 'getMountsIn', 'getMount'])
+ ->onlyMethods(['getUser', 'getMountsIn', 'getMount'])
->setConstructorArgs([$manager, $view, $this->user, $this->userMountCache, $this->logger, $this->userManager, $this->eventDispatcher, $this->cacheFactory])
->getMock();
- /** @var \PHPUnit\Framework\MockObject\MockObject|\OC\Files\FileInfo $folderInfo */
+ /** @var \PHPUnit\Framework\MockObject\MockObject|FileInfo $folderInfo */
$folderInfo = $this->getMockBuilder(FileInfo::class)
->disableOriginalConstructor()->getMock();
@@ -830,7 +834,7 @@ class FolderTest extends NodeTest {
'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 +842,7 @@ class FolderTest extends NodeTest {
'mimetype' => 'text/plain',
'size' => 3,
'parent' => $id1,
- 'permissions' => \OCP\Constants::PERMISSION_ALL,
+ 'permissions' => Constants::PERMISSION_ALL,
]);
$node = new Folder($root, $view, $folderPath, $folderInfo);
@@ -859,10 +863,10 @@ class FolderTest extends NodeTest {
$view = $this->getRootViewMock();
/** @var \PHPUnit\Framework\MockObject\MockObject|\OC\Files\Node\Root $root */
$root = $this->getMockBuilder(Root::class)
- ->setMethods(['getUser', 'getMountsIn', 'getMount'])
+ ->onlyMethods(['getUser', 'getMountsIn', 'getMount'])
->setConstructorArgs([$manager, $view, $this->user, $this->userMountCache, $this->logger, $this->userManager, $this->eventDispatcher, $this->cacheFactory])
->getMock();
- /** @var \PHPUnit\Framework\MockObject\MockObject|\OC\Files\FileInfo $folderInfo */
+ /** @var \PHPUnit\Framework\MockObject\MockObject|FileInfo $folderInfo */
$folderInfo = $this->getMockBuilder(FileInfo::class)
->disableOriginalConstructor()->getMock();
@@ -891,7 +895,7 @@ class FolderTest extends NodeTest {
'mtime' => $baseTime,
'mimetype' => 'text/plain',
'size' => 3,
- 'permissions' => \OCP\Constants::PERMISSION_ALL,
+ 'permissions' => Constants::PERMISSION_ALL,
]);
$cache->put('outside.txt', [
@@ -910,7 +914,7 @@ class FolderTest extends NodeTest {
$this->assertEquals([$id1], $ids);
}
- public function offsetLimitProvider() {
+ public static function offsetLimitProvider(): array {
return [
[0, 10, ['/bar/foo/foo1', '/bar/foo/foo2', '/bar/foo/foo3', '/bar/foo/foo4', '/bar/foo/sub1/foo5', '/bar/foo/sub1/foo6', '/bar/foo/sub2/foo7', '/bar/foo/sub2/foo8'], []],
[0, 5, ['/bar/foo/foo1', '/bar/foo/foo2', '/bar/foo/foo3', '/bar/foo/foo4', '/bar/foo/sub1/foo5'], []],
@@ -931,14 +935,14 @@ class FolderTest extends NodeTest {
}
/**
- * @dataProvider offsetLimitProvider
* @param int $offset
* @param int $limit
* @param string[] $expectedPaths
* @param ISearchOrder[] $ordering
* @throws NotFoundException
- * @throws \OCP\Files\InvalidPathException
+ * @throws InvalidPathException
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('offsetLimitProvider')]
public function testSearchSubStoragesLimitOffset(int $offset, int $limit, array $expectedPaths, array $ordering): void {
if (!$ordering) {
$ordering = [new SearchOrder(ISearchOrder::DIRECTION_ASCENDING, 'fileid')];
diff --git a/tests/lib/Files/Node/HookConnectorTest.php b/tests/lib/Files/Node/HookConnectorTest.php
index 1a3337b9ddc..3f3957bab1d 100644
--- a/tests/lib/Files/Node/HookConnectorTest.php
+++ b/tests/lib/Files/Node/HookConnectorTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -15,6 +16,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 +34,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 +82,15 @@ class HookConnectorTest extends TestCase {
$this->root = new Root(
Filesystem::getMountManager(),
$this->view,
- \OC::$server->getUserManager()->get($this->userId),
- \OC::$server->getUserMountCache(),
+ 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 {
@@ -96,51 +99,51 @@ class HookConnectorTest extends TestCase {
\OC_Util::tearDownFS();
}
- public function viewToNodeProvider() {
+ 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],
@@ -150,8 +153,8 @@ class HookConnectorTest extends TestCase {
/**
* @param callable $operation
* @param string $expectedHook
- * @dataProvider viewToNodeProvider
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('viewToNodeProvider')]
public function testViewToNode(callable $operation, $expectedHook, $expectedLegacyEvent, $expectedEvent): void {
$connector = new HookConnector($this->root, $this->view, $this->eventDispatcher, $this->logger);
$connector->viewToNode();
@@ -159,7 +162,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 +170,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 +178,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;
@@ -195,21 +198,21 @@ class HookConnectorTest extends TestCase {
$this->assertEquals('/' . $this->userId . '/files/test.txt', $newDispatcherNode->getPath());
}
- public function viewToNodeProviderCopyRename() {
+ 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],
@@ -219,8 +222,8 @@ class HookConnectorTest extends TestCase {
/**
* @param callable $operation
* @param string $expectedHook
- * @dataProvider viewToNodeProviderCopyRename
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('viewToNodeProviderCopyRename')]
public function testViewToNodeCopyRename(callable $operation, $expectedHook, $expectedLegacyEvent, $expectedEvent): void {
$connector = new HookConnector($this->root, $this->view, $this->eventDispatcher, $this->logger);
$connector->viewToNode();
@@ -230,7 +233,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 +244,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 +255,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 +286,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 +294,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 +303,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..f059afa1625 100644
--- a/tests/lib/Files/Node/IntegrationTest.php
+++ b/tests/lib/Files/Node/IntegrationTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -8,6 +9,7 @@
namespace Test\Files\Node;
use OC\Files\Node\Root;
+use OC\Files\Storage\Storage;
use OC\Files\Storage\Temporary;
use OC\Files\View;
use OC\Memcache\ArrayCache;
@@ -16,6 +18,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;
@@ -35,19 +38,19 @@ class IntegrationTest extends \Test\TestCase {
private $root;
/**
- * @var \OC\Files\Storage\Storage[]
+ * @var Storage[]
*/
private $storages;
/**
- * @var \OC\Files\View $view
+ * @var View $view
*/
private $view;
protected function setUp(): void {
parent::setUp();
- $manager = \OCP\Server::get(IMountManager::class);
+ $manager = Server::get(IMountManager::class);
\OC_Hook::clear('OC_Filesystem');
@@ -64,7 +67,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/NodeTest.php b/tests/lib/Files/Node/NodeTestCase.php
index db87aa925d3..4aecd0fef11 100644
--- a/tests/lib/Files/Node/NodeTest.php
+++ b/tests/lib/Files/Node/NodeTestCase.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -9,13 +10,22 @@ 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\Storage\Storage;
use OC\Files\View;
use OC\Memcache\ArrayCache;
+use OC\User\User;
+use OCP\Constants;
use OCP\EventDispatcher\IEventDispatcher;
+use OCP\Files\Config\IUserMountCache;
+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;
@@ -27,16 +37,16 @@ use Psr\Log\LoggerInterface;
*
* @package Test\Files\Node
*/
-abstract class NodeTest extends \Test\TestCase {
- /** @var \OC\User\User */
+abstract class NodeTestCase extends \Test\TestCase {
+ /** @var User */
protected $user;
/** @var \OC\Files\Mount\Manager */
protected $manager;
- /** @var \OC\Files\View|\PHPUnit\Framework\MockObject\MockObject */
+ /** @var View|\PHPUnit\Framework\MockObject\MockObject */
protected $view;
/** @var \OC\Files\Node\Root|\PHPUnit\Framework\MockObject\MockObject */
protected $root;
- /** @var \OCP\Files\Config\IUserMountCache|\PHPUnit\Framework\MockObject\MockObject */
+ /** @var IUserMountCache|\PHPUnit\Framework\MockObject\MockObject */
protected $userMountCache;
/** @var LoggerInterface|\PHPUnit\Framework\MockObject\MockObject */
protected $logger;
@@ -71,13 +81,13 @@ abstract class NodeTest extends \Test\TestCase {
->willReturnCallback(function () {
return new ArrayCache();
});
- $this->root = $this->getMockBuilder('\OC\Files\Node\Root')
+ $this->root = $this->getMockBuilder(Root::class)
->setConstructorArgs([$this->manager, $this->view, $this->user, $this->userMountCache, $this->logger, $this->userManager, $this->eventDispatcher, $this->cacheFactory])
->getMock();
}
/**
- * @return \OC\Files\View | \PHPUnit\Framework\MockObject\MockObject $view
+ * @return View|\PHPUnit\Framework\MockObject\MockObject $view
*/
protected function getRootViewMock() {
$view = $this->createMock(View::class);
@@ -138,7 +148,7 @@ abstract class NodeTest 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())
@@ -155,7 +165,7 @@ abstract class NodeTest 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());
@@ -166,7 +176,7 @@ abstract class NodeTest 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());
@@ -175,7 +185,7 @@ abstract class NodeTest extends \Test\TestCase {
$hooksRun++;
};
- $root = new \OC\Files\Node\Root(
+ $root = new Root(
$this->manager,
$this->view,
$this->user,
@@ -192,7 +202,7 @@ abstract class NodeTest 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())
@@ -206,7 +216,7 @@ abstract class NodeTest extends \Test\TestCase {
public function testDeleteNotPermitted(): void {
- $this->expectException(\OCP\Files\NotPermittedException::class);
+ $this->expectException(NotPermittedException::class);
$this->root->expects($this->any())
->method('getUser')
@@ -215,7 +225,7 @@ abstract class NodeTest 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();
@@ -334,7 +344,7 @@ abstract class NodeTest extends \Test\TestCase {
->method('getUser')
->willReturn($this->user);
/**
- * @var \OC\Files\Storage\Storage | \PHPUnit\Framework\MockObject\MockObject $storage
+ * @var Storage|\PHPUnit\Framework\MockObject\MockObject $storage
*/
$storage = $this->getMockBuilder('\OC\Files\Storage\Storage')
->disableOriginalConstructor()
@@ -358,7 +368,7 @@ abstract class NodeTest extends \Test\TestCase {
->method('getUser')
->willReturn($this->user);
/**
- * @var \OC\Files\Storage\Storage | \PHPUnit\Framework\MockObject\MockObject $storage
+ * @var Storage|\PHPUnit\Framework\MockObject\MockObject $storage
*/
$storage = $this->getMockBuilder('\OC\Files\Storage\Storage')
->disableOriginalConstructor()
@@ -396,7 +406,7 @@ abstract class NodeTest 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);
@@ -409,7 +419,7 @@ abstract class NodeTest 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++;
@@ -418,13 +428,13 @@ abstract class NodeTest 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,
@@ -445,7 +455,7 @@ abstract class NodeTest 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);
@@ -454,7 +464,7 @@ abstract class NodeTest extends \Test\TestCase {
public function testTouchNotPermitted(): void {
- $this->expectException(\OCP\Files\NotPermittedException::class);
+ $this->expectException(NotPermittedException::class);
$this->root->expects($this->any())
->method('getUser')
@@ -463,7 +473,7 @@ abstract class NodeTest 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);
@@ -471,7 +481,7 @@ abstract class NodeTest 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();
@@ -485,10 +495,10 @@ abstract class NodeTest 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')
@@ -504,10 +514,10 @@ abstract class NodeTest 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
+ * @var Storage|\PHPUnit\Framework\MockObject\MockObject $storage
*/
$storage = $this->createMock('\OC\Files\Storage\Storage');
@@ -519,10 +529,10 @@ abstract class NodeTest 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')
@@ -535,7 +545,7 @@ abstract class NodeTest extends \Test\TestCase {
public function testCopyNoParent(): void {
- $this->expectException(\OCP\Files\NotFoundException::class);
+ $this->expectException(NotFoundException::class);
$this->view->expects($this->never())
->method('copy');
@@ -545,20 +555,20 @@ abstract class NodeTest 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')
@@ -577,10 +587,10 @@ abstract class NodeTest 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')
@@ -592,7 +602,7 @@ abstract class NodeTest extends \Test\TestCase {
$this->assertEquals('/bar/asd', $node->getPath());
}
- public function moveOrCopyProvider() {
+ public static function moveOrCopyProvider(): array {
return [
['move', 'rename', 'preRename', 'postRename'],
['copy', 'copy', 'preCopy', 'postCopy'],
@@ -600,17 +610,17 @@ abstract class NodeTest extends \Test\TestCase {
}
/**
- * @dataProvider moveOrCopyProvider
* @param string $operationMethod
* @param string $viewMethod
* @param string $preHookName
* @param string $postHookName
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('moveOrCopyProvider')]
public function testMoveCopyHooks($operationMethod, $viewMethod, $preHookName, $postHookName): void {
/** @var IRootFolder|\PHPUnit\Framework\MockObject\MockObject $root */
- $root = $this->getMockBuilder('\OC\Files\Node\Root')
+ $root = $this->getMockBuilder(Root::class)
->setConstructorArgs([$this->manager, $this->view, $this->user, $this->userMountCache, $this->logger, $this->userManager, $this->eventDispatcher, $this->cacheFactory])
- ->setMethods(['get'])
+ ->onlyMethods(['get'])
->getMock();
$this->view->expects($this->any())
@@ -620,13 +630,13 @@ abstract class NodeTest 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())
@@ -635,7 +645,7 @@ abstract class NodeTest 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);
@@ -643,7 +653,7 @@ abstract class NodeTest 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);
@@ -652,13 +662,13 @@ abstract class NodeTest 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++;
};
@@ -675,17 +685,17 @@ abstract class NodeTest 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')
@@ -697,10 +707,10 @@ abstract class NodeTest 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
+ * @var Storage|\PHPUnit\Framework\MockObject\MockObject $storage
*/
$storage = $this->createMock('\OC\Files\Storage\Storage');
@@ -712,20 +722,20 @@ abstract class NodeTest 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')
@@ -737,7 +747,7 @@ abstract class NodeTest extends \Test\TestCase {
public function testMoveFailed(): void {
- $this->expectException(\OCP\Files\NotPermittedException::class);
+ $this->expectException(NotPermittedException::class);
$this->view->expects($this->any())
->method('rename')
@@ -746,10 +756,10 @@ abstract class NodeTest 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')
@@ -760,7 +770,7 @@ abstract class NodeTest extends \Test\TestCase {
public function testCopyFailed(): void {
- $this->expectException(\OCP\Files\NotPermittedException::class);
+ $this->expectException(NotPermittedException::class);
$this->view->expects($this->any())
->method('copy')
@@ -769,10 +779,10 @@ abstract class NodeTest 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..d90e6a2cc6e 100644
--- a/tests/lib/Files/Node/RootTest.php
+++ b/tests/lib/Files/Node/RootTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -10,10 +11,17 @@ 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\Storage\Storage;
use OC\Files\View;
use OC\Memcache\ArrayCache;
+use OC\User\NoUserException;
+use OC\User\User;
use OCP\Cache\CappedMemoryCache;
use OCP\EventDispatcher\IEventDispatcher;
+use OCP\Files\Config\IUserMountCache;
+use OCP\Files\NotFoundException;
+use OCP\Files\NotPermittedException;
use OCP\ICacheFactory;
use OCP\IUser;
use OCP\IUserManager;
@@ -25,11 +33,11 @@ use Psr\Log\LoggerInterface;
* @package Test\Files\Node
*/
class RootTest extends \Test\TestCase {
- /** @var \OC\User\User */
+ /** @var User */
private $user;
/** @var \OC\Files\Mount\Manager */
private $manager;
- /** @var \OCP\Files\Config\IUserMountCache|\PHPUnit\Framework\MockObject\MockObject */
+ /** @var IUserMountCache|\PHPUnit\Framework\MockObject\MockObject */
private $userMountCache;
/** @var LoggerInterface|\PHPUnit\Framework\MockObject\MockObject */
private $logger;
@@ -61,7 +69,7 @@ class RootTest extends \Test\TestCase {
}
/**
- * @return \OC\Files\View | \PHPUnit\Framework\MockObject\MockObject $view
+ * @return View|\PHPUnit\Framework\MockObject\MockObject $view
*/
protected function getRootViewMock() {
$view = $this->createMock(View::class);
@@ -77,13 +85,13 @@ class RootTest extends \Test\TestCase {
public function testGet(): void {
/**
- * @var \OC\Files\Storage\Storage $storage
+ * @var Storage $storage
*/
$storage = $this->getMockBuilder('\OC\Files\Storage\Storage')
->disableOriginalConstructor()
->getMock();
$view = $this->getRootViewMock();
- $root = new \OC\Files\Node\Root(
+ $root = new Root(
$this->manager,
$view,
$this->user,
@@ -107,16 +115,16 @@ 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
+ * @var Storage $storage
*/
$storage = $this->getMockBuilder('\OC\Files\Storage\Storage')
->disableOriginalConstructor()
->getMock();
$view = $this->getRootViewMock();
- $root = new \OC\Files\Node\Root(
+ $root = new Root(
$this->manager,
$view,
$this->user,
@@ -138,10 +146,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 +165,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 +183,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 +222,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 c82ed988434..52d2b9e8657 100644
--- a/tests/lib/Files/ObjectStore/AzureTest.php
+++ b/tests/lib/Files/ObjectStore/AzureTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2018 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
@@ -7,13 +8,15 @@
namespace Test\Files\ObjectStore;
use OC\Files\ObjectStore\Azure;
+use OCP\IConfig;
+use OCP\Server;
/**
* @group PRIMARY-azure
*/
-class AzureTest extends ObjectStoreTest {
+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/FailDeleteObjectStore.php b/tests/lib/Files/ObjectStore/FailDeleteObjectStore.php
index b84ee1a1b64..767125d42aa 100644
--- a/tests/lib/Files/ObjectStore/FailDeleteObjectStore.php
+++ b/tests/lib/Files/ObjectStore/FailDeleteObjectStore.php
@@ -11,10 +11,9 @@ namespace Test\Files\ObjectStore;
use OCP\Files\ObjectStore\IObjectStore;
class FailDeleteObjectStore implements IObjectStore {
- private $objectStore;
-
- public function __construct(IObjectStore $objectStore) {
- $this->objectStore = $objectStore;
+ public function __construct(
+ private IObjectStore $objectStore,
+ ) {
}
public function getStorageId() {
diff --git a/tests/lib/Files/ObjectStore/FailWriteObjectStore.php b/tests/lib/Files/ObjectStore/FailWriteObjectStore.php
index b84b123244e..924bbdada4f 100644
--- a/tests/lib/Files/ObjectStore/FailWriteObjectStore.php
+++ b/tests/lib/Files/ObjectStore/FailWriteObjectStore.php
@@ -11,10 +11,9 @@ namespace Test\Files\ObjectStore;
use OCP\Files\ObjectStore\IObjectStore;
class FailWriteObjectStore implements IObjectStore {
- private $objectStore;
-
- public function __construct(IObjectStore $objectStore) {
- $this->objectStore = $objectStore;
+ public function __construct(
+ private IObjectStore $objectStore,
+ ) {
}
public function getStorageId() {
diff --git a/tests/lib/Files/ObjectStore/LocalTest.php b/tests/lib/Files/ObjectStore/LocalTest.php
index 99c5b61534f..d3e9ad56164 100644
--- a/tests/lib/Files/ObjectStore/LocalTest.php
+++ b/tests/lib/Files/ObjectStore/LocalTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
@@ -8,10 +9,11 @@ namespace Test\Files\ObjectStore;
use OC\Files\ObjectStore\StorageObjectStore;
use OC\Files\Storage\Temporary;
+use OCP\Files\ObjectStore\IObjectStore;
-class LocalTest extends ObjectStoreTest {
+class LocalTest extends ObjectStoreTestCase {
/**
- * @return \OCP\Files\ObjectStore\IObjectStore
+ * @return IObjectStore
*/
protected function getInstance() {
$storage = new Temporary();
diff --git a/tests/lib/Files/ObjectStore/MapperTest.php b/tests/lib/Files/ObjectStore/MapperTest.php
index 15a2d497fc3..6448d5ce1f5 100644
--- a/tests/lib/Files/ObjectStore/MapperTest.php
+++ b/tests/lib/Files/ObjectStore/MapperTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -29,7 +30,7 @@ class MapperTest extends \Test\TestCase {
$this->mapper = new Mapper($this->user, $this->config);
}
- public function dataGetBucket() {
+ public static function dataGetBucket(): array {
return [
['user', 64, 0, '17'],
['USER', 64, 0, '0'],
@@ -42,11 +43,11 @@ class MapperTest extends \Test\TestCase {
}
/**
- * @dataProvider dataGetBucket
* @param string $username
* @param int $numBuckets
* @param string $expectedBucket
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataGetBucket')]
public function testGetBucket($username, $numBuckets, $bucketShift, $expectedBucket): void {
$this->user->expects($this->once())
->method('getUID')
diff --git a/tests/lib/Files/ObjectStore/ObjectStoreScannerTest.php b/tests/lib/Files/ObjectStore/ObjectStoreScannerTest.php
index 11c913cd232..ea6ac682c70 100644
--- a/tests/lib/Files/ObjectStore/ObjectStoreScannerTest.php
+++ b/tests/lib/Files/ObjectStore/ObjectStoreScannerTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2023 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
diff --git a/tests/lib/Files/ObjectStore/ObjectStoreStorageTest.php b/tests/lib/Files/ObjectStore/ObjectStoreStorageTest.php
index 3dbdc3afc27..3387808445a 100644
--- a/tests/lib/Files/ObjectStore/ObjectStoreStorageTest.php
+++ b/tests/lib/Files/ObjectStore/ObjectStoreStorageTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -10,6 +11,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;
@@ -71,9 +73,7 @@ class ObjectStoreStorageTest extends Storage {
$this->markTestSkipped('Detecting external changes is not supported on object storages');
}
- /**
- * @dataProvider copyAndMoveProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('copyAndMoveProvider')]
public function testMove($source, $target): void {
$this->initSourceAndTarget($source);
$sourceId = $this->instance->getCache()->getId(ltrim($source, '/'));
@@ -231,13 +231,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,12 +254,25 @@ 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 {
+ $cache = $this->instance->getCache();
+
+ $this->instance->mkdir('source');
+ $this->instance->file_put_contents('source/test.txt', 'foo');
+ $this->instance->getUpdater()->update('source/test.txt');
+ $this->assertEquals(3, $cache->get('source')->getSize());
+
+ $this->assertTrue($this->instance->copy('source', 'target'));
+
+ $this->assertEquals(3, $cache->get('target')->getSize());
}
}
diff --git a/tests/lib/Files/ObjectStore/ObjectStoreStoragesDifferentBucketTest.php b/tests/lib/Files/ObjectStore/ObjectStoreStoragesDifferentBucketTest.php
index a0e18a5557b..d39426ee821 100644
--- a/tests/lib/Files/ObjectStore/ObjectStoreStoragesDifferentBucketTest.php
+++ b/tests/lib/Files/ObjectStore/ObjectStoreStoragesDifferentBucketTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -9,19 +10,20 @@ namespace Test\Files\ObjectStore;
use OC\Files\ObjectStore\StorageObjectStore;
use OC\Files\Storage\Temporary;
-use Test\Files\Storage\StoragesTest;
+use OCP\Files\ObjectStore\IObjectStore;
+use Test\Files\Storage\StoragesTestCase;
/**
* @group DB
*/
-class ObjectStoreStoragesDifferentBucketTest extends StoragesTest {
+class ObjectStoreStoragesDifferentBucketTest extends StoragesTestCase {
/**
- * @var \OCP\Files\ObjectStore\IObjectStore
+ * @var IObjectStore
*/
private $objectStore1;
/**
- * @var \OCP\Files\ObjectStore\IObjectStore
+ * @var IObjectStore
*/
private $objectStore2;
diff --git a/tests/lib/Files/ObjectStore/ObjectStoreStoragesSameBucketTest.php b/tests/lib/Files/ObjectStore/ObjectStoreStoragesSameBucketTest.php
index 19a1f4b7bc5..4e42668cd3f 100644
--- a/tests/lib/Files/ObjectStore/ObjectStoreStoragesSameBucketTest.php
+++ b/tests/lib/Files/ObjectStore/ObjectStoreStoragesSameBucketTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -9,14 +10,15 @@ namespace Test\Files\ObjectStore;
use OC\Files\ObjectStore\StorageObjectStore;
use OC\Files\Storage\Temporary;
-use Test\Files\Storage\StoragesTest;
+use OCP\Files\ObjectStore\IObjectStore;
+use Test\Files\Storage\StoragesTestCase;
/**
* @group DB
*/
-class ObjectStoreStoragesSameBucketTest extends StoragesTest {
+class ObjectStoreStoragesSameBucketTest extends StoragesTestCase {
/**
- * @var \OCP\Files\ObjectStore\IObjectStore
+ * @var IObjectStore
*/
private $objectStore;
diff --git a/tests/lib/Files/ObjectStore/ObjectStoreTest.php b/tests/lib/Files/ObjectStore/ObjectStoreTestCase.php
index 4a4f85dfb91..03e7b9545e0 100644
--- a/tests/lib/Files/ObjectStore/ObjectStoreTest.php
+++ b/tests/lib/Files/ObjectStore/ObjectStoreTestCase.php
@@ -7,14 +7,17 @@
namespace Test\Files\ObjectStore;
+use OCP\Files\ObjectStore\IObjectStore;
use Test\TestCase;
-abstract class ObjectStoreTest extends TestCase {
+abstract class ObjectStoreTestCase extends TestCase {
/** @var string[] */
private $cleanup = [];
+ private $instance = null;
+
/**
- * @return \OCP\Files\ObjectStore\IObjectStore
+ * @return IObjectStore
*/
abstract protected function getInstance();
@@ -22,13 +25,20 @@ abstract class ObjectStoreTest extends TestCase {
$this->cleanup[] = $urn;
}
- public function tearDown(): void {
- parent::tearDown();
+ public function setUp(): void {
+ parent::setUp();
- $instance = $this->getInstance();
- foreach ($this->cleanup as $urn) {
- $instance->deleteObject($urn);
+ $this->instance = $this->getInstance();
+ }
+
+ public function tearDown(): void {
+ if ($this->instance) {
+ foreach ($this->cleanup as $urn) {
+ $this->instance->deleteObject($urn);
+ }
}
+
+ parent::tearDown();
}
protected function stringToStream($data) {
diff --git a/tests/lib/Files/ObjectStore/S3Test.php b/tests/lib/Files/ObjectStore/S3Test.php
index 1501f575f9a..2915ada0aab 100644
--- a/tests/lib/Files/ObjectStore/S3Test.php
+++ b/tests/lib/Files/ObjectStore/S3Test.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
@@ -8,6 +9,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) {
@@ -44,7 +47,7 @@ class NonSeekableStream extends Wrapper {
/**
* @group PRIMARY-s3
*/
-class S3Test extends ObjectStoreTest {
+class S3Test extends ObjectStoreTestCase {
public function setUp(): void {
parent::setUp();
$s3 = $this->getInstance();
@@ -52,7 +55,7 @@ class S3Test extends ObjectStoreTest {
}
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');
}
@@ -126,13 +129,13 @@ class S3Test extends ObjectStoreTest {
}
/** File size to upload in bytes */
- public function dataFileSizes() {
+ public static function dataFileSizes(): array {
return [
[1000000], [2000000], [5242879], [5242880], [5242881], [10000000]
];
}
- /** @dataProvider dataFileSizes */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataFileSizes')]
public function testFileSizes($size): void {
if (str_starts_with(PHP_VERSION, '8.3') && getenv('CI')) {
$this->markTestSkipped('Test is unreliable and skipped on 8.3');
diff --git a/tests/lib/Files/ObjectStore/SwiftTest.php b/tests/lib/Files/ObjectStore/SwiftTest.php
index 8a34d25e57b..3f919c0dd48 100644
--- a/tests/lib/Files/ObjectStore/SwiftTest.php
+++ b/tests/lib/Files/ObjectStore/SwiftTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -8,16 +9,19 @@
namespace Test\Files\ObjectStore;
use OC\Files\ObjectStore\Swift;
+use OCP\Files\ObjectStore\IObjectStore;
+use OCP\IConfig;
+use OCP\Server;
/**
* @group PRIMARY-swift
*/
-class SwiftTest extends ObjectStoreTest {
+class SwiftTest extends ObjectStoreTestCase {
/**
- * @return \OCP\Files\ObjectStore\IObjectStore
+ * @return 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 fcbe0a6957f..e13dbe4f207 100644
--- a/tests/lib/Files/PathVerificationTest.php
+++ b/tests/lib/Files/PathVerificationTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -10,6 +11,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
@@ -20,7 +23,7 @@ use OCP\Files\InvalidPathException;
*/
class PathVerificationTest extends \Test\TestCase {
/**
- * @var \OC\Files\View
+ * @var View
*/
private $view;
@@ -31,7 +34,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);
@@ -39,34 +42,30 @@ class PathVerificationTest extends \Test\TestCase {
}
- /**
- * @dataProvider providesEmptyFiles
- */
+ #[\PHPUnit\Framework\Attributes\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);
}
- public function providesEmptyFiles() {
+ public static function providesEmptyFiles(): array {
return [
[''],
[' '],
];
}
- /**
- * @dataProvider providesDotFiles
- */
+ #[\PHPUnit\Framework\Attributes\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);
}
- public function providesDotFiles() {
+ public static function providesDotFiles(): array {
return [
['.'],
['..'],
@@ -79,11 +78,9 @@ class PathVerificationTest extends \Test\TestCase {
];
}
- /**
- * @dataProvider providesAstralPlane
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('providesAstralPlane')]
public function testPathVerificationAstralPlane($fileName): void {
- $connection = \OC::$server->getDatabaseConnection();
+ $connection = Server::get(IDBConnection::class);
if (!$connection->supports4ByteText()) {
$this->expectException(InvalidPathException::class);
@@ -95,7 +92,7 @@ class PathVerificationTest extends \Test\TestCase {
$this->view->verifyPath('', $fileName);
}
- public function providesAstralPlane() {
+ public static function providesAstralPlane(): array {
return [
// this is the monkey emoji - http://en.wikipedia.org/w/index.php?title=%F0%9F%90%B5&redirect=no
['🐵'],
@@ -106,9 +103,7 @@ class PathVerificationTest extends \Test\TestCase {
];
}
- /**
- * @dataProvider providesValidPosixPaths
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('providesValidPosixPaths')]
public function testPathVerificationValidPaths($fileName): void {
$storage = new Local(['datadir' => '']);
@@ -117,7 +112,7 @@ class PathVerificationTest extends \Test\TestCase {
$this->addToAssertionCount(1);
}
- public function providesValidPosixPaths() {
+ public static function providesValidPosixPaths(): array {
return [
['simple'],
['simple.txt'],
diff --git a/tests/lib/Files/Search/QueryOptimizer/CombinedTests.php b/tests/lib/Files/Search/QueryOptimizer/CombinedTests.php
index e6cb11a7eba..665224cb63e 100644
--- a/tests/lib/Files/Search/QueryOptimizer/CombinedTests.php
+++ b/tests/lib/Files/Search/QueryOptimizer/CombinedTests.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2023 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
diff --git a/tests/lib/Files/Search/QueryOptimizer/FlattenNestedBoolTest.php b/tests/lib/Files/Search/QueryOptimizer/FlattenNestedBoolTest.php
index 6777047d68b..1d43541a5a0 100644
--- a/tests/lib/Files/Search/QueryOptimizer/FlattenNestedBoolTest.php
+++ b/tests/lib/Files/Search/QueryOptimizer/FlattenNestedBoolTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2023 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
diff --git a/tests/lib/Files/Search/QueryOptimizer/MergeDistributiveOperationsTest.php b/tests/lib/Files/Search/QueryOptimizer/MergeDistributiveOperationsTest.php
index 4f933d0c371..9aaa7030aac 100644
--- a/tests/lib/Files/Search/QueryOptimizer/MergeDistributiveOperationsTest.php
+++ b/tests/lib/Files/Search/QueryOptimizer/MergeDistributiveOperationsTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2023 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
diff --git a/tests/lib/Files/Search/QueryOptimizer/OrEqualsToInTest.php b/tests/lib/Files/Search/QueryOptimizer/OrEqualsToInTest.php
index 8b1c3b992b2..d51fe3d0d16 100644
--- a/tests/lib/Files/Search/QueryOptimizer/OrEqualsToInTest.php
+++ b/tests/lib/Files/Search/QueryOptimizer/OrEqualsToInTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2023 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
diff --git a/tests/lib/Files/Search/SearchIntegrationTest.php b/tests/lib/Files/Search/SearchIntegrationTest.php
index 0ca67285fd5..e3e99bbfadd 100644
--- a/tests/lib/Files/Search/SearchIntegrationTest.php
+++ b/tests/lib/Files/Search/SearchIntegrationTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
diff --git a/tests/lib/Files/SimpleFS/SimpleFileTest.php b/tests/lib/Files/SimpleFS/SimpleFileTest.php
index d0676eae70f..6ce5ddad351 100644
--- a/tests/lib/Files/SimpleFS/SimpleFileTest.php
+++ b/tests/lib/Files/SimpleFS/SimpleFileTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
diff --git a/tests/lib/Files/SimpleFS/SimpleFolderTest.php b/tests/lib/Files/SimpleFS/SimpleFolderTest.php
index 6897aab1f02..50038b286a9 100644
--- a/tests/lib/Files/SimpleFS/SimpleFolderTest.php
+++ b/tests/lib/Files/SimpleFS/SimpleFolderTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
diff --git a/tests/lib/Files/Storage/CommonTest.php b/tests/lib/Files/Storage/CommonTest.php
index b51b35be8f9..c5ff6bb0b5f 100644
--- a/tests/lib/Files/Storage/CommonTest.php
+++ b/tests/lib/Files/Storage/CommonTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -9,10 +10,12 @@ namespace Test\Files\Storage;
use OC\Files\Storage\Wrapper\Jail;
use OC\Files\Storage\Wrapper\Wrapper;
+use OCP\Files;
use OCP\Files\IFilenameValidator;
use OCP\Files\InvalidCharacterInPathException;
use OCP\Files\InvalidPathException;
use OCP\ITempManager;
+use OCP\Server;
use PHPUnit\Framework\MockObject\MockObject;
/**
@@ -32,12 +35,12 @@ 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]);
}
protected function tearDown(): void {
- \OC_Helper::rmdirr($this->tmpDir);
+ Files::rmdirr($this->tmpDir);
$this->restoreService(IFilenameValidator::class);
parent::tearDown();
}
diff --git a/tests/lib/Files/Storage/CopyDirectoryTest.php b/tests/lib/Files/Storage/CopyDirectoryTest.php
index e434c6b787f..b593b7c984f 100644
--- a/tests/lib/Files/Storage/CopyDirectoryTest.php
+++ b/tests/lib/Files/Storage/CopyDirectoryTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -7,6 +8,7 @@
namespace Test\Files\Storage;
+use OC\Files\Storage\PolyFill\CopyDirectory;
use OC\Files\Storage\Temporary;
class StorageNoRecursiveCopy extends Temporary {
@@ -19,7 +21,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 b6d0f1aa85a..84a9816cb0c 100644
--- a/tests/lib/Files/Storage/HomeTest.php
+++ b/tests/lib/Files/Storage/HomeTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -7,20 +8,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() {
@@ -48,21 +50,21 @@ class HomeTest extends Storage {
private $userId;
/**
- * @var \OC\User\User $user
+ * @var User $user
*/
private $user;
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 {
- \OC_Helper::rmdirr($this->tmpDir);
+ Files::rmdirr($this->tmpDir);
parent::tearDown();
}
diff --git a/tests/lib/Files/Storage/LocalTest.php b/tests/lib/Files/Storage/LocalTest.php
index 65bc538ef17..89449a51351 100644
--- a/tests/lib/Files/Storage/LocalTest.php
+++ b/tests/lib/Files/Storage/LocalTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -7,7 +8,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
@@ -25,12 +32,12 @@ 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 {
- \OC_Helper::rmdirr($this->tmpDir);
+ Files::rmdirr($this->tmpDir);
parent::tearDown();
}
@@ -54,19 +61,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';
@@ -76,7 +83,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');
}
@@ -90,7 +97,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);
@@ -128,12 +135,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 36d70965848..51bb5b7c8ad 100644
--- a/tests/lib/Files/Storage/Storage.php
+++ b/tests/lib/Files/Storage/Storage.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -8,6 +9,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;
@@ -49,9 +51,7 @@ abstract class Storage extends \Test\TestCase {
$this->assertTrue($this->instance->test());
}
- /**
- * @dataProvider directoryProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('directoryProvider')]
public function testDirectories($directory): void {
$this->assertFalse($this->instance->file_exists('/' . $directory));
@@ -108,7 +108,7 @@ abstract class Storage extends \Test\TestCase {
$this->assertEquals([], $content);
}
- public function fileNameProvider() {
+ public static function fileNameProvider(): array {
return [
['file.txt'],
[' file.txt'],
@@ -119,7 +119,7 @@ abstract class Storage extends \Test\TestCase {
];
}
- public function directoryProvider() {
+ public static function directoryProvider(): array {
return [
['folder'],
[' folder'],
@@ -130,7 +130,7 @@ abstract class Storage extends \Test\TestCase {
];
}
- public function loremFileProvider() {
+ public static function loremFileProvider(): array {
$root = \OC::$SERVERROOT . '/tests/data/';
return [
// small file
@@ -142,9 +142,8 @@ abstract class Storage extends \Test\TestCase {
/**
* test the various uses of file_get_contents and file_put_contents
- *
- * @dataProvider loremFileProvider
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('loremFileProvider')]
public function testGetPutContents($sourceFile): void {
$sourceText = file_get_contents($sourceFile);
@@ -179,7 +178,7 @@ abstract class Storage extends \Test\TestCase {
}
- public function copyAndMoveProvider() {
+ public static function copyAndMoveProvider(): array {
return [
['/source.txt', '/target.txt'],
['/source.txt', '/target with space.txt'],
@@ -210,9 +209,7 @@ abstract class Storage extends \Test\TestCase {
);
}
- /**
- * @dataProvider copyAndMoveProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('copyAndMoveProvider')]
public function testCopy($source, $target): void {
$this->initSourceAndTarget($source);
@@ -223,9 +220,7 @@ abstract class Storage extends \Test\TestCase {
$this->assertTrue($this->instance->file_exists($source), $source . ' was deleted');
}
- /**
- * @dataProvider copyAndMoveProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('copyAndMoveProvider')]
public function testMove($source, $target): void {
$this->initSourceAndTarget($source);
@@ -237,9 +232,7 @@ abstract class Storage extends \Test\TestCase {
$this->assertSameAsLorem($target);
}
- /**
- * @dataProvider copyAndMoveProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('copyAndMoveProvider')]
public function testCopyOverwrite($source, $target): void {
$this->initSourceAndTarget($source, $target);
@@ -251,9 +244,7 @@ abstract class Storage extends \Test\TestCase {
$this->assertSameAsLorem($source);
}
- /**
- * @dataProvider copyAndMoveProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('copyAndMoveProvider')]
public function testMoveOverwrite($source, $target): void {
$this->initSourceAndTarget($source, $target);
@@ -327,7 +318,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';
@@ -350,9 +341,7 @@ abstract class Storage extends \Test\TestCase {
$this->assertFalse($this->instance->file_exists('/lorem.txt'));
}
- /**
- * @dataProvider fileNameProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('fileNameProvider')]
public function testFOpen($fileName): void {
$textFile = \OC::$SERVERROOT . '/tests/data/lorem.txt';
@@ -414,7 +403,7 @@ abstract class Storage extends \Test\TestCase {
$this->assertFalse($this->instance->file_exists('folder'));
}
- public function hashProvider() {
+ public static function hashProvider(): array {
return [
['Foobar', 'md5'],
['Foobar', 'sha1'],
@@ -422,9 +411,7 @@ abstract class Storage extends \Test\TestCase {
];
}
- /**
- * @dataProvider hashProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('hashProvider')]
public function testHash($data, $type): void {
$this->instance->file_put_contents('hash.txt', $data);
$this->assertEquals(hash($type, $data), $this->instance->hash($type, 'hash.txt'));
@@ -557,7 +544,7 @@ abstract class Storage extends \Test\TestCase {
$this->instance->copy('source', 'target');
- $this->assertFalse($this->instance->file_exists('target/test2.txt'));
+ $this->assertFalse($this->instance->file_exists('target/test2.txt'), 'File target/test2.txt should no longer exist, but does');
$this->assertEquals('foo', $this->instance->file_get_contents('target/test1.txt'));
}
@@ -578,9 +565,7 @@ abstract class Storage extends \Test\TestCase {
$this->assertFalse($this->instance->instanceOfStorage('\OC'));
}
- /**
- * @dataProvider copyAndMoveProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('copyAndMoveProvider')]
public function testCopyFromSameStorage($source, $target): void {
$this->initSourceAndTarget($source);
diff --git a/tests/lib/Files/Storage/StorageFactoryTest.php b/tests/lib/Files/Storage/StorageFactoryTest.php
index 83e8a7bf6eb..0bb9cbf5824 100644
--- a/tests/lib/Files/Storage/StorageFactoryTest.php
+++ b/tests/lib/Files/Storage/StorageFactoryTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -8,6 +9,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 +28,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 +41,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 +52,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/StoragesTest.php b/tests/lib/Files/Storage/StoragesTestCase.php
index 3f8198d331d..565ff1ddfda 100644
--- a/tests/lib/Files/Storage/StoragesTest.php
+++ b/tests/lib/Files/Storage/StoragesTestCase.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -7,16 +8,17 @@
namespace Test\Files\Storage;
+use OC\Files\Storage\Storage;
use Test\TestCase;
-abstract class StoragesTest extends TestCase {
+abstract class StoragesTestCase extends TestCase {
/**
- * @var \OC\Files\Storage\Storage
+ * @var Storage
*/
protected $storage1;
/**
- * @var \OC\Files\Storage\Storage
+ * @var Storage
*/
protected $storage2;
diff --git a/tests/lib/Files/Storage/Wrapper/AvailabilityTest.php b/tests/lib/Files/Storage/Wrapper/AvailabilityTest.php
index 29277772358..d890081cbb6 100644
--- a/tests/lib/Files/Storage/Wrapper/AvailabilityTest.php
+++ b/tests/lib/Files/Storage/Wrapper/AvailabilityTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -53,7 +54,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 +83,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 +98,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 +107,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 +149,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 d8b03a891c2..cb6b6de0fb7 100644
--- a/tests/lib/Files/Storage/Wrapper/EncodingTest.php
+++ b/tests/lib/Files/Storage/Wrapper/EncodingTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -7,19 +8,22 @@
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';
/**
- * @var \OC\Files\Storage\Temporary
+ * @var Temporary
*/
private $sourceStorage;
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
]);
}
@@ -29,42 +33,38 @@ class EncodingTest extends \Test\Files\Storage\Storage {
parent::tearDown();
}
- public function directoryProvider() {
+ public static function directoryProvider(): array {
$a = parent::directoryProvider();
$a[] = [self::NFC_NAME];
return $a;
}
- public function fileNameProvider() {
+ public static function fileNameProvider(): array {
$a = parent::fileNameProvider();
$a[] = [self::NFD_NAME . '.txt'];
return $a;
}
- public function copyAndMoveProvider() {
+ public static function copyAndMoveProvider(): array {
$a = parent::copyAndMoveProvider();
$a[] = [self::NFD_NAME . '.txt', self::NFC_NAME . '-renamed.txt'];
return $a;
}
- public function accessNameProvider() {
+ public static function accessNameProvider(): array {
return [
[self::NFD_NAME],
[self::NFC_NAME],
];
}
- /**
- * @dataProvider accessNameProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('accessNameProvider')]
public function testFputEncoding($accessName): void {
$this->sourceStorage->file_put_contents(self::NFD_NAME, 'bar');
$this->assertEquals('bar', $this->instance->file_get_contents($accessName));
}
- /**
- * @dataProvider accessNameProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('accessNameProvider')]
public function testFopenReadEncoding($accessName): void {
$this->sourceStorage->file_put_contents(self::NFD_NAME, 'bar');
$fh = $this->instance->fopen($accessName, 'r');
@@ -73,9 +73,7 @@ class EncodingTest extends \Test\Files\Storage\Storage {
$this->assertEquals('bar', $data);
}
- /**
- * @dataProvider accessNameProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('accessNameProvider')]
public function testFopenOverwriteEncoding($accessName): void {
$this->sourceStorage->file_put_contents(self::NFD_NAME, 'bar');
$fh = $this->instance->fopen($accessName, 'w');
@@ -86,17 +84,13 @@ class EncodingTest extends \Test\Files\Storage\Storage {
$this->assertFalse($this->sourceStorage->file_exists(self::NFC_NAME));
}
- /**
- * @dataProvider accessNameProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('accessNameProvider')]
public function testFileExistsEncoding($accessName): void {
$this->sourceStorage->file_put_contents(self::NFD_NAME, 'bar');
$this->assertTrue($this->instance->file_exists($accessName));
}
- /**
- * @dataProvider accessNameProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('accessNameProvider')]
public function testUnlinkEncoding($accessName): void {
$this->sourceStorage->file_put_contents(self::NFD_NAME, 'bar');
$this->assertTrue($this->instance->unlink($accessName));
@@ -110,7 +104,7 @@ class EncodingTest extends \Test\Files\Storage\Storage {
$this->assertEquals('nfc', $this->instance->file_get_contents(self::NFC_NAME));
}
- public function encodedDirectoriesProvider() {
+ public static function encodedDirectoriesProvider(): array {
return [
[self::NFD_NAME, self::NFC_NAME],
[self::NFD_NAME . '/' . self::NFD_NAME, self::NFC_NAME . '/' . self::NFC_NAME],
@@ -118,9 +112,7 @@ class EncodingTest extends \Test\Files\Storage\Storage {
];
}
- /**
- * @dataProvider encodedDirectoriesProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('encodedDirectoriesProvider')]
public function testOperationInsideDirectory($sourceDir, $accessDir): void {
$this->sourceStorage->mkdir($sourceDir);
$this->instance->file_put_contents($accessDir . '/test.txt', 'bar');
@@ -150,7 +142,7 @@ class EncodingTest extends \Test\Files\Storage\Storage {
$this->assertEquals('barbaric', $this->instance->file_get_contents('//' . self::NFC_NAME));
}
- public function sourceAndTargetDirectoryProvider() {
+ public static function sourceAndTargetDirectoryProvider(): array {
return [
[self::NFC_NAME . '1', self::NFC_NAME . '2'],
[self::NFD_NAME . '1', self::NFC_NAME . '2'],
@@ -159,9 +151,7 @@ class EncodingTest extends \Test\Files\Storage\Storage {
];
}
- /**
- * @dataProvider sourceAndTargetDirectoryProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('sourceAndTargetDirectoryProvider')]
public function testCopyAndMoveEncodedFolder($sourceDir, $targetDir): void {
$this->sourceStorage->mkdir($sourceDir);
$this->sourceStorage->mkdir($targetDir);
@@ -179,9 +169,7 @@ class EncodingTest extends \Test\Files\Storage\Storage {
$this->assertEquals('bar', $this->instance->file_get_contents(self::NFC_NAME . '2/test2.txt'));
}
- /**
- * @dataProvider sourceAndTargetDirectoryProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('sourceAndTargetDirectoryProvider')]
public function testCopyAndMoveFromStorageEncodedFolder($sourceDir, $targetDir): void {
$this->sourceStorage->mkdir($sourceDir);
$this->sourceStorage->mkdir($targetDir);
diff --git a/tests/lib/Files/Storage/Wrapper/EncryptionTest.php b/tests/lib/Files/Storage/Wrapper/EncryptionTest.php
index bb3df36dec2..3e643714300 100644
--- a/tests/lib/Files/Storage/Wrapper/EncryptionTest.php
+++ b/tests/lib/Files/Storage/Wrapper/EncryptionTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -8,10 +9,8 @@
namespace Test\Files\Storage\Wrapper;
use Exception;
-use OC;
use OC\Encryption\Exceptions\ModuleDoesNotExistsException;
use OC\Encryption\File;
-use OC\Encryption\Update;
use OC\Encryption\Util;
use OC\Files\Cache\Cache;
use OC\Files\Cache\CacheEntry;
@@ -29,6 +28,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;
@@ -46,7 +47,6 @@ class EncryptionTest extends Storage {
private Util&MockObject $util;
private \OC\Encryption\Manager&MockObject $encryptionManager;
private IEncryptionModule&MockObject $encryptionModule;
- private Update&MockObject $update;
private Cache&MockObject $cache;
private LoggerInterface&MockObject $logger;
private File&MockObject $file;
@@ -62,9 +62,9 @@ class EncryptionTest extends Storage {
parent::setUp();
$mockModule = $this->buildMockModule();
- $this->encryptionManager = $this->getMockBuilder('\OC\Encryption\Manager')
+ $this->encryptionManager = $this->getMockBuilder(\OC\Encryption\Manager::class)
->disableOriginalConstructor()
- ->setMethods(['getEncryptionModule', 'isEnabled'])
+ ->onlyMethods(['getEncryptionModule', 'isEnabled'])
->getMock();
$this->encryptionManager->expects($this->any())
->method('getEncryptionModule')
@@ -78,8 +78,8 @@ class EncryptionTest extends Storage {
->disableOriginalConstructor()
->getMock();
- $this->util = $this->getMockBuilder('\OC\Encryption\Util')
- ->setMethods(['getUidAndFilename', 'isFile', 'isExcluded', 'stripPartialFileExtension'])
+ $this->util = $this->getMockBuilder(Util::class)
+ ->onlyMethods(['getUidAndFilename', 'isFile', 'isExcluded', 'stripPartialFileExtension'])
->setConstructorArgs([new View(), new Manager(
$this->config,
$this->createMock(ICacheFactory::class),
@@ -98,9 +98,9 @@ class EncryptionTest extends Storage {
return $path;
});
- $this->file = $this->getMockBuilder('\OC\Encryption\File')
+ $this->file = $this->getMockBuilder(File::class)
->disableOriginalConstructor()
- ->setMethods(['getAccessList'])
+ ->onlyMethods(['getAccessList'])
->getMock();
$this->file->expects($this->any())->method('getAccessList')->willReturn([]);
@@ -108,15 +108,11 @@ class EncryptionTest extends Storage {
$this->sourceStorage = new Temporary([]);
- $this->keyStore = $this->getMockBuilder('\OC\Encryption\Keys\Storage')
- ->disableOriginalConstructor()->getMock();
+ $this->keyStore = $this->createMock(\OC\Encryption\Keys\Storage::class);
- $this->update = $this->getMockBuilder('\OC\Encryption\Update')
- ->disableOriginalConstructor()->getMock();
-
- $this->mount = $this->getMockBuilder('\OC\Files\Mount\MountPoint')
+ $this->mount = $this->getMockBuilder(MountPoint::class)
->disableOriginalConstructor()
- ->setMethods(['getOption'])
+ ->onlyMethods(['getOption'])
->getMock();
$this->mount->expects($this->any())->method('getOption')->willReturnCallback(function ($option, $default) {
if ($option === 'encrypt' && $default === true) {
@@ -155,12 +151,11 @@ class EncryptionTest extends Storage {
$this->file,
null,
$this->keyStore,
- $this->update,
$this->mountManager,
$this->arrayCache
]
)
- ->setMethods(['getMetaData', 'getCache', 'getEncryptionModule'])
+ ->onlyMethods(['getMetaData', 'getCache', 'getEncryptionModule'])
->getMock();
$this->instance->expects($this->any())
@@ -181,7 +176,7 @@ class EncryptionTest extends Storage {
protected function buildMockModule(): IEncryptionModule&MockObject {
$this->encryptionModule = $this->getMockBuilder('\OCP\Encryption\IEncryptionModule')
->disableOriginalConstructor()
- ->setMethods(['getId', 'getDisplayName', 'begin', 'end', 'encrypt', 'decrypt', 'update', 'shouldEncrypt', 'getUnencryptedBlockSize', 'isReadable', 'encryptAll', 'prepareDecryptAll', 'isReadyForUser', 'needDetailedAccessList'])
+ ->onlyMethods(['getId', 'getDisplayName', 'begin', 'end', 'encrypt', 'decrypt', 'update', 'shouldEncrypt', 'getUnencryptedBlockSize', 'isReadable', 'encryptAll', 'prepareDecryptAll', 'isReadyForUser', 'needDetailedAccessList'])
->getMock();
$this->encryptionModule->expects($this->any())->method('getId')->willReturn('UNIT_TEST_MODULE');
@@ -199,7 +194,6 @@ class EncryptionTest extends Storage {
}
/**
- * @dataProvider dataTestGetMetaData
*
* @param string $path
* @param array $metaData
@@ -208,6 +202,7 @@ class EncryptionTest extends Storage {
* @param int $storedUnencryptedSize
* @param array $expected
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataTestGetMetaData')]
public function testGetMetaData($path, $metaData, $encrypted, $unencryptedSizeSet, $storedUnencryptedSize, $expected): void {
$sourceStorage = $this->getMockBuilder('\OC\Files\Storage\Storage')
->disableOriginalConstructor()->getMock();
@@ -237,12 +232,11 @@ class EncryptionTest extends Storage {
$this->file,
null,
$this->keyStore,
- $this->update,
$this->mountManager,
$this->arrayCache,
]
)
- ->setMethods(['getCache', 'verifyUnencryptedSize'])
+ ->onlyMethods(['getCache', 'verifyUnencryptedSize'])
->getMock();
if ($unencryptedSizeSet) {
@@ -285,7 +279,7 @@ class EncryptionTest extends Storage {
}
}
- public function dataTestGetMetaData() {
+ public static function dataTestGetMetaData(): array {
return [
['/test.txt', ['size' => 42, 'encrypted' => 2, 'encryptedVersion' => 2, 'fileid' => 1], true, true, 12, ['size' => 12, 'encrypted' => true, 'encryptedVersion' => 2]],
['/test.txt', null, true, true, 12, null],
@@ -316,12 +310,11 @@ class EncryptionTest extends Storage {
$this->file,
null,
$this->keyStore,
- $this->update,
$this->mountManager,
$this->arrayCache,
]
)
- ->setMethods(['getCache', 'verifyUnencryptedSize'])
+ ->onlyMethods(['getCache', 'verifyUnencryptedSize'])
->getMock();
$this->instance->expects($this->any())->method('getCache')->willReturn($cache);
@@ -335,13 +328,13 @@ class EncryptionTest extends Storage {
}
/**
- * @dataProvider dataTestVerifyUnencryptedSize
*
* @param int $encryptedSize
* @param int $unencryptedSize
* @param bool $failure
* @param int $expected
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataTestVerifyUnencryptedSize')]
public function testVerifyUnencryptedSize($encryptedSize, $unencryptedSize, $failure, $expected): void {
$sourceStorage = $this->getMockBuilder('\OC\Files\Storage\Storage')
->disableOriginalConstructor()->getMock();
@@ -361,12 +354,11 @@ class EncryptionTest extends Storage {
$this->file,
null,
$this->keyStore,
- $this->update,
$this->mountManager,
$this->arrayCache,
]
)
- ->setMethods(['fixUnencryptedSize'])
+ ->onlyMethods(['fixUnencryptedSize'])
->getMock();
$sourceStorage->expects($this->once())->method('filesize')->willReturn($encryptedSize);
@@ -389,7 +381,7 @@ class EncryptionTest extends Storage {
);
}
- public function dataTestVerifyUnencryptedSize() {
+ public static function dataTestVerifyUnencryptedSize(): array {
return [
[120, 80, false, 80],
[120, 120, false, 80],
@@ -399,13 +391,13 @@ class EncryptionTest extends Storage {
}
/**
- * @dataProvider dataTestCopyAndRename
*
* @param string $source
* @param string $target
* @param $encryptionEnabled
* @param boolean $renameKeysReturn
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataTestCopyAndRename')]
public function testRename($source,
$target,
$encryptionEnabled,
@@ -444,7 +436,7 @@ class EncryptionTest extends Storage {
*
* @return array
*/
- public function dataTestCopyAndRename() {
+ public static function dataTestCopyAndRename(): array {
return [
['source', 'target', true, false, false],
['source', 'target', true, true, false],
@@ -461,13 +453,13 @@ class EncryptionTest extends Storage {
}
/**
- * @dataProvider dataTestRmdir
*
* @param string $path
* @param boolean $rmdirResult
* @param boolean $isExcluded
* @param boolean $encryptionEnabled
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataTestRmdir')]
public function testRmdir($path, $rmdirResult, $isExcluded, $encryptionEnabled): void {
$sourceStorage = $this->getMockBuilder('\OC\Files\Storage\Storage')
->disableOriginalConstructor()->getMock();
@@ -491,7 +483,6 @@ class EncryptionTest extends Storage {
$this->file,
null,
$this->keyStore,
- $this->update,
$this->mountManager,
$this->arrayCache,
);
@@ -506,7 +497,7 @@ class EncryptionTest extends Storage {
$encryptionStorage->rmdir($path);
}
- public function dataTestRmdir() {
+ public static function dataTestRmdir(): array {
return [
['/file.txt', true, true, true],
['/file.txt', false, true, true],
@@ -520,11 +511,11 @@ class EncryptionTest extends Storage {
}
/**
- * @dataProvider dataTestCopyKeys
*
* @param boolean $excluded
* @param boolean $expected
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataTestCopyKeys')]
public function testCopyKeys($excluded, $expected): void {
$this->util->expects($this->once())
->method('isExcluded')
@@ -541,7 +532,7 @@ class EncryptionTest extends Storage {
);
}
- public function dataTestCopyKeys() {
+ public static function dataTestCopyKeys(): array {
return [
[true, false],
[false, true],
@@ -549,12 +540,12 @@ class EncryptionTest extends Storage {
}
/**
- * @dataProvider dataTestGetHeader
*
* @param string $path
* @param bool $strippedPathExists
* @param string $strippedPath
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataTestGetHeader')]
public function testGetHeader($path, $strippedPathExists, $strippedPath): void {
$sourceStorage = $this->getMockBuilder('\OC\Files\Storage\Storage')
->disableOriginalConstructor()->getMock();
@@ -598,12 +589,11 @@ class EncryptionTest extends Storage {
$this->file,
null,
$this->keyStore,
- $this->update,
$this->mountManager,
$this->arrayCache,
]
)
- ->setMethods(['getCache', 'readFirstBlock'])
+ ->onlyMethods(['getCache', 'readFirstBlock'])
->getMock();
$instance->method('getCache')->willReturn($cache);
@@ -629,7 +619,7 @@ class EncryptionTest extends Storage {
$this->invokePrivate($instance, 'getHeader', [$path]);
}
- public function dataTestGetHeader() {
+ public static function dataTestGetHeader(): array {
return [
['/foo/bar.txt', false, '/foo/bar.txt'],
['/foo/bar.txt.part', false, '/foo/bar.txt'],
@@ -642,11 +632,10 @@ class EncryptionTest extends Storage {
/**
* test if getHeader adds the default module correctly to the header for
* legacy files
- *
- * @dataProvider dataTestGetHeaderAddLegacyModule
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataTestGetHeaderAddLegacyModule')]
public function testGetHeaderAddLegacyModule($header, $isEncrypted, $strippedPathExists, $expected): void {
- $sourceStorage = $this->getMockBuilder('\OC\Files\Storage\Storage')
+ $sourceStorage = $this->getMockBuilder(\OC\Files\Storage\Storage::class)
->disableOriginalConstructor()->getMock();
$sourceStorage->expects($this->once())
@@ -654,7 +643,7 @@ class EncryptionTest extends Storage {
->with('test.txt')
->willReturn($strippedPathExists);
- $util = $this->getMockBuilder('\OC\Encryption\Util')
+ $util = $this->getMockBuilder(Util::class)
->onlyMethods(['stripPartialFileExtension', 'parseRawHeader'])
->setConstructorArgs([new View(), new Manager(
$this->config,
@@ -669,8 +658,7 @@ class EncryptionTest extends Storage {
return $path;
});
- $cache = $this->getMockBuilder('\OC\Files\Cache\Cache')
- ->disableOriginalConstructor()->getMock();
+ $cache = $this->createMock(Cache::class);
$cache->expects($this->any())
->method('get')
->willReturnCallback(function ($path) use ($isEncrypted) {
@@ -692,12 +680,11 @@ class EncryptionTest extends Storage {
$this->file,
null,
$this->keyStore,
- $this->update,
$this->mountManager,
$this->arrayCache,
]
)
- ->setMethods(['readFirstBlock', 'getCache'])
+ ->onlyMethods(['readFirstBlock', 'getCache'])
->getMock();
$instance->method('readFirstBlock')->willReturn('');
@@ -713,7 +700,7 @@ class EncryptionTest extends Storage {
}
}
- public function dataTestGetHeaderAddLegacyModule() {
+ public static function dataTestGetHeaderAddLegacyModule(): array {
return [
[['cipher' => 'AES-128'], true, true, ['cipher' => 'AES-128', Util::HEADER_ENCRYPTION_MODULE_KEY => 'OC_DEFAULT_MODULE']],
[[], true, false, []],
@@ -722,7 +709,7 @@ class EncryptionTest extends Storage {
];
}
- public function dataCopyBetweenStorage() {
+ public static function dataCopyBetweenStorage(): array {
return [
[true, true, true],
[true, false, false],
@@ -740,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')
@@ -774,12 +761,12 @@ class EncryptionTest extends Storage {
}
/**
- * @dataProvider dataCopyBetweenStorage
*
* @param bool $encryptionEnabled
* @param bool $mountPointEncryptionEnabled
* @param bool $expectedEncrypted
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataCopyBetweenStorage')]
public function testCopyBetweenStorage($encryptionEnabled, $mountPointEncryptionEnabled, $expectedEncrypted): void {
$storage2 = $this->createMock(\OC\Files\Storage\Storage::class);
@@ -789,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')
@@ -834,13 +821,13 @@ class EncryptionTest extends Storage {
}
/**
- * @dataProvider dataTestCopyBetweenStorageVersions
*
* @param string $sourceInternalPath
* @param string $targetInternalPath
* @param bool $copyResult
* @param bool $encrypted
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataTestCopyBetweenStorageVersions')]
public function testCopyBetweenStorageVersions($sourceInternalPath, $targetInternalPath, $copyResult, $encrypted): void {
$sourceStorage = $this->createMock(\OC\Files\Storage\Storage::class);
@@ -867,12 +854,11 @@ class EncryptionTest extends Storage {
$this->file,
null,
$this->keyStore,
- $this->update,
$this->mountManager,
$this->arrayCache
]
)
- ->setMethods(['updateUnencryptedSize', 'getCache'])
+ ->onlyMethods(['updateUnencryptedSize', 'getCache'])
->getMock();
$targetStorage->expects($this->once())->method('copyFromStorage')
@@ -914,7 +900,7 @@ class EncryptionTest extends Storage {
$this->assertSame($copyResult, $result);
}
- public function dataTestCopyBetweenStorageVersions() {
+ public static function dataTestCopyBetweenStorageVersions(): array {
return [
['/files/foo.txt', '/files_versions/foo.txt.768743', true, true],
['/files/foo.txt', '/files_versions/foo.txt.768743', true, false],
@@ -929,17 +915,17 @@ class EncryptionTest extends Storage {
}
/**
- * @dataProvider dataTestIsVersion
* @param string $path
* @param bool $expected
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataTestIsVersion')]
public function testIsVersion($path, $expected): void {
$this->assertSame($expected,
$this->invokePrivate($this->instance, 'isVersion', [$path])
);
}
- public function dataTestIsVersion() {
+ public static function dataTestIsVersion(): array {
return [
['files_versions/foo', true],
['/files_versions/foo', true],
@@ -951,13 +937,13 @@ class EncryptionTest extends Storage {
}
/**
- * @dataProvider dataTestShouldEncrypt
*
* @param bool $encryptMountPoint
* @param mixed $encryptionModule
* @param bool $encryptionModuleShouldEncrypt
* @param bool $expected
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataTestShouldEncrypt')]
public function testShouldEncrypt(
$encryptMountPoint,
$encryptionModule,
@@ -968,7 +954,6 @@ class EncryptionTest extends Storage {
$util = $this->createMock(Util::class);
$fileHelper = $this->createMock(IFile::class);
$keyStorage = $this->createMock(IStorage::class);
- $update = $this->createMock(Update::class);
$mountManager = $this->createMock(\OC\Files\Mount\Manager::class);
$mount = $this->createMock(IMountPoint::class);
$arrayCache = $this->createMock(ArrayCache::class);
@@ -986,12 +971,11 @@ class EncryptionTest extends Storage {
$fileHelper,
null,
$keyStorage,
- $update,
$mountManager,
$arrayCache
]
)
- ->setMethods(['getFullPath', 'getEncryptionModule'])
+ ->onlyMethods(['getFullPath', 'getEncryptionModule'])
->getMock();
if ($encryptionModule === true) {
@@ -1033,7 +1017,7 @@ class EncryptionTest extends Storage {
$this->assertSame($expected, $result);
}
- public function dataTestShouldEncrypt() {
+ public static function dataTestShouldEncrypt(): array {
return [
[false, false, false, false],
[true, false, false, false],
diff --git a/tests/lib/Files/Storage/Wrapper/JailTest.php b/tests/lib/Files/Storage/Wrapper/JailTest.php
index fbc4e1d09ee..0043e37ba33 100644
--- a/tests/lib/Files/Storage/Wrapper/JailTest.php
+++ b/tests/lib/Files/Storage/Wrapper/JailTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -7,17 +8,21 @@
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
+ * @var Temporary
*/
private $sourceStorage;
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 +33,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/KnownMtimeTest.php b/tests/lib/Files/Storage/Wrapper/KnownMtimeTest.php
index bbeb48c5cef..b1b5582b4ed 100644
--- a/tests/lib/Files/Storage/Wrapper/KnownMtimeTest.php
+++ b/tests/lib/Files/Storage/Wrapper/KnownMtimeTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2023 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
diff --git a/tests/lib/Files/Storage/Wrapper/PermissionsMaskTest.php b/tests/lib/Files/Storage/Wrapper/PermissionsMaskTest.php
index 5c0a035d094..a2f3460c58c 100644
--- a/tests/lib/Files/Storage/Wrapper/PermissionsMaskTest.php
+++ b/tests/lib/Files/Storage/Wrapper/PermissionsMaskTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -7,6 +8,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;
@@ -16,13 +19,13 @@ use OCP\Files\Cache\IScanner;
*/
class PermissionsMaskTest extends \Test\Files\Storage\Storage {
/**
- * @var \OC\Files\Storage\Temporary
+ * @var Temporary
*/
private $sourceStorage;
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 +35,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 +130,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 +152,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 +170,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 f07e6021e4e..2878fe6ca92 100644
--- a/tests/lib/Files/Storage/Wrapper/QuotaTest.php
+++ b/tests/lib/Files/Storage/Wrapper/QuotaTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -10,8 +11,10 @@ namespace Test\Files\Storage\Wrapper;
//ensure the constants are loaded
use OC\Files\Cache\CacheEntry;
use OC\Files\Storage\Local;
-
-\OC::$loader->load('\OC\Files\Filesystem');
+use OC\Files\Storage\Wrapper\Quota;
+use OCP\Files;
+use OCP\ITempManager;
+use OCP\Server;
/**
* Class QuotaTest
@@ -29,13 +32,13 @@ 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 {
- \OC_Helper::rmdirr($this->tmpDir);
+ Files::rmdirr($this->tmpDir);
parent::tearDown();
}
@@ -43,10 +46,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 {
@@ -76,7 +79,7 @@ class QuotaTest extends \Test\Files\Storage\Storage {
public function testFreeSpaceWithUnknownDiskSpace(): void {
$storage = $this->getMockBuilder(Local::class)
- ->setMethods(['free_space'])
+ ->onlyMethods(['free_space'])
->setConstructorArgs([['datadir' => $this->tmpDir]])
->getMock();
$storage->expects($this->any())
@@ -84,7 +87,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]
);
@@ -132,14 +135,14 @@ class QuotaTest extends \Test\Files\Storage\Storage {
public function testReturnFalseWhenFopenFailed(): void {
$failStorage = $this->getMockBuilder(Local::class)
- ->setMethods(['fopen'])
+ ->onlyMethods(['fopen'])
->setConstructorArgs([['datadir' => $this->tmpDir]])
->getMock();
$failStorage->expects($this->any())
->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'));
}
@@ -197,7 +200,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 1d0f41bf3ed..60f139450c7 100644
--- a/tests/lib/Files/Storage/Wrapper/WrapperTest.php
+++ b/tests/lib/Files/Storage/Wrapper/WrapperTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -7,6 +8,12 @@
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 {
/**
* @var string tmpDir
@@ -16,13 +23,13 @@ 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 {
- \OC_Helper::rmdirr($this->tmpDir);
+ Files::rmdirr($this->tmpDir);
parent::tearDown();
}
diff --git a/tests/lib/Files/Stream/DummyEncryptionWrapper.php b/tests/lib/Files/Stream/DummyEncryptionWrapper.php
index 211050905bd..89904e6de73 100644
--- a/tests/lib/Files/Stream/DummyEncryptionWrapper.php
+++ b/tests/lib/Files/Stream/DummyEncryptionWrapper.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -7,7 +8,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/EncryptionTest.php b/tests/lib/Files/Stream/EncryptionTest.php
index 36e72ea764a..62eaab3cc7e 100644
--- a/tests/lib/Files/Stream/EncryptionTest.php
+++ b/tests/lib/Files/Stream/EncryptionTest.php
@@ -9,8 +9,12 @@ declare(strict_types=1);
*/
namespace Test\Files\Stream;
+use OC\Encryption\File;
+use OC\Encryption\Util;
use OC\Files\Cache\CacheEntry;
+use OC\Files\Storage\Storage;
use OC\Files\Storage\Wrapper\Wrapper;
+use OC\Files\Stream\Encryption;
use OC\Files\View;
use OC\Memcache\ArrayCache;
use OCP\Encryption\IEncryptionModule;
@@ -53,11 +57,11 @@ class EncryptionTest extends \Test\TestCase {
->getMock();
$file = $this->getMockBuilder('\OC\Encryption\File')
->disableOriginalConstructor()
- ->setMethods(['getAccessList'])
+ ->onlyMethods(['getAccessList'])
->getMock();
$file->expects($this->any())->method('getAccessList')->willReturn([]);
$util = $this->getMockBuilder('\OC\Encryption\Util')
- ->setMethods(['getUidAndFilename'])
+ ->onlyMethods(['getUidAndFilename'])
->setConstructorArgs([new View(), new \OC\User\Manager(
$config,
$this->createMock(ICacheFactory::class),
@@ -97,9 +101,7 @@ class EncryptionTest extends \Test\TestCase {
);
}
- /**
- * @dataProvider dataProviderStreamOpen()
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataProviderStreamOpen')]
public function testStreamOpen(
$isMasterKeyUsed,
$mode,
@@ -111,20 +113,17 @@ class EncryptionTest extends \Test\TestCase {
$expectedReadOnly,
): void {
// build mocks
- $encryptionModuleMock = $this->getMockBuilder('\OCP\Encryption\IEncryptionModule')
- ->disableOriginalConstructor()->getMock();
+ $encryptionModuleMock = $this->createMock(IEncryptionModule::class);
$encryptionModuleMock->expects($this->any())->method('needDetailedAccessList')->willReturn(!$isMasterKeyUsed);
$encryptionModuleMock->expects($this->once())
->method('getUnencryptedBlockSize')->willReturn(99);
$encryptionModuleMock->expects($this->once())
->method('begin')->willReturn([]);
- $storageMock = $this->getMockBuilder('\OC\Files\Storage\Storage')
- ->disableOriginalConstructor()->getMock();
+ $storageMock = $this->createMock(Storage::class);
$storageMock->expects($this->once())->method('file_exists')->willReturn($fileExists);
- $fileMock = $this->getMockBuilder('\OC\Encryption\File')
- ->disableOriginalConstructor()->getMock();
+ $fileMock = $this->createMock(File::class);
if ($isMasterKeyUsed) {
$fileMock->expects($this->never())->method('getAccessList');
} else {
@@ -134,18 +133,20 @@ class EncryptionTest extends \Test\TestCase {
return [];
});
}
- $utilMock = $this->getMockBuilder('\OC\Encryption\Util')
+ $utilMock = $this->getMockBuilder(Util::class)
->disableOriginalConstructor()->getMock();
$utilMock->expects($this->any())
->method('getHeaderSize')
->willReturn(8192);
// get a instance of the stream wrapper
- $streamWrapper = $this->getMockBuilder('\OC\Files\Stream\Encryption')
- ->setMethods(['loadContext', 'writeHeader', 'skipHeader'])->disableOriginalConstructor()->getMock();
+ $streamWrapper = $this->getMockBuilder(Encryption::class)
+ ->onlyMethods(['loadContext', 'writeHeader', 'skipHeader'])
+ ->disableOriginalConstructor()
+ ->getMock();
// set internal properties of the stream wrapper
- $stream = new \ReflectionClass('\OC\Files\Stream\Encryption');
+ $stream = new \ReflectionClass(Encryption::class);
$encryptionModule = $stream->getProperty('encryptionModule');
$encryptionModule->setAccessible(true);
$encryptionModule->setValue($streamWrapper, $encryptionModuleMock);
@@ -195,7 +196,7 @@ class EncryptionTest extends \Test\TestCase {
$readOnly->setAccessible(false);
}
- public function dataProviderStreamOpen() {
+ public static function dataProviderStreamOpen(): array {
return [
[false, 'r', '/foo/bar/test.txt', true, '/foo/bar/test.txt', null, null, true],
[false, 'r', '/foo/bar/test.txt', false, '/foo/bar', null, null, true],
@@ -266,7 +267,7 @@ class EncryptionTest extends \Test\TestCase {
unlink($fileName);
}
- public function dataFilesProvider() {
+ public static function dataFilesProvider(): array {
return [
['lorem-big.txt'],
['block-aligned.txt'],
@@ -274,9 +275,7 @@ class EncryptionTest extends \Test\TestCase {
];
}
- /**
- * @dataProvider dataFilesProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataFilesProvider')]
public function testWriteReadBigFile($testFile): void {
$expectedData = file_get_contents(\OC::$SERVERROOT . '/tests/data/' . $testFile);
// write it
@@ -311,13 +310,15 @@ class EncryptionTest extends \Test\TestCase {
/**
* simulate a non-seekable storage
- *
- * @dataProvider dataFilesProvider
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataFilesProvider')]
public function testWriteToNonSeekableStorage($testFile): void {
- $wrapper = $this->getMockBuilder('\OC\Files\Stream\Encryption')
- ->setMethods(['parentSeekStream'])->getMock();
- $wrapper->expects($this->any())->method('parentSeekStream')->willReturn(false);
+ $wrapper = $this->getMockBuilder(Encryption::class)
+ ->onlyMethods(['parentStreamSeek'])
+ ->getMock();
+ $wrapper->expects($this->any())
+ ->method('parentStreamSeek')
+ ->willReturn(false);
$expectedData = file_get_contents(\OC::$SERVERROOT . '/tests/data/' . $testFile);
// write it
@@ -351,9 +352,9 @@ class EncryptionTest extends \Test\TestCase {
}
protected function buildMockModule(): IEncryptionModule&MockObject {
- $encryptionModule = $this->getMockBuilder('\OCP\Encryption\IEncryptionModule')
+ $encryptionModule = $this->getMockBuilder(IEncryptionModule::class)
->disableOriginalConstructor()
- ->setMethods(['getId', 'getDisplayName', 'begin', 'end', 'encrypt', 'decrypt', 'update', 'shouldEncrypt', 'getUnencryptedBlockSize', 'isReadable', 'encryptAll', 'prepareDecryptAll', 'isReadyForUser', 'needDetailedAccessList'])
+ ->onlyMethods(['getId', 'getDisplayName', 'begin', 'end', 'encrypt', 'decrypt', 'update', 'shouldEncrypt', 'getUnencryptedBlockSize', 'isReadable', 'encryptAll', 'prepareDecryptAll', 'isReadyForUser', 'needDetailedAccessList'])
->getMock();
$encryptionModule->expects($this->any())->method('getId')->willReturn('UNIT_TEST_MODULE');
diff --git a/tests/lib/Files/Stream/HashWrapperTest.php b/tests/lib/Files/Stream/HashWrapperTest.php
index ee50fe3b13a..459bc5c4318 100644
--- a/tests/lib/Files/Stream/HashWrapperTest.php
+++ b/tests/lib/Files/Stream/HashWrapperTest.php
@@ -12,9 +12,7 @@ use OC\Files\Stream\HashWrapper;
use Test\TestCase;
class HashWrapperTest extends TestCase {
- /**
- * @dataProvider hashProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('hashProvider')]
public function testHashStream($data, string $algo, string $hash): void {
if (!is_resource($data)) {
$tmpData = fopen('php://temp', 'r+');
@@ -25,13 +23,13 @@ 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);
}
- public function hashProvider() {
+ public static function hashProvider(): array {
return [
['foo', 'md5', 'acbd18db4cc2f85cedef654fccc4a4d8'],
['foo', 'sha1', '0beec7b5ea3f0fdbc95d0dd47f3c5bc275da8a33'],
diff --git a/tests/lib/Files/Stream/QuotaTest.php b/tests/lib/Files/Stream/QuotaTest.php
index 2df767d6c60..4248d14f5a1 100644
--- a/tests/lib/Files/Stream/QuotaTest.php
+++ b/tests/lib/Files/Stream/QuotaTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2017-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -7,6 +8,8 @@
namespace Test\Files\Stream;
+use OC\Files\Stream\Quota;
+
class QuotaTest extends \Test\TestCase {
/**
* @param string $mode
@@ -15,7 +18,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 +63,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 +72,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..c30b21de401 100644
--- a/tests/lib/Files/Type/DetectionTest.php
+++ b/tests/lib/Files/Type/DetectionTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -9,6 +10,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 +20,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/'
);
@@ -45,11 +47,11 @@ class DetectionTest extends \Test\TestCase {
}
/**
- * @dataProvider dataDetectPath
*
* @param string $path
* @param string $expected
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataDetectPath')]
public function testDetectPath(string $path, string $expected): void {
$this->assertEquals($expected, $this->detection->detectPath($path));
}
@@ -65,11 +67,11 @@ class DetectionTest extends \Test\TestCase {
}
/**
- * @dataProvider dataDetectContent
*
* @param string $path
* @param string $expected
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataDetectContent')]
public function testDetectContent(string $path, string $expected): void {
$this->assertEquals($expected, $this->detection->detectContent(\OC::$SERVERROOT . '/tests/data' . $path));
}
@@ -85,11 +87,11 @@ class DetectionTest extends \Test\TestCase {
}
/**
- * @dataProvider dataDetect
*
* @param string $path
* @param string $expected
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataDetect')]
public function testDetect(string $path, string $expected): void {
$this->assertEquals($expected, $this->detection->detect(\OC::$SERVERROOT . '/tests/data' . $path));
}
@@ -109,11 +111,11 @@ class DetectionTest extends \Test\TestCase {
}
/**
- * @dataProvider dataMimeTypeCustom
*
* @param string $ext
* @param string $mime
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataMimeTypeCustom')]
public function testDetectMimeTypeCustom(string $ext, string $mime): void {
$confDir = sys_get_temp_dir();
file_put_contents($confDir . '/mimetypemapping.dist.json', json_encode([]));
@@ -143,11 +145,11 @@ class DetectionTest extends \Test\TestCase {
}
/**
- * @dataProvider dataGetSecureMimeType
*
* @param string $mimeType
* @param string $expected
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataGetSecureMimeType')]
public function testGetSecureMimeType(string $mimeType, string $expected): void {
$this->assertEquals($expected, $this->detection->getSecureMimeType($mimeType));
}
diff --git a/tests/lib/Files/Type/LoaderTest.php b/tests/lib/Files/Type/LoaderTest.php
index 6eaf6ac2013..44745a50dc0 100644
--- a/tests/lib/Files/Type/LoaderTest.php
+++ b/tests/lib/Files/Type/LoaderTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -9,6 +10,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 +18,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 f66bb72e865..49399ef70a6 100644
--- a/tests/lib/Files/Utils/ScannerTest.php
+++ b/tests/lib/Files/Utils/ScannerTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -10,20 +11,25 @@ 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
+ * @var MountPoint[] $mounts
*/
private $mounts = [];
/**
- * @param \OC\Files\Mount\MountPoint $mount
+ * @param MountPoint $mount
*/
public function addMount($mount) {
$this->mounts[] = $mount;
@@ -51,13 +57,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 +77,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 +99,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,24 +130,21 @@ class ScannerTest extends \Test\TestCase {
}
});
- \OC::$server->getMountProviderCollection()->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');
$this->assertTrue($cache->inCache('folder/bar.txt'));
}
- /**
- * @return array
- */
- public function invalidPathProvider() {
+ public static function invalidPathProvider(): array {
return [
[
'../',
@@ -156,14 +159,14 @@ class ScannerTest extends \Test\TestCase {
}
/**
- * @dataProvider invalidPathProvider
* @param string $invalidPath
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('invalidPathProvider')]
public function testInvalidPathScanning($invalidPath): void {
$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);
}
@@ -177,7 +180,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('');
@@ -203,7 +206,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 53e5855d0e9..c490cd08dae 100644
--- a/tests/lib/Files/ViewTest.php
+++ b/tests/lib/Files/ViewTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -7,6 +8,7 @@
namespace Test\Files;
+use OC\Files\Cache\Scanner;
use OC\Files\Cache\Watcher;
use OC\Files\Filesystem;
use OC\Files\Mount\MountPoint;
@@ -20,12 +22,21 @@ 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\IGroup;
+use OCP\IGroupManager;
+use OCP\ITempManager;
+use OCP\IUser;
use OCP\IUserManager;
use OCP\Lock\ILockingProvider;
use OCP\Lock\LockedException;
@@ -86,7 +97,7 @@ class ViewTest extends \Test\TestCase {
use UserTrait;
/**
- * @var \OC\Files\Storage\Storage[] $storages
+ * @var Storage[] $storages
*/
private $storages = [];
@@ -96,16 +107,16 @@ class ViewTest extends \Test\TestCase {
private $user;
/**
- * @var \OCP\IUser
+ * @var IUser
*/
private $userObject;
/**
- * @var \OCP\IGroup
+ * @var IGroup
*/
private $groupObject;
- /** @var \OC\Files\Storage\Storage */
+ /** @var Storage */
private $tempStorage;
protected function setUp(): void {
@@ -116,8 +127,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');
@@ -127,7 +138,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;
@@ -148,13 +159,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 = \OC::$server->getMountProviderCollection();
+ $mountProviderCollection = Server::get(IMountProviderCollection::class);
self::invokePrivate($mountProviderCollection, 'providers', [[]]);
parent::tearDown();
@@ -274,7 +285,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, [], '/');
@@ -309,14 +320,12 @@ class ViewTest extends \Test\TestCase {
];
}
- /**
- * @dataProvider sharingDisabledPermissionProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('sharingDisabledPermissionProvider')]
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);
@@ -339,7 +348,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 {
@@ -518,10 +527,10 @@ class ViewTest extends \Test\TestCase {
}
public function moveBetweenStorages($storage1, $storage2) {
- Filesystem::mount($storage1, [], '/');
- Filesystem::mount($storage2, [], '/substorage');
+ Filesystem::mount($storage1, [], '/' . $this->user . '/');
+ Filesystem::mount($storage2, [], '/' . $this->user . '/substorage');
- $rootView = new View('');
+ $rootView = new View('/' . $this->user);
$rootView->rename('foo.txt', 'substorage/folder/foo.txt');
$this->assertFalse($rootView->file_exists('foo.txt'));
$this->assertTrue($rootView->file_exists('substorage/folder/foo.txt'));
@@ -558,9 +567,7 @@ class ViewTest extends \Test\TestCase {
return [['rmdir'], ['unlink']];
}
- /**
- * @dataProvider rmdirOrUnlinkDataProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('rmdirOrUnlinkDataProvider')]
public function testRmdir($method): void {
$storage1 = $this->getTestStorage();
Filesystem::mount($storage1, [], '/');
@@ -681,11 +688,11 @@ class ViewTest extends \Test\TestCase {
/**
* @param bool $scan
* @param string $class
- * @return \OC\Files\Storage\Storage
+ * @return Storage
*/
private function getTestStorage($scan = true, $class = Temporary::class) {
/**
- * @var \OC\Files\Storage\Storage $storage
+ * @var Storage $storage
*/
$storage = new $class([]);
$textData = "dummy file data\n";
@@ -767,9 +774,7 @@ class ViewTest extends \Test\TestCase {
\OC_Hook::clear('OC_Filesystem', 'post_write');
}
- /**
- * @dataProvider resolvePathTestProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('resolvePathTestProvider')]
public function testResolvePath($expected, $pathToTest): void {
$storage1 = $this->getTestStorage();
Filesystem::mount($storage1, [], '/');
@@ -844,7 +849,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 {
@@ -891,7 +896,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']);
@@ -929,9 +934,7 @@ class ViewTest extends \Test\TestCase {
$this->assertNotEquals($newFolderInfo->getEtag(), $oldEtag);
}
- /**
- * @dataProvider absolutePathProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('absolutePathProvider')]
public function testGetAbsolutePath($expectedPath, $relativePath): void {
$view = new View('/files');
$this->assertEquals($expectedPath, $view->getAbsolutePath($relativePath));
@@ -941,14 +944,16 @@ class ViewTest extends \Test\TestCase {
$storage = new Temporary([]);
$scanner = $storage->getScanner();
Filesystem::mount($storage, [], '/test/');
- $storage->file_put_contents('test.part', 'foobar');
+ $sizeWritten = $storage->file_put_contents('test.part', 'foobar');
$scanner->scan('');
$view = new View('/test');
$info = $view->getFileInfo('test.part');
$this->assertInstanceOf('\OCP\Files\FileInfo', $info);
$this->assertNull($info->getId());
+ $this->assertEquals(6, $sizeWritten);
$this->assertEquals(6, $info->getSize());
+ $this->assertEquals('foobar', $view->file_get_contents('test.part'));
}
public static function absolutePathProvider(): array {
@@ -963,9 +968,7 @@ class ViewTest extends \Test\TestCase {
];
}
- /**
- * @dataProvider chrootRelativePathProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('chrootRelativePathProvider')]
public function testChrootGetRelativePath($root, $absolutePath, $expectedPath): void {
$view = new View('/files');
$view->chroot($root);
@@ -976,9 +979,7 @@ class ViewTest extends \Test\TestCase {
return self::relativePathProvider('/');
}
- /**
- * @dataProvider initRelativePathProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('initRelativePathProvider')]
public function testInitGetRelativePath($root, $absolutePath, $expectedPath): void {
$view = new View($root);
$this->assertEquals($expectedPath, $view->getRelativePath($absolutePath));
@@ -1075,11 +1076,9 @@ class ViewTest extends \Test\TestCase {
$this->assertEquals('foo', $view->file_get_contents(''));
}
- /**
- * @dataProvider tooLongPathDataProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('tooLongPathDataProvider')]
public function testTooLongPath($operation, $param0 = null): void {
- $this->expectException(\OCP\Files\InvalidPathException::class);
+ $this->expectException(InvalidPathException::class);
$longPath = '';
@@ -1263,9 +1262,9 @@ class ViewTest extends \Test\TestCase {
}
/**
- * @dataProvider directoryTraversalProvider
* @param string $root
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('directoryTraversalProvider')]
public function testConstructDirectoryTraversalException($root): void {
$this->expectException(\Exception::class);
@@ -1288,7 +1287,7 @@ class ViewTest extends \Test\TestCase {
public function testSetMountOptionsInStorage(): void {
$mount = new MountPoint(Temporary::class, '/asd/', [[]], Filesystem::getLoader(), ['foo' => 'bar']);
Filesystem::getMountManager()->addMount($mount);
- /** @var \OC\Files\Storage\Common $storage */
+ /** @var Common $storage */
$storage = $mount->getStorage();
$this->assertEquals($storage->getMountOption('foo'), 'bar');
}
@@ -1296,7 +1295,7 @@ class ViewTest extends \Test\TestCase {
public function testSetMountOptionsWatcherPolicy(): void {
$mount = new MountPoint(Temporary::class, '/asd/', [[]], Filesystem::getLoader(), ['filesystem_check_changes' => Watcher::CHECK_NEVER]);
Filesystem::getMountManager()->addMount($mount);
- /** @var \OC\Files\Storage\Common $storage */
+ /** @var Common $storage */
$storage = $mount->getStorage();
$watcher = $storage->getWatcher();
$this->assertEquals(Watcher::CHECK_NEVER, $watcher->getPolicy());
@@ -1323,13 +1322,13 @@ class ViewTest extends \Test\TestCase {
* e.g. reading from a folder that's being renamed
*
*
- * @dataProvider dataLockPaths
*
* @param string $rootPath
* @param string $pathPrefix
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataLockPaths')]
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);
@@ -1344,11 +1343,11 @@ class ViewTest extends \Test\TestCase {
/**
* Reading from a files_encryption folder that's being renamed
*
- * @dataProvider dataLockPaths
*
* @param string $rootPath
* @param string $pathPrefix
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataLockPaths')]
public function testReadFromWriteUnlockablePath($rootPath, $pathPrefix): void {
$rootPath = str_replace('{folder}', 'files_encryption', $rootPath);
$pathPrefix = str_replace('{folder}', 'files_encryption', $pathPrefix);
@@ -1364,13 +1363,13 @@ class ViewTest extends \Test\TestCase {
* e.g. writing a file that's being downloaded
*
*
- * @dataProvider dataLockPaths
*
* @param string $rootPath
* @param string $pathPrefix
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataLockPaths')]
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);
@@ -1385,11 +1384,11 @@ class ViewTest extends \Test\TestCase {
/**
* Writing a file that's being downloaded
*
- * @dataProvider dataLockPaths
*
* @param string $rootPath
* @param string $pathPrefix
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataLockPaths')]
public function testWriteToReadUnlockableFile($rootPath, $pathPrefix): void {
$rootPath = str_replace('{folder}', 'files_encryption', $rootPath);
$pathPrefix = str_replace('{folder}', 'files_encryption', $pathPrefix);
@@ -1405,7 +1404,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, [], '/');
@@ -1435,7 +1434,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, [], '/');
@@ -1465,7 +1464,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, [], '/');
@@ -1512,9 +1511,7 @@ class ViewTest extends \Test\TestCase {
];
}
- /**
- * @dataProvider pathRelativeToFilesProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('pathRelativeToFilesProvider')]
public function testGetPathRelativeToFiles($path, $expectedPath): void {
$view = new View();
$this->assertEquals($expectedPath, $view->getPathRelativeToFiles($path));
@@ -1531,9 +1528,9 @@ class ViewTest extends \Test\TestCase {
}
/**
- * @dataProvider pathRelativeToFilesProviderExceptionCases
* @param string $path
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('pathRelativeToFilesProviderExceptionCases')]
public function testGetPathRelativeToFilesWithInvalidArgument($path): void {
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage('$absolutePath must be relative to "files"');
@@ -1576,11 +1573,11 @@ class ViewTest extends \Test\TestCase {
}
/**
- * @dataProvider hookPathProvider
* @param $root
* @param $path
* @param $shouldEmit
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('hookPathProvider')]
public function testHookPaths($root, $path, $shouldEmit): void {
$filesystemReflection = new \ReflectionClass(Filesystem::class);
$defaultRootValue = $filesystemReflection->getProperty('defaultInstance');
@@ -1608,7 +1605,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)
@@ -1623,7 +1620,7 @@ class ViewTest extends \Test\TestCase {
->method('getMountsForUser')
->willReturn($mounts);
- $mountProviderCollection = \OC::$server->getMountProviderCollection();
+ $mountProviderCollection = Server::get(IMountProviderCollection::class);
$mountProviderCollection->registerProvider($mountProvider);
return $mounts;
@@ -1720,16 +1717,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);
@@ -1915,7 +1912,6 @@ class ViewTest extends \Test\TestCase {
/**
* Test whether locks are set before and after the operation
*
- * @dataProvider basicOperationProviderForLocks
*
* @param string $operation operation name on the view
* @param array $operationArgs arguments for the operation
@@ -1927,6 +1923,7 @@ class ViewTest extends \Test\TestCase {
* @param int $expectedStrayLock expected lock after returning, should
* be null (unlock) for most operations
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('basicOperationProviderForLocks')]
public function testLockBasicOperation(
$operation,
$operationArgs,
@@ -1947,6 +1944,8 @@ class ViewTest extends \Test\TestCase {
/* Pause trash to avoid the trashbin intercepting rmdir and unlink calls */
Server::get(ITrashManager::class)->pauseTrash();
+ /* Same thing with encryption wrapper */
+ Server::get(IStorageFactory::class)->removeStorageWrapper('oc_encryption');
Filesystem::mount($storage, [], $this->user . '/');
@@ -2074,12 +2073,12 @@ class ViewTest extends \Test\TestCase {
/**
* Test locks for fopen with fclose at the end
*
- * @dataProvider basicOperationProviderForLocks
*
* @param string $operation operation name on the view
* @param array $operationArgs arguments for the operation
* @param string $path path of the locked item to check
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('basicOperationProviderForLocks')]
public function testLockBasicOperationUnlocksAfterException(
$operation,
$operationArgs,
@@ -2097,6 +2096,8 @@ class ViewTest extends \Test\TestCase {
/* Pause trash to avoid the trashbin intercepting rmdir and unlink calls */
Server::get(ITrashManager::class)->pauseTrash();
+ /* Same thing with encryption wrapper */
+ Server::get(IStorageFactory::class)->removeStorageWrapper('oc_encryption');
Filesystem::mount($storage, [], $this->user . '/');
@@ -2110,7 +2111,7 @@ class ViewTest extends \Test\TestCase {
$storage->expects($this->once())
->method($operation)
->willReturnCallback(
- function () {
+ function (): void {
throw new \Exception('Simulated exception');
}
);
@@ -2163,13 +2164,13 @@ class ViewTest extends \Test\TestCase {
/**
* Test locks for fopen with fclose at the end
*
- * @dataProvider basicOperationProviderForLocks
*
* @param string $operation operation name on the view
* @param array $operationArgs arguments for the operation
* @param string $path path of the locked item to check
* @param string $hookType hook type
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('basicOperationProviderForLocks')]
public function testLockBasicOperationUnlocksAfterCancelledHook(
$operation,
$operationArgs,
@@ -2208,12 +2209,12 @@ class ViewTest extends \Test\TestCase {
/**
* Test locks for rename or copy operation
*
- * @dataProvider lockFileRenameOrCopyDataProvider
*
* @param string $operation operation to be done on the view
* @param int $expectedLockTypeSourceDuring expected lock type on source file during
* the operation
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('lockFileRenameOrCopyDataProvider')]
public function testLockFileRename($operation, $expectedLockTypeSourceDuring): void {
$view = new View('/' . $this->user . '/files/');
@@ -2224,13 +2225,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);
@@ -2238,6 +2239,9 @@ class ViewTest extends \Test\TestCase {
$sourcePath = 'original.txt';
$targetPath = 'target.txt';
+ /* Disable encryption wrapper to avoid it intercepting mocked call */
+ Server::get(IStorageFactory::class)->removeStorageWrapper('oc_encryption');
+
Filesystem::mount($storage, [], $this->user . '/');
$storage->mkdir('files');
$view->file_put_contents($sourcePath, 'meh');
@@ -2291,6 +2295,9 @@ class ViewTest extends \Test\TestCase {
$sourcePath = 'original.txt';
$targetPath = 'target.txt';
+ /* Disable encryption wrapper to avoid it intercepting mocked call */
+ Server::get(IStorageFactory::class)->removeStorageWrapper('oc_encryption');
+
Filesystem::mount($storage, [], $this->user . '/');
$storage->mkdir('files');
$view->file_put_contents($sourcePath, 'meh');
@@ -2298,7 +2305,7 @@ class ViewTest extends \Test\TestCase {
$storage->expects($this->once())
->method('copy')
->willReturnCallback(
- function () {
+ function (): void {
throw new \Exception();
}
);
@@ -2392,13 +2399,13 @@ class ViewTest extends \Test\TestCase {
/**
* Test locks for rename or copy operation cross-storage
*
- * @dataProvider lockFileRenameOrCopyCrossStorageDataProvider
*
* @param string $viewOperation operation to be done on the view
* @param string $storageOperation operation to be mocked on the storage
* @param int $expectedLockTypeSourceDuring expected lock type on source file during
* the operation
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('lockFileRenameOrCopyCrossStorageDataProvider')]
public function testLockFileRenameCrossStorage($viewOperation, $storageOperation, $expectedLockTypeSourceDuring): void {
$view = new View('/' . $this->user . '/files/');
@@ -2413,13 +2420,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);
@@ -2427,6 +2434,9 @@ class ViewTest extends \Test\TestCase {
$sourcePath = 'original.txt';
$targetPath = 'substorage/target.txt';
+ /* Disable encryption wrapper to avoid it intercepting mocked call */
+ Server::get(IStorageFactory::class)->removeStorageWrapper('oc_encryption');
+
Filesystem::mount($storage, [], $this->user . '/');
Filesystem::mount($storage2, [], $this->user . '/files/substorage');
$storage->mkdir('files');
@@ -2550,14 +2560,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);
}
);
@@ -2657,8 +2667,8 @@ class ViewTest extends \Test\TestCase {
/**
* @param string $filter
* @param string[] $expected
- * @dataProvider mimeFilterProvider
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('mimeFilterProvider')]
public function testGetDirectoryContentMimeFilter($filter, $expected): void {
$storage1 = new Temporary();
$root = self::getUniqueID('/');
@@ -2778,7 +2788,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/FilesTest.php b/tests/lib/FilesTest.php
new file mode 100644
index 00000000000..2ba6ce2666b
--- /dev/null
+++ b/tests/lib/FilesTest.php
@@ -0,0 +1,42 @@
+<?php
+
+declare(strict_types=1);
+
+/**
+ * SPDX-FileCopyrightText: 2025 Nextcloud GmbH and Nextcloud contributors
+ * SPDX-License-Identifier: AGPL-3.0-or-later
+ */
+
+namespace Test;
+
+use OCP\Files;
+use OCP\ITempManager;
+use OCP\Server;
+
+class FilesTest extends TestCase {
+
+ /**
+ * Tests recursive folder deletion with rmdirr()
+ */
+ public function testRecursiveFolderDeletion(): void {
+ $baseDir = Server::get(ITempManager::class)->getTemporaryFolder() . '/';
+ mkdir($baseDir . 'a/b/c/d/e', 0777, true);
+ mkdir($baseDir . 'a/b/c1/d/e', 0777, true);
+ mkdir($baseDir . 'a/b/c2/d/e', 0777, true);
+ mkdir($baseDir . 'a/b1/c1/d/e', 0777, true);
+ mkdir($baseDir . 'a/b2/c1/d/e', 0777, true);
+ mkdir($baseDir . 'a/b3/c1/d/e', 0777, true);
+ mkdir($baseDir . 'a1/b', 0777, true);
+ mkdir($baseDir . 'a1/c', 0777, true);
+ file_put_contents($baseDir . 'a/test.txt', 'Hello file!');
+ file_put_contents($baseDir . 'a/b1/c1/test one.txt', 'Hello file one!');
+ file_put_contents($baseDir . 'a1/b/test two.txt', 'Hello file two!');
+ Files::rmdirr($baseDir . 'a');
+
+ $this->assertFalse(file_exists($baseDir . 'a'));
+ $this->assertTrue(file_exists($baseDir . 'a1'));
+
+ Files::rmdirr($baseDir);
+ $this->assertFalse(file_exists($baseDir));
+ }
+}
diff --git a/tests/lib/GlobalScale/ConfigTest.php b/tests/lib/GlobalScale/ConfigTest.php
index aa001268ecd..447b5886ce3 100644
--- a/tests/lib/GlobalScale/ConfigTest.php
+++ b/tests/lib/GlobalScale/ConfigTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2017 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
@@ -28,7 +29,7 @@ class ConfigTest extends TestCase {
if (!empty($mockMethods)) {
return $this->getMockBuilder(Config::class)
->setConstructorArgs([$this->config])
- ->setMethods($mockMethods)
+ ->onlyMethods($mockMethods)
->getMock();
}
@@ -47,12 +48,12 @@ class ConfigTest extends TestCase {
/**
- * @dataProvider dataTestOnlyInternalFederation
*
* @param bool $gsEnabled
* @param string $gsFederation
* @param bool $expected
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataTestOnlyInternalFederation')]
public function testOnlyInternalFederation($gsEnabled, $gsFederation, $expected): void {
$gsConfig = $this->getInstance(['isGlobalScaleEnabled']);
@@ -64,7 +65,7 @@ class ConfigTest extends TestCase {
$this->assertSame($expected, $gsConfig->onlyInternalFederation());
}
- public function dataTestOnlyInternalFederation() {
+ public static function dataTestOnlyInternalFederation(): array {
return [
[true, 'global', false],
[true, 'internal', true],
diff --git a/tests/lib/Group/Backend.php b/tests/lib/Group/Backend.php
index b55e51b72a4..3c068d8d64b 100644
--- a/tests/lib/Group/Backend.php
+++ b/tests/lib/Group/Backend.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2018-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
diff --git a/tests/lib/Group/DatabaseTest.php b/tests/lib/Group/DatabaseTest.php
index 593fbe60bf9..ee6b4156040 100644
--- a/tests/lib/Group/DatabaseTest.php
+++ b/tests/lib/Group/DatabaseTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -7,6 +8,8 @@
namespace Test\Group;
+use OC\Group\Database;
+
/**
* Class Database
*
@@ -27,7 +30,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 +45,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/Dummy.php b/tests/lib/Group/Dummy.php
index 4ba885c6cdd..5f2a81cf0aa 100644
--- a/tests/lib/Group/Dummy.php
+++ b/tests/lib/Group/Dummy.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
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/HideFromCollaborationTest.php b/tests/lib/Group/HideFromCollaborationTest.php
new file mode 100644
index 00000000000..5ff7c797508
--- /dev/null
+++ b/tests/lib/Group/HideFromCollaborationTest.php
@@ -0,0 +1,53 @@
+<?php
+
+declare(strict_types=1);
+
+/**
+ * SPDX-FileCopyrightText: 2025 Nextcloud GmbH and Nextcloud contributors
+ * SPDX-License-Identifier: AGPL-3.0-or-later
+ */
+
+namespace Test\Group;
+
+use OC\Group\Group;
+use OCP\EventDispatcher\IEventDispatcher;
+use OCP\Group\Backend\ABackend;
+use OCP\Group\Backend\IHideFromCollaborationBackend;
+use OCP\IUserManager;
+use PHPUnit\Framework\MockObject\MockObject;
+use Test\TestCase;
+
+abstract class HideFromCollaborationBackendTest extends ABackend implements IHideFromCollaborationBackend {
+
+}
+
+class HideFromCollaborationTest extends TestCase {
+
+ private IUserManager&MockObject $userManager;
+ private IEventDispatcher&MockObject $dispatcher;
+
+ protected function setUp(): void {
+ parent::setUp();
+
+ $this->userManager = $this->createMock(IUserManager::class);
+ $this->dispatcher = $this->createMock(IEventDispatcher::class);
+ }
+
+
+ public function testHideFromCollaboration(): void {
+ // Arrange
+ $backend1 = $this->createMock(HideFromCollaborationBackendTest::class);
+ $backend1->method('hideGroup')
+ ->willReturn(false);
+ $backend2 = $this->createMock(HideFromCollaborationBackendTest::class);
+ $backend2->method('hideGroup')
+ ->willReturn(true);
+ $group = new Group('group1', [$backend1, $backend2], $this->dispatcher, $this->userManager);
+
+ // Act
+ $result = $group->hideFromCollaboration();
+
+ // Assert
+ $this->assertTrue($result);
+ }
+}
diff --git a/tests/lib/Group/ManagerTest.php b/tests/lib/Group/ManagerTest.php
index 0f8d7a5ecc3..8515ef0e3e8 100644
--- a/tests/lib/Group/ManagerTest.php
+++ b/tests/lib/Group/ManagerTest.php
@@ -12,6 +12,11 @@ use OC\Group\Database;
use OC\User\Manager;
use OC\User\User;
use OCP\EventDispatcher\IEventDispatcher;
+use OCP\Group\Backend\ABackend;
+use OCP\Group\Backend\IAddToGroupBackend;
+use OCP\Group\Backend\ICreateGroupBackend;
+use OCP\Group\Backend\IGroupDetailsBackend;
+use OCP\Group\Backend\IRemoveFromGroupBackend;
use OCP\Group\Backend\ISearchableGroupBackend;
use OCP\GroupInterface;
use OCP\ICacheFactory;
@@ -21,7 +26,8 @@ use PHPUnit\Framework\MockObject\MockObject;
use Psr\Log\LoggerInterface;
use Test\TestCase;
-interface ISearchableGroupInterface extends ISearchableGroupBackend, GroupInterface {
+abstract class TestBackend extends ABackend implements ISearchableGroupBackend, IAddToGroupBackend, ICreateGroupBackend, IGroupDetailsBackend, IRemoveFromGroupBackend, GroupInterface {
+
}
class ManagerTest extends TestCase {
@@ -65,18 +71,18 @@ class ManagerTest extends TestCase {
*/
private function getTestBackend($implementedActions = null) {
if ($implementedActions === null) {
- $implementedActions =
- GroupInterface::ADD_TO_GROUP |
- GroupInterface::REMOVE_FROM_GOUP |
- GroupInterface::COUNT_USERS |
- GroupInterface::CREATE_GROUP |
- GroupInterface::DELETE_GROUP;
+ $implementedActions
+ = GroupInterface::ADD_TO_GROUP
+ | GroupInterface::REMOVE_FROM_GOUP
+ | GroupInterface::COUNT_USERS
+ | GroupInterface::CREATE_GROUP
+ | GroupInterface::DELETE_GROUP;
}
// need to declare it this way due to optional methods
// thanks to the implementsActions logic
- $backend = $this->getMockBuilder(ISearchableGroupInterface::class)
+ $backend = $this->getMockBuilder(TestBackend::class)
->disableOriginalConstructor()
- ->setMethods([
+ ->onlyMethods([
'getGroupDetails',
'implementsActions',
'getUserGroups',
@@ -207,12 +213,12 @@ class ManagerTest extends TestCase {
/** @var \PHPUnit\Framework\MockObject\MockObject|\OC\Group\Backend $backend */
$backendGroupCreated = false;
$backend = $this->getTestBackend(
- GroupInterface::ADD_TO_GROUP |
- GroupInterface::REMOVE_FROM_GOUP |
- GroupInterface::COUNT_USERS |
- GroupInterface::CREATE_GROUP |
- GroupInterface::DELETE_GROUP |
- GroupInterface::GROUP_DETAILS
+ GroupInterface::ADD_TO_GROUP
+ | GroupInterface::REMOVE_FROM_GOUP
+ | GroupInterface::COUNT_USERS
+ | GroupInterface::CREATE_GROUP
+ | GroupInterface::DELETE_GROUP
+ | GroupInterface::GROUP_DETAILS
);
$backend->expects($this->any())
->method('groupExists')
@@ -236,12 +242,12 @@ class ManagerTest extends TestCase {
/** @var \PHPUnit\Framework\MockObject\MockObject|\OC\Group\Backend $backend */
$backendGroupCreated = false;
$backend = $this->getTestBackend(
- GroupInterface::ADD_TO_GROUP |
- GroupInterface::REMOVE_FROM_GOUP |
- GroupInterface::COUNT_USERS |
- GroupInterface::CREATE_GROUP |
- GroupInterface::DELETE_GROUP |
- GroupInterface::GROUP_DETAILS
+ GroupInterface::ADD_TO_GROUP
+ | GroupInterface::REMOVE_FROM_GOUP
+ | GroupInterface::COUNT_USERS
+ | GroupInterface::CREATE_GROUP
+ | GroupInterface::DELETE_GROUP
+ | GroupInterface::GROUP_DETAILS
);
$groupName = str_repeat('x', 256);
$backend->expects($this->any())
@@ -283,9 +289,10 @@ class ManagerTest extends TestCase {
->with('1')
->willReturn(['group1']);
$backend->expects($this->once())
- ->method('groupExists')
- ->with('group1')
- ->willReturn(true);
+ ->method('getGroupDetails')
+ ->willReturnMap([
+ ['group1', ['displayName' => 'group1']],
+ ]);
$manager = new \OC\Group\Manager($this->userManager, $this->dispatcher, $this->logger, $this->cache, $this->remoteIpAddress);
$manager->addBackend($backend);
@@ -306,8 +313,11 @@ class ManagerTest extends TestCase {
->with('1')
->willReturn(['group1']);
$backend1->expects($this->any())
- ->method('groupExists')
- ->willReturn(true);
+ ->method('getGroupDetails')
+ ->willReturnMap([
+ ['group1', ['displayName' => 'group1']],
+ ['group12', []],
+ ]);
/**
* @var \PHPUnit\Framework\MockObject\MockObject | \OC\Group\Backend $backend2
@@ -318,8 +328,11 @@ class ManagerTest extends TestCase {
->with('1')
->willReturn(['group12', 'group1']);
$backend2->expects($this->any())
- ->method('groupExists')
- ->willReturn(true);
+ ->method('getGroupDetails')
+ ->willReturnMap([
+ ['group12', ['displayName' => 'group12']],
+ ['group1', ['displayName' => 'group1']],
+ ]);
$manager = new \OC\Group\Manager($this->userManager, $this->dispatcher, $this->logger, $this->cache, $this->remoteIpAddress);
$manager->addBackend($backend1);
@@ -335,7 +348,7 @@ class ManagerTest extends TestCase {
public function testSearchMultipleBackendsLimitAndOffset(): void {
/**
- * @var \PHPUnit\Framework\MockObject\MockObject | \OC\Group\Backend $backend1
+ * @var \PHPUnit\Framework\MockObject\MockObject|\OC\Group\Backend $backend1
*/
$backend1 = $this->getTestBackend();
$backend1->expects($this->once())
@@ -343,11 +356,16 @@ class ManagerTest extends TestCase {
->with('1', 2, 1)
->willReturn(['group1']);
$backend1->expects($this->any())
- ->method('groupExists')
- ->willReturn(true);
+ ->method('getGroupDetails')
+ ->willReturnMap([
+ [1, []],
+ [2, []],
+ ['group1', ['displayName' => 'group1']],
+ ['group12', []],
+ ]);
/**
- * @var \PHPUnit\Framework\MockObject\MockObject | \OC\Group\Backend $backend2
+ * @var \PHPUnit\Framework\MockObject\MockObject|\OC\Group\Backend $backend2
*/
$backend2 = $this->getTestBackend();
$backend2->expects($this->once())
@@ -355,8 +373,13 @@ class ManagerTest extends TestCase {
->with('1', 2, 1)
->willReturn(['group12']);
$backend2->expects($this->any())
- ->method('groupExists')
- ->willReturn(true);
+ ->method('getGroupDetails')
+ ->willReturnMap([
+ [1, []],
+ [2, []],
+ ['group1', []],
+ ['group12', ['displayName' => 'group12']],
+ ]);
$manager = new \OC\Group\Manager($this->userManager, $this->dispatcher, $this->logger, $this->cache, $this->remoteIpAddress);
$manager->addBackend($backend1);
@@ -429,7 +452,7 @@ class ManagerTest extends TestCase {
$manager = new \OC\Group\Manager($this->userManager, $this->dispatcher, $this->logger, $this->cache, $this->remoteIpAddress);
$manager->addBackend($backend);
- /** @var \OC\User\User|\PHPUnit\Framework\MockObject\MockObject $user */
+ /** @var User|\PHPUnit\Framework\MockObject\MockObject $user */
$user = $this->createMock(IUser::class);
$user->method('getUID')
->willReturn('myUID');
@@ -459,7 +482,7 @@ class ManagerTest extends TestCase {
$manager = new \OC\Group\Manager($this->userManager, $this->dispatcher, $this->logger, $this->cache, $this->remoteIpAddress);
$manager->addBackend($backend);
- /** @var \OC\User\User|\PHPUnit\Framework\MockObject\MockObject $user */
+ /** @var User|\PHPUnit\Framework\MockObject\MockObject $user */
$user = $this->createMock(IUser::class);
$user->expects($this->atLeastOnce())
->method('getUID')
@@ -932,12 +955,12 @@ class ManagerTest extends TestCase {
* @var \PHPUnit\Framework\MockObject\MockObject | \OC\Group\Backend $backend
*/
$backend = $this->getTestBackend(
- GroupInterface::ADD_TO_GROUP |
- GroupInterface::REMOVE_FROM_GOUP |
- GroupInterface::COUNT_USERS |
- GroupInterface::CREATE_GROUP |
- GroupInterface::DELETE_GROUP |
- GroupInterface::GROUP_DETAILS
+ GroupInterface::ADD_TO_GROUP
+ | GroupInterface::REMOVE_FROM_GOUP
+ | GroupInterface::COUNT_USERS
+ | GroupInterface::CREATE_GROUP
+ | GroupInterface::DELETE_GROUP
+ | GroupInterface::GROUP_DETAILS
);
$backend->expects($this->any())
->method('getGroupDetails')
diff --git a/tests/lib/Group/MetaDataTest.php b/tests/lib/Group/MetaDataTest.php
index 70f2022ae78..dee59eab8da 100644
--- a/tests/lib/Group/MetaDataTest.php
+++ b/tests/lib/Group/MetaDataTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -7,12 +8,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 +24,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 +39,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 455bd288351..140be04ec64 100644
--- a/tests/lib/HelperStorageTest.php
+++ b/tests/lib/HelperStorageTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -7,9 +8,13 @@
namespace Test;
+use OC\Files\Filesystem;
+use OC\Files\Storage\Storage;
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;
/**
@@ -22,9 +27,9 @@ class HelperStorageTest extends \Test\TestCase {
/** @var string */
private $user;
- /** @var \OC\Files\Storage\Storage */
+ /** @var Storage */
private $storageMock;
- /** @var \OC\Files\Storage\Storage */
+ /** @var Storage */
private $storage;
private bool $savedQuotaIncludeExternalStorage;
@@ -35,12 +40,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 +59,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();
}
@@ -67,17 +72,17 @@ class HelperStorageTest extends \Test\TestCase {
* free space
*
* @param int $freeSpace free space value
- * @return \OC\Files\Storage\Storage
+ * @return Storage
*/
private function getStorageMock($freeSpace = 12) {
$this->storageMock = $this->getMockBuilder(Temporary::class)
- ->setMethods(['free_space'])
+ ->onlyMethods(['free_space'])
->setConstructorArgs([[]])
->getMock();
$this->storageMock->expects($this->once())
->method('free_space')
- ->willReturn(12);
+ ->willReturn($freeSpace);
return $this->storageMock;
}
@@ -86,7 +91,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('');
@@ -94,6 +99,7 @@ class HelperStorageTest extends \Test\TestCase {
$this->assertEquals(5, $storageInfo['used']);
$this->assertEquals(17, $storageInfo['total']);
}
+
private function getIncludeExternalStorage(): bool {
$class = new \ReflectionClass(\OC_Helper::class);
$prop = $class->getProperty('quotaIncludeExternalStorage');
@@ -113,16 +119,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']);
@@ -134,19 +140,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('');
@@ -164,16 +170,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('');
@@ -189,13 +195,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']);
@@ -209,13 +215,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']);
@@ -231,13 +237,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..19eca59ac80 100644
--- a/tests/lib/HookHelper.php
+++ b/tests/lib/HookHelper.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -8,6 +9,7 @@
namespace Test;
use OC\Files\Filesystem;
+use OCP\Util;
/**
* Helper class to register hooks on
@@ -17,38 +19,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..6c00da2eaa3 100644
--- a/tests/lib/Hooks/BasicEmitterTest.php
+++ b/tests/lib/Hooks/BasicEmitterTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2018-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -7,6 +8,9 @@
namespace Test\Hooks;
+use OC\Hooks\BasicEmitter;
+use OC\Hooks\Emitter;
+
/**
* Class DummyEmitter
*
@@ -14,7 +18,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);
}
@@ -32,7 +36,7 @@ class EmittedException extends \Exception {
class BasicEmitterTest extends \Test\TestCase {
/**
- * @var \OC\Hooks\Emitter $emitter
+ * @var Emitter $emitter
*/
protected $emitter;
@@ -49,17 +53,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 +71,7 @@ class BasicEmitterTest extends \Test\TestCase {
$this->emitter->emitEvent('Test', 'test');
}
-
+
public function testNonStaticCallback(): void {
$this->expectException(\Test\Hooks\EmittedException::class);
@@ -77,7 +81,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 +92,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 +104,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 +116,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 +128,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 +140,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 +153,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 +164,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 +179,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 +192,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 +205,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 +219,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 +237,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 +252,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 +267,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..e76b66b52d7 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',
@@ -151,9 +151,9 @@ class ClientTest extends \Test\TestCase {
}
/**
- * @dataProvider dataPreventLocalAddress
* @param string $uri
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataPreventLocalAddress')]
public function testPreventLocalAddressDisabledByGlobalConfig(string $uri): void {
$this->config->expects($this->once())
->method('getSystemValueBool')
@@ -164,9 +164,9 @@ class ClientTest extends \Test\TestCase {
}
/**
- * @dataProvider dataPreventLocalAddress
* @param string $uri
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataPreventLocalAddress')]
public function testPreventLocalAddressDisabledByOption(string $uri): void {
$this->config->expects($this->never())
->method('getSystemValueBool');
@@ -177,9 +177,9 @@ class ClientTest extends \Test\TestCase {
}
/**
- * @dataProvider dataPreventLocalAddress
* @param string $uri
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataPreventLocalAddress')]
public function testPreventLocalAddressOnGet(string $uri): void {
$host = parse_url($uri, PHP_URL_HOST);
$this->expectException(LocalServerException::class);
@@ -192,9 +192,9 @@ class ClientTest extends \Test\TestCase {
}
/**
- * @dataProvider dataPreventLocalAddress
* @param string $uri
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataPreventLocalAddress')]
public function testPreventLocalAddressOnHead(string $uri): void {
$host = parse_url($uri, PHP_URL_HOST);
$this->expectException(LocalServerException::class);
@@ -207,9 +207,9 @@ class ClientTest extends \Test\TestCase {
}
/**
- * @dataProvider dataPreventLocalAddress
* @param string $uri
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataPreventLocalAddress')]
public function testPreventLocalAddressOnPost(string $uri): void {
$host = parse_url($uri, PHP_URL_HOST);
$this->expectException(LocalServerException::class);
@@ -222,9 +222,9 @@ class ClientTest extends \Test\TestCase {
}
/**
- * @dataProvider dataPreventLocalAddress
* @param string $uri
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataPreventLocalAddress')]
public function testPreventLocalAddressOnPut(string $uri): void {
$host = parse_url($uri, PHP_URL_HOST);
$this->expectException(LocalServerException::class);
@@ -237,9 +237,9 @@ class ClientTest extends \Test\TestCase {
}
/**
- * @dataProvider dataPreventLocalAddress
* @param string $uri
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataPreventLocalAddress')]
public function testPreventLocalAddressOnDelete(string $uri): void {
$host = parse_url($uri, PHP_URL_HOST);
$this->expectException(LocalServerException::class);
@@ -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/Http/Client/NegativeDnsCacheTest.php b/tests/lib/Http/Client/NegativeDnsCacheTest.php
index ba91e95a906..eb0f86f5c7a 100644
--- a/tests/lib/Http/Client/NegativeDnsCacheTest.php
+++ b/tests/lib/Http/Client/NegativeDnsCacheTest.php
@@ -30,7 +30,7 @@ class NegativeDnsCacheTest extends \Test\TestCase {
->method('createLocal')
->with('NegativeDnsCache')
->willReturn($this->cache);
-
+
$this->negativeDnsCache = new NegativeDnsCache($this->cacheFactory);
}
diff --git a/tests/lib/Http/Client/ResponseTest.php b/tests/lib/Http/Client/ResponseTest.php
index 291dc287148..1acf1eb1cbd 100644
--- a/tests/lib/Http/Client/ResponseTest.php
+++ b/tests/lib/Http/Client/ResponseTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2017-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
diff --git a/tests/lib/ImageTest.php b/tests/lib/ImageTest.php
index 5de5435335a..02181fffff9 100644
--- a/tests/lib/ImageTest.php
+++ b/tests/lib/ImageTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -271,7 +272,7 @@ class ImageTest extends \Test\TestCase {
$this->assertEquals(15, $img->height());
}
- public static function sampleProvider() {
+ public static function sampleProvider(): array {
return [
['testimage.png', [200, 100], [100, 100]],
['testimage.jpg', [840, 840], [840, 525]],
@@ -280,12 +281,12 @@ class ImageTest extends \Test\TestCase {
}
/**
- * @dataProvider sampleProvider
*
* @param string $filename
* @param int[] $asked
* @param int[] $expected
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('sampleProvider')]
public function testFitIn($filename, $asked, $expected): void {
$img = new Image();
$img->loadFromFile(OC::$SERVERROOT . '/tests/data/' . $filename);
@@ -294,7 +295,7 @@ class ImageTest extends \Test\TestCase {
$this->assertEquals($expected[1], $img->height());
}
- public static function sampleFilenamesProvider() {
+ public static function sampleFilenamesProvider(): array {
return [
['testimage.png'],
['testimage.jpg'],
@@ -305,10 +306,10 @@ class ImageTest extends \Test\TestCase {
/**
* Image should not be resized if it's already smaller than what is required
*
- * @dataProvider sampleFilenamesProvider
*
* @param string $filename
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('sampleFilenamesProvider')]
public function testScaleDownToFitWhenSmallerAlready($filename): void {
$img = new Image();
$img->loadFromFile(OC::$SERVERROOT . '/tests/data/' . $filename);
@@ -328,7 +329,7 @@ class ImageTest extends \Test\TestCase {
);
}
- public static function largeSampleProvider() {
+ public static function largeSampleProvider(): array {
return [
['testimage.png', [200, 100], [100, 100]],
['testimage.jpg', [840, 840], [840, 525]],
@@ -336,12 +337,12 @@ class ImageTest extends \Test\TestCase {
}
/**
- * @dataProvider largeSampleProvider
*
* @param string $filename
* @param int[] $asked
* @param int[] $expected
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('largeSampleProvider')]
public function testScaleDownWhenBigger($filename, $asked, $expected): void {
$img = new Image();
$img->loadFromFile(OC::$SERVERROOT . '/tests/data/' . $filename);
@@ -351,7 +352,7 @@ class ImageTest extends \Test\TestCase {
$this->assertEquals($expected[1], $img->height());
}
- public function convertDataProvider() {
+ public static function convertDataProvider(): array {
return [
[ 'image/gif'],
[ 'image/jpeg'],
@@ -359,9 +360,7 @@ class ImageTest extends \Test\TestCase {
];
}
- /**
- * @dataProvider convertDataProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('convertDataProvider')]
public function testConvert($mimeType): void {
$img = new Image();
$img->loadFromFile(OC::$SERVERROOT . '/tests/data/testimage.png');
diff --git a/tests/lib/InfoXmlTest.php b/tests/lib/InfoXmlTest.php
index e579a4b4efd..e92ee5b9c09 100644
--- a/tests/lib/InfoXmlTest.php
+++ b/tests/lib/InfoXmlTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
@@ -7,6 +8,7 @@
namespace Test;
use OCP\App\IAppManager;
+use OCP\AppFramework\App;
use OCP\Server;
/**
@@ -23,7 +25,7 @@ class InfoXmlTest extends TestCase {
$this->appManager = Server::get(IAppManager::class);
}
- public function dataApps() {
+ public static function dataApps(): array {
return [
['admin_audit'],
['comments'],
@@ -48,85 +50,84 @@ class InfoXmlTest extends TestCase {
}
/**
- * @dataProvider dataApps
- *
* @param string $app
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataApps')]
public function testClasses($app): void {
$appInfo = $this->appManager->getAppInfo($app);
$appPath = $this->appManager->getAppPath($app);
\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/InitialStateServiceTest.php b/tests/lib/InitialStateServiceTest.php
index f58d54cb26b..9081aa93b84 100644
--- a/tests/lib/InitialStateServiceTest.php
+++ b/tests/lib/InitialStateServiceTest.php
@@ -36,7 +36,7 @@ class InitialStateServiceTest extends TestCase {
);
}
- public function staticData(): array {
+ public static function staticData(): array {
return [
['string'],
[23],
@@ -49,9 +49,7 @@ class InitialStateServiceTest extends TestCase {
];
}
- /**
- * @dataProvider staticData
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('staticData')]
public function testStaticData(mixed $value): void {
$this->service->provideInitialState('test', 'key', $value);
$data = $this->service->getInitialStates();
@@ -88,9 +86,7 @@ class InitialStateServiceTest extends TestCase {
);
}
- /**
- * @dataProvider staticData
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('staticData')]
public function testLazyData(mixed $value): void {
$this->service->provideLazyInitialState('test', 'key', function () use ($value) {
return $value;
diff --git a/tests/lib/InstallerTest.php b/tests/lib/InstallerTest.php
index d27ca6e2159..1813d2cd151 100644
--- a/tests/lib/InstallerTest.php
+++ b/tests/lib/InstallerTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -15,6 +16,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 +48,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 +75,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,21 +99,21 @@ 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);
}
- public function updateArrayProvider() {
+ public static function updateArrayProvider(): array {
return [
// Update available
[
@@ -145,10 +147,10 @@ class InstallerTest extends TestCase {
}
/**
- * @dataProvider updateArrayProvider
* @param array $appArray
* @param string|bool $updateAvailable
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('updateArrayProvider')]
public function testIsUpdateAvailable(array $appArray, $updateAvailable): void {
$this->appFetcher
->expects($this->once())
@@ -337,7 +339,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 +417,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 +501,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 +580,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 +674,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 c5a4f255397..a8a2596a3d8 100644
--- a/tests/lib/IntegrityCheck/CheckerTest.php
+++ b/tests/lib/IntegrityCheck/CheckerTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -8,6 +9,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 +56,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 +113,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 +447,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 +471,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')
@@ -713,7 +715,9 @@ class CheckerTest extends TestCase {
*/
public function testVerifyCoreSignatureWithModifiedMimetypelistSignatureData(): void {
$shippedMimetypeAliases = (array)json_decode(file_get_contents(\OC::$SERVERROOT . '/resources/config/mimetypealiases.dist.json'));
+ $shippedMimetypeNames = (array)json_decode(file_get_contents(\OC::$SERVERROOT . '/resources/config/mimetypenames.dist.json'));
$allAliases = array_merge($shippedMimetypeAliases, ['my-custom/mimetype' => 'custom']);
+ $allMimetypeNames = array_merge($shippedMimetypeNames, ['my-custom/mimetype' => 'Custom Document']);
$this->mimeTypeDetector
->method('getOnlyDefaultAliases')
@@ -723,9 +727,14 @@ class CheckerTest extends TestCase {
->method('getAllAliases')
->willReturn($allAliases);
+ $this->mimeTypeDetector
+ ->method('getAllNamings')
+ ->willReturn($allMimetypeNames);
+
$oldMimetypeList = new GenerateMimetypeFileBuilder();
$all = $this->mimeTypeDetector->getAllAliases();
- $newFile = $oldMimetypeList->generateFile($all);
+ $namings = $this->mimeTypeDetector->getAllNamings();
+ $newFile = $oldMimetypeList->generateFile($all, $namings);
// When updating the mimetype list the test assets need to be updated as well
// 1. Update core/js/mimetypelist.js with the new generated js by running the test with the next line uncommented:
@@ -1070,8 +1079,8 @@ class CheckerTest extends TestCase {
/**
* @param string $channel
* @param bool $isCodeSigningEnforced
- * @dataProvider channelDataProvider
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('channelDataProvider')]
public function testIsCodeCheckEnforced($channel, $isCodeSigningEnforced): void {
$this->serverVersion
->expects($this->once())
@@ -1088,8 +1097,8 @@ class CheckerTest extends TestCase {
/**
* @param string $channel
- * @dataProvider channelDataProvider
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('channelDataProvider')]
public function testIsCodeCheckEnforcedWithDisabledConfigSwitch($channel): void {
$this->serverVersion
->expects($this->once())
diff --git a/tests/lib/IntegrityCheck/Helpers/AppLocatorTest.php b/tests/lib/IntegrityCheck/Helpers/AppLocatorTest.php
index 6d3006bb3c4..837b397ac1f 100644
--- a/tests/lib/IntegrityCheck/Helpers/AppLocatorTest.php
+++ b/tests/lib/IntegrityCheck/Helpers/AppLocatorTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -23,7 +24,7 @@ class AppLocatorTest extends TestCase {
$this->assertSame(\OC_App::getAppPath('files'), $this->locator->getAppPath('files'));
}
-
+
public function testGetAppPathNotExistentApp(): void {
$this->expectException(\Exception::class);
$this->expectExceptionMessage('App not found');
diff --git a/tests/lib/IntegrityCheck/Helpers/EnvironmentHelperTest.php b/tests/lib/IntegrityCheck/Helpers/EnvironmentHelperTest.php
index 379eb178b06..caa5ed2e782 100644
--- a/tests/lib/IntegrityCheck/Helpers/EnvironmentHelperTest.php
+++ b/tests/lib/IntegrityCheck/Helpers/EnvironmentHelperTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
diff --git a/tests/lib/IntegrityCheck/Helpers/FileAccessHelperTest.php b/tests/lib/IntegrityCheck/Helpers/FileAccessHelperTest.php
index 866850b7cff..b8bec35328d 100644
--- a/tests/lib/IntegrityCheck/Helpers/FileAccessHelperTest.php
+++ b/tests/lib/IntegrityCheck/Helpers/FileAccessHelperTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -8,6 +9,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 +23,7 @@ class FileAccessHelperTest extends TestCase {
}
public function testReadAndWrite(): void {
- $tempManager = \OC::$server->getTempManager();
+ $tempManager = Server::get(ITempManager::class);
$filePath = $tempManager->getTemporaryFile();
$data = 'SomeDataGeneratedByIntegrityCheck';
@@ -28,7 +31,7 @@ class FileAccessHelperTest extends TestCase {
$this->assertSame($data, $this->fileAccessHelper->file_get_contents($filePath));
}
-
+
public function testFile_put_contentsWithException(): void {
$this->expectException(\Exception::class);
$this->expectExceptionMessage('Failed to write into /anabsolutelynotexistingfolder/on/the/system.txt');
@@ -38,10 +41,10 @@ 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')));
}
-
+
public function testAssertDirectoryExistsWithException(): void {
$this->expectException(\Exception::class);
$this->expectExceptionMessage('Directory /anabsolutelynotexistingfolder/on/the/system does not exist.');
@@ -50,7 +53,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/IntegrityCheck/Iterator/ExcludeFileByNameFilterIteratorTest.php b/tests/lib/IntegrityCheck/Iterator/ExcludeFileByNameFilterIteratorTest.php
index 14cc8851178..dfd0941bd20 100644
--- a/tests/lib/IntegrityCheck/Iterator/ExcludeFileByNameFilterIteratorTest.php
+++ b/tests/lib/IntegrityCheck/Iterator/ExcludeFileByNameFilterIteratorTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2018 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2015 ownCloud, Inc.
@@ -17,11 +18,11 @@ class ExcludeFileByNameFilterIteratorTest extends TestCase {
parent::setUp();
$this->filter = $this->getMockBuilder(ExcludeFileByNameFilterIterator::class)
->disableOriginalConstructor()
- ->setMethods(['current'])
+ ->onlyMethods(['current'])
->getMock();
}
- public function fileNameProvider(): array {
+ public static function fileNameProvider(): array {
return [
['a file', true],
['Thumbs.db', false],
@@ -35,14 +36,14 @@ class ExcludeFileByNameFilterIteratorTest extends TestCase {
}
/**
- * @dataProvider fileNameProvider
* @param string $fileName
* @param bool $expectedResult
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('fileNameProvider')]
public function testAcceptForFiles($fileName, $expectedResult): void {
$iteratorMock = $this->getMockBuilder(\RecursiveDirectoryIterator::class)
->disableOriginalConstructor()
- ->setMethods(['getFilename', 'isDir'])
+ ->onlyMethods(['getFilename', 'isDir'])
->getMock();
$iteratorMock->method('getFilename')
@@ -57,14 +58,14 @@ class ExcludeFileByNameFilterIteratorTest extends TestCase {
}
/**
- * @dataProvider fileNameProvider
* @param string $fileName
* @param bool $expectedResult
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('fileNameProvider')]
public function testAcceptForDirs($fileName, $expectedResult): void {
$iteratorMock = $this->getMockBuilder(\RecursiveDirectoryIterator::class)
->disableOriginalConstructor()
- ->setMethods(['getFilename', 'isDir'])
+ ->onlyMethods(['getFilename', 'isDir'])
->getMock();
$iteratorMock->method('getFilename')
diff --git a/tests/lib/L10N/FactoryTest.php b/tests/lib/L10N/FactoryTest.php
index cd66217c49d..8c15baba9f6 100644
--- a/tests/lib/L10N/FactoryTest.php
+++ b/tests/lib/L10N/FactoryTest.php
@@ -278,10 +278,9 @@ class FactoryTest extends TestCase {
}
/**
- * @dataProvider dataFindAvailableLanguages
- *
* @param string|null $app
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataFindAvailableLanguages')]
public function testFindAvailableLanguages($app): void {
$factory = $this->getFactory(['findL10nDir']);
$factory->expects(self::once())
@@ -324,13 +323,13 @@ class FactoryTest extends TestCase {
}
/**
- * @dataProvider dataLanguageExists
*
* @param string|null $app
* @param string $lang
* @param string[] $availableLanguages
* @param string $expected
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataLanguageExists')]
public function testLanguageExists($app, $lang, array $availableLanguages, $expected): void {
$factory = $this->getFactory(['findAvailableLanguages']);
$factory->expects(($lang === 'en') ? self::never() : self::once())
@@ -364,13 +363,13 @@ class FactoryTest extends TestCase {
}
/**
- * @dataProvider dataSetLanguageFromRequest
*
* @param string|null $app
* @param string $header
* @param string[] $availableLanguages
* @param string $expected
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataSetLanguageFromRequest')]
public function testGetLanguageFromRequest($app, $header, array $availableLanguages, $expected): void {
$factory = $this->getFactory(['findAvailableLanguages', 'respectDefaultLanguage']);
$factory->expects(self::once())
@@ -409,11 +408,11 @@ class FactoryTest extends TestCase {
}
/**
- * @dataProvider dataGetL10nFilesForApp
*
* @param string $app
* @param string $expected
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataGetL10nFilesForApp')]
public function testGetL10nFilesForApp($app, $lang, $expected): void {
$factory = $this->getFactory();
if (in_array($app, ['settings','files'])) {
@@ -442,11 +441,11 @@ class FactoryTest extends TestCase {
}
/**
- * @dataProvider dataFindL10NDir
*
* @param string $app
* @param string $expected
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataFindL10NDir')]
public function testFindL10NDir($app, $expected): void {
$factory = $this->getFactory();
if (in_array($app, ['settings','files'])) {
@@ -479,12 +478,12 @@ class FactoryTest extends TestCase {
}
/**
- * @dataProvider dataFindLanguage
*
* @param bool $loggedIn
* @param array $availableLang
* @param string $expected
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataFindLanguage')]
public function testFindLanguage($loggedIn, $availableLang, $expected): void {
$userLang = 'nl';
$browserLang = 'de';
@@ -671,13 +670,13 @@ class FactoryTest extends TestCase {
/**
* test if we respect default language if possible
*
- * @dataProvider dataTestRespectDefaultLanguage
*
* @param string $lang
* @param string $defaultLanguage
* @param bool $langExists
* @param string $expected
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataTestRespectDefaultLanguage')]
public function testRespectDefaultLanguage($lang, $defaultLanguage, $langExists, $expected): void {
$factory = $this->getFactory(['languageExists']);
$factory->expects(self::any())
@@ -703,13 +702,13 @@ class FactoryTest extends TestCase {
* - if available languages set is not reduced to an empty set if
* the reduce config is an empty set
*
- * @dataProvider dataTestReduceToLanguages
*
* @param string $lang
* @param array $availableLanguages
* @param array $reducedLanguageSet
* @param array $expected
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataTestReduceToLanguages')]
public function testReduceLanguagesByConfiguration(string $lang, array $availableLanguages, array $reducedLanguageSet, array $expected): void {
$factory = $this->getFactory(['findAvailableLanguages', 'languageExists']);
$factory->expects(self::any())
@@ -744,9 +743,7 @@ class FactoryTest extends TestCase {
];
}
- /**
- * @dataProvider languageIteratorRequestProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('languageIteratorRequestProvider')]
public function testGetLanguageIterator(bool $hasSession, bool $mockUser): void {
$factory = $this->getFactory();
$user = null;
@@ -777,9 +774,7 @@ class FactoryTest extends TestCase {
];
}
- /**
- * @dataProvider dataGetLanguageDirection
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataGetLanguageDirection')]
public function testGetLanguageDirection(string $language, string $expectedDirection) {
$factory = $this->getFactory();
diff --git a/tests/lib/L10N/L10nTest.php b/tests/lib/L10N/L10nTest.php
index 32b81cf06a7..842f1bc5eda 100644
--- a/tests/lib/L10N/L10nTest.php
+++ b/tests/lib/L10N/L10nTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -16,6 +17,8 @@ use OCP\IConfig;
use OCP\IRequest;
use OCP\IUserSession;
use OCP\L10N\IFactory;
+use OCP\Server;
+use OCP\Util;
use Test\TestCase;
/**
@@ -28,9 +31,9 @@ class L10nTest extends TestCase {
* @return Factory
*/
protected function getFactory() {
- /** @var \OCP\IConfig $config */
+ /** @var IConfig $config */
$config = $this->createMock(IConfig::class);
- /** @var \OCP\IRequest $request */
+ /** @var IRequest $request */
$request = $this->createMock(IRequest::class);
/** @var IUserSession $userSession */
$userSession = $this->createMock(IUserSession::class);
@@ -96,7 +99,7 @@ class L10nTest extends TestCase {
$this->assertEquals('5 Dateien', (string)$l->n('%n file', '%n files', 5));
}
- public function dataPlaceholders(): array {
+ public static function dataPlaceholders(): array {
return [
['Ordered placeholders one %s two %s', 'Placeholder one 1 two 2'],
['Reordered placeholders one %s two %s', 'Placeholder two 2 one 1'],
@@ -105,11 +108,11 @@ class L10nTest extends TestCase {
}
/**
- * @dataProvider dataPlaceholders
*
* @param $string
* @param $expected
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataPlaceholders')]
public function testPlaceholders($string, $expected): void {
$transFile = \OC::$SERVERROOT . '/tests/data/l10n/de.json';
$l = new L10N($this->getFactory(), 'test', 'de', 'de_AT', [$transFile]);
@@ -117,7 +120,7 @@ class L10nTest extends TestCase {
$this->assertEquals($expected, $l->t($string, ['1', '2']));
}
- public function localizationData() {
+ public static function localizationData(): array {
return [
// timestamp as string
["February 13, 2009, 11:31:30\xE2\x80\xAFPM UTC", 'en', 'en_US', 'datetime', '1234567890'],
@@ -153,15 +156,13 @@ class L10nTest extends TestCase {
];
}
- /**
- * @dataProvider localizationData
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('localizationData')]
public function testNumericStringLocalization($expectedDate, $lang, $locale, $type, $value): void {
$l = new L10N($this->getFactory(), 'test', $lang, $locale, []);
$this->assertSame($expectedDate, $l->l($type, $value));
}
- public function firstDayData() {
+ public static function firstDayData(): array {
return [
[1, 'de', 'de_DE'],
[0, 'en', 'en_US'],
@@ -169,17 +170,17 @@ class L10nTest extends TestCase {
}
/**
- * @dataProvider firstDayData
* @param $expected
* @param $lang
* @param $locale
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('firstDayData')]
public function testFirstWeekDay($expected, $lang, $locale): void {
$l = new L10N($this->getFactory(), 'test', $lang, $locale, []);
$this->assertSame($expected, $l->l('firstday', 'firstday'));
}
- public function jsDateData() {
+ public static function jsDateData(): array {
return [
['dd.MM.yy', 'de', 'de_DE'],
['M/d/yy', 'en', 'en_US'],
@@ -187,11 +188,11 @@ class L10nTest extends TestCase {
}
/**
- * @dataProvider jsDateData
* @param $expected
* @param $lang
* @param $locale
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('jsDateData')]
public function testJSDate($expected, $lang, $locale): void {
$l = new L10N($this->getFactory(), 'test', $lang, $locale, []);
$this->assertSame($expected, $l->l('jsdate', 'jsdate'));
@@ -203,31 +204,28 @@ 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']));
}
/**
- * @dataProvider findLanguageFromLocaleData
* @param $locale
* @param $language
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('findLanguageFromLocaleData')]
public function testFindLanguageFromLocale($locale, $language): void {
$this->assertEquals(
$language,
- \OC::$server->get(IFactory::class)->findLanguageFromLocale('lib', $locale)
+ Server::get(IFactory::class)->findLanguageFromLocale('lib', $locale)
);
}
- /**
- * @return array
- */
- public function findLanguageFromLocaleData(): array {
+ public static function findLanguageFromLocaleData(): array {
return [
'en_US' => ['en_US', 'en'],
'en_UK' => ['en_UK', 'en'],
diff --git a/tests/lib/L10N/LanguageIteratorTest.php b/tests/lib/L10N/LanguageIteratorTest.php
index 79998c36354..4d1c666cc42 100644
--- a/tests/lib/L10N/LanguageIteratorTest.php
+++ b/tests/lib/L10N/LanguageIteratorTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2018 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
@@ -28,7 +29,7 @@ class LanguageIteratorTest extends TestCase {
$this->iterator = new LanguageIterator($this->user, $this->config);
}
- public function languageSettingsProvider() {
+ public static function languageSettingsProvider(): array {
return [
// all language settings set
[ 'de_DE', 'es_CU', 'zh_TW', ['de_DE', 'de', 'es_CU', 'es', 'zh_TW', 'zh', 'en']],
@@ -57,9 +58,7 @@ class LanguageIteratorTest extends TestCase {
];
}
- /**
- * @dataProvider languageSettingsProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('languageSettingsProvider')]
public function testIterator($forcedLang, $userLang, $sysLang, $expectedValues): void {
$this->config->expects($this->any())
->method('getSystemValue')
diff --git a/tests/lib/LargeFileHelperGetFileSizeTest.php b/tests/lib/LargeFileHelperGetFileSizeTest.php
index 247886fee6a..fbf22f1eb87 100644
--- a/tests/lib/LargeFileHelperGetFileSizeTest.php
+++ b/tests/lib/LargeFileHelperGetFileSizeTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -8,6 +9,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,10 +27,10 @@ class LargeFileHelperGetFileSizeTest extends TestCase {
protected function setUp(): void {
parent::setUp();
- $this->helper = new \OC\LargeFileHelper();
+ $this->helper = new LargeFileHelper();
}
- public function dataFileNameProvider() {
+ public static function dataFileNameProvider(): array {
$path = dirname(__DIR__) . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR;
return [
@@ -35,16 +39,14 @@ class LargeFileHelperGetFileSizeTest extends TestCase {
];
}
- /**
- * @dataProvider dataFileNameProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataFileNameProvider')]
public function XtestGetFileSizeViaCurl($filename, $fileSize) {
if (!extension_loaded('curl')) {
$this->markTestSkipped(
'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.'
);
@@ -55,14 +57,12 @@ class LargeFileHelperGetFileSizeTest extends TestCase {
);
}
- /**
- * @dataProvider dataFileNameProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataFileNameProvider')]
public function testGetFileSizeViaExec($filename, $fileSize): void {
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.'
);
@@ -73,9 +73,7 @@ class LargeFileHelperGetFileSizeTest extends TestCase {
);
}
- /**
- * @dataProvider dataFileNameProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataFileNameProvider')]
public function testGetFileSizeNative($filename, $fileSize): void {
$this->assertSame(
$fileSize,
diff --git a/tests/lib/LargeFileHelperTest.php b/tests/lib/LargeFileHelperTest.php
index 2cccfa441ab..86d0c1387df 100644
--- a/tests/lib/LargeFileHelperTest.php
+++ b/tests/lib/LargeFileHelperTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -7,12 +8,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 {
@@ -36,7 +39,7 @@ class LargeFileHelperTest extends TestCase {
);
}
-
+
public function testFormatUnsignedIntegerStringException(): void {
$this->expectException(\UnexpectedValueException::class);
diff --git a/tests/lib/LegacyHelperTest.php b/tests/lib/LegacyHelperTest.php
index ea359d4e50c..c18f929e40c 100644
--- a/tests/lib/LegacyHelperTest.php
+++ b/tests/lib/LegacyHelperTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -23,85 +24,6 @@ class LegacyHelperTest extends \Test\TestCase {
\OC::$WEBROOT = $this->originalWebRoot;
}
- /**
- * @dataProvider humanFileSizeProvider
- */
- public function testHumanFileSize($expected, $input): void {
- $result = OC_Helper::humanFileSize($input);
- $this->assertEquals($expected, $result);
- }
-
- public function humanFileSizeProvider() {
- return [
- ['0 B', 0],
- ['1 KB', 1024],
- ['9.5 MB', 10000000],
- ['1.3 GB', 1395864371],
- ['465.7 GB', 500000000000],
- ['454.7 TB', 500000000000000],
- ['444.1 PB', 500000000000000000],
- ];
- }
-
- /**
- * @dataProvider providesComputerFileSize
- */
- public function testComputerFileSize($expected, $input): void {
- $result = OC_Helper::computerFileSize($input);
- $this->assertEquals($expected, $result);
- }
-
- public function providesComputerFileSize() {
- return [
- [0.0, '0 B'],
- [1024.0, '1 KB'],
- [1395864371.0, '1.3 GB'],
- [9961472.0, '9.5 MB'],
- [500041567437.0, '465.7 GB'],
- [false, '12 GB etfrhzui']
- ];
- }
-
- public function testMb_array_change_key_case(): void {
- $arrayStart = [
- 'Foo' => 'bar',
- 'Bar' => 'foo',
- ];
- $arrayResult = [
- 'foo' => 'bar',
- 'bar' => 'foo',
- ];
- $result = OC_Helper::mb_array_change_key_case($arrayStart);
- $expected = $arrayResult;
- $this->assertEquals($result, $expected);
-
- $arrayStart = [
- 'foo' => 'bar',
- 'bar' => 'foo',
- ];
- $arrayResult = [
- 'FOO' => 'bar',
- 'BAR' => 'foo',
- ];
- $result = OC_Helper::mb_array_change_key_case($arrayStart, MB_CASE_UPPER);
- $expected = $arrayResult;
- $this->assertEquals($result, $expected);
- }
-
- public function testRecursiveArraySearch(): void {
- $haystack = [
- 'Foo' => 'own',
- 'Bar' => 'Cloud',
- ];
-
- $result = OC_Helper::recursiveArraySearch($haystack, 'own');
- $expected = 'Foo';
- $this->assertEquals($result, $expected);
-
- $result = OC_Helper::recursiveArraySearch($haystack, 'NotFound');
- $this->assertFalse($result);
- }
-
public function testBuildNotExistingFileNameForView(): void {
$viewMock = $this->createMock(View::class);
$this->assertEquals('/filename', OC_Helper::buildNotExistingFileNameForView('/', 'filename', $viewMock));
@@ -110,101 +32,91 @@ class LegacyHelperTest extends \Test\TestCase {
$viewMock = $this->createMock(View::class);
$viewMock->expects($this->exactly(2))
->method('file_exists')
- ->withConsecutive(
+ ->willReturnMap([
// Conflict on filename.ext
- ['dir/filename.ext'],
- ['dir/filename (2).ext'],
- )
- ->will($this->onConsecutiveCalls(true, false));
+ ['dir/filename.ext', true],
+ ['dir/filename (2).ext', false],
+ ]);
$this->assertEquals('dir/filename (2).ext', OC_Helper::buildNotExistingFileNameForView('dir', 'filename.ext', $viewMock));
$viewMock = $this->createMock(View::class);
$viewMock->expects($this->exactly(3))
->method('file_exists')
- ->withConsecutive(
- ['dir/filename.ext'],
- ['dir/filename (2).ext'],
- ['dir/filename (3).ext'],
- )
- ->will($this->onConsecutiveCalls(true, true, false));
+ ->willReturnMap([
+ // Conflict on filename.ext
+ ['dir/filename.ext', true],
+ ['dir/filename (2).ext', true],
+ ['dir/filename (3).ext', false],
+ ]);
$this->assertEquals('dir/filename (3).ext', OC_Helper::buildNotExistingFileNameForView('dir', 'filename.ext', $viewMock));
$viewMock = $this->createMock(View::class);
$viewMock->expects($this->exactly(2))
->method('file_exists')
- ->withConsecutive(
- ['dir/filename (1).ext'],
- ['dir/filename (2).ext'],
- )
- ->will($this->onConsecutiveCalls(true, false));
+ ->willReturnMap([
+ ['dir/filename (1).ext', true],
+ ['dir/filename (2).ext', false],
+ ]);
$this->assertEquals('dir/filename (2).ext', OC_Helper::buildNotExistingFileNameForView('dir', 'filename (1).ext', $viewMock));
$viewMock = $this->createMock(View::class);
$viewMock->expects($this->exactly(2))
->method('file_exists')
- ->withConsecutive(
- ['dir/filename (2).ext'],
- ['dir/filename (3).ext'],
- )
- ->will($this->onConsecutiveCalls(true, false));
+ ->willReturnMap([
+ ['dir/filename (2).ext', true],
+ ['dir/filename (3).ext', false],
+ ]);
$this->assertEquals('dir/filename (3).ext', OC_Helper::buildNotExistingFileNameForView('dir', 'filename (2).ext', $viewMock));
$viewMock = $this->createMock(View::class);
$viewMock->expects($this->exactly(3))
->method('file_exists')
- ->withConsecutive(
- ['dir/filename (2).ext'],
- ['dir/filename (3).ext'],
- ['dir/filename (4).ext'],
- )
- ->will($this->onConsecutiveCalls(true, true, false));
+ ->willReturnMap([
+ ['dir/filename (2).ext', true],
+ ['dir/filename (3).ext', true],
+ ['dir/filename (4).ext', false],
+ ]);
$this->assertEquals('dir/filename (4).ext', OC_Helper::buildNotExistingFileNameForView('dir', 'filename (2).ext', $viewMock));
$viewMock = $this->createMock(View::class);
$viewMock->expects($this->exactly(2))
->method('file_exists')
- ->withConsecutive(
- ['dir/filename(1).ext'],
- ['dir/filename(2).ext'],
- )
- ->will($this->onConsecutiveCalls(true, false));
+ ->willReturnMap([
+ ['dir/filename(1).ext', true],
+ ['dir/filename(2).ext', false],
+ ]);
$this->assertEquals('dir/filename(2).ext', OC_Helper::buildNotExistingFileNameForView('dir', 'filename(1).ext', $viewMock));
$viewMock = $this->createMock(View::class);
$viewMock->expects($this->exactly(2))
->method('file_exists')
- ->withConsecutive(
- ['dir/filename(1) (1).ext'],
- ['dir/filename(1) (2).ext'],
- )
- ->will($this->onConsecutiveCalls(true, false));
+ ->willReturnMap([
+ ['dir/filename(1) (1).ext', true],
+ ['dir/filename(1) (2).ext', false],
+ ]);
$this->assertEquals('dir/filename(1) (2).ext', OC_Helper::buildNotExistingFileNameForView('dir', 'filename(1) (1).ext', $viewMock));
$viewMock = $this->createMock(View::class);
$viewMock->expects($this->exactly(3))
->method('file_exists')
- ->withConsecutive(
- ['dir/filename(1) (1).ext'],
- ['dir/filename(1) (2).ext'],
- ['dir/filename(1) (3).ext'],
- )
- ->will($this->onConsecutiveCalls(true, true, false));
+ ->willReturnMap([
+ ['dir/filename(1) (1).ext', true],
+ ['dir/filename(1) (2).ext', true],
+ ['dir/filename(1) (3).ext', false],
+ ]);
$this->assertEquals('dir/filename(1) (3).ext', OC_Helper::buildNotExistingFileNameForView('dir', 'filename(1) (1).ext', $viewMock));
$viewMock = $this->createMock(View::class);
$viewMock->expects($this->exactly(2))
->method('file_exists')
- ->withConsecutive(
- ['dir/filename(1) (2) (3).ext'],
- ['dir/filename(1) (2) (4).ext'],
- )
- ->will($this->onConsecutiveCalls(true, false));
+ ->willReturnMap([
+ ['dir/filename(1) (2) (3).ext', true],
+ ['dir/filename(1) (2) (4).ext', false],
+ ]);
$this->assertEquals('dir/filename(1) (2) (4).ext', OC_Helper::buildNotExistingFileNameForView('dir', 'filename(1) (2) (3).ext', $viewMock));
}
- /**
- * @dataProvider streamCopyDataProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('streamCopyDataProvider')]
public function testStreamCopy($expectedCount, $expectedResult, $source, $target): void {
if (is_string($source)) {
$source = fopen($source, 'r');
@@ -227,7 +139,7 @@ class LegacyHelperTest extends \Test\TestCase {
}
- public function streamCopyDataProvider() {
+ public static function streamCopyDataProvider(): array {
return [
[0, false, false, false],
[0, false, \OC::$SERVERROOT . '/tests/data/lorem.txt', false],
@@ -235,42 +147,4 @@ class LegacyHelperTest extends \Test\TestCase {
[3670, true, \OC::$SERVERROOT . '/tests/data/testimage.png', \OC::$SERVERROOT . '/tests/data/testimage-copy.png'],
];
}
-
- /**
- * Tests recursive folder deletion with rmdirr()
- */
- public function testRecursiveFolderDeletion(): void {
- $baseDir = \OC::$server->getTempManager()->getTemporaryFolder() . '/';
- mkdir($baseDir . 'a/b/c/d/e', 0777, true);
- mkdir($baseDir . 'a/b/c1/d/e', 0777, true);
- mkdir($baseDir . 'a/b/c2/d/e', 0777, true);
- mkdir($baseDir . 'a/b1/c1/d/e', 0777, true);
- mkdir($baseDir . 'a/b2/c1/d/e', 0777, true);
- mkdir($baseDir . 'a/b3/c1/d/e', 0777, true);
- mkdir($baseDir . 'a1/b', 0777, true);
- mkdir($baseDir . 'a1/c', 0777, true);
- file_put_contents($baseDir . 'a/test.txt', 'Hello file!');
- file_put_contents($baseDir . 'a/b1/c1/test one.txt', 'Hello file one!');
- file_put_contents($baseDir . 'a1/b/test two.txt', 'Hello file two!');
- \OC_Helper::rmdirr($baseDir . 'a');
-
- $this->assertFalse(file_exists($baseDir . 'a'));
- $this->assertTrue(file_exists($baseDir . 'a1'));
-
- \OC_Helper::rmdirr($baseDir);
- $this->assertFalse(file_exists($baseDir));
- }
-
- /**
- * Allows us to test private methods/properties
- *
- * @param $object
- * @param $methodName
- * @param array $parameters
- * @return mixed
- * @deprecated Please extend \Test\TestCase and use self::invokePrivate() then
- */
- public static function invokePrivate($object, $methodName, array $parameters = []) {
- return parent::invokePrivate($object, $methodName, $parameters);
- }
}
diff --git a/tests/lib/Lock/DBLockingProviderTest.php b/tests/lib/Lock/DBLockingProviderTest.php
index 1c02e8d7d77..32a223b4913 100644
--- a/tests/lib/Lock/DBLockingProviderTest.php
+++ b/tests/lib/Lock/DBLockingProviderTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -7,8 +8,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
@@ -24,12 +28,12 @@ class DBLockingProviderTest extends LockingProvider {
protected $instance;
/**
- * @var \OCP\IDBConnection
+ * @var IDBConnection
*/
protected $connection;
/**
- * @var \OCP\AppFramework\Utility\ITimeFactory
+ * @var ITimeFactory
*/
protected $timeFactory;
@@ -47,11 +51,11 @@ class DBLockingProviderTest extends LockingProvider {
}
/**
- * @return \OCP\Lock\ILockingProvider
+ * @return 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..2827f2c9160 100644
--- a/tests/lib/Lock/LockingProvider.php
+++ b/tests/lib/Lock/LockingProvider.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2018-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -13,12 +14,12 @@ use Test\TestCase;
abstract class LockingProvider extends TestCase {
/**
- * @var \OCP\Lock\ILockingProvider
+ * @var ILockingProvider
*/
protected $instance;
/**
- * @return \OCP\Lock\ILockingProvider
+ * @return ILockingProvider
*/
abstract protected function getInstance();
@@ -59,9 +60,9 @@ abstract class LockingProvider extends TestCase {
$this->assertFalse($this->instance->isLocked('foo', ILockingProvider::LOCK_SHARED));
}
-
+
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));
@@ -76,9 +77,9 @@ abstract class LockingProvider extends TestCase {
$this->instance->acquireLock('foo', ILockingProvider::LOCK_EXCLUSIVE);
}
-
+
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));
@@ -150,9 +151,9 @@ 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));
@@ -197,40 +198,40 @@ abstract class LockingProvider extends TestCase {
$this->assertTrue($this->instance->isLocked('foo', ILockingProvider::LOCK_SHARED));
}
-
+
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);
$this->instance->changeLock('foo', ILockingProvider::LOCK_EXCLUSIVE);
}
-
+
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);
}
-
+
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..ea7b3c26b3c 100644
--- a/tests/lib/Lock/MemcacheLockingProviderTest.php
+++ b/tests/lib/Lock/MemcacheLockingProviderTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -7,22 +8,26 @@
namespace Test\Lock;
+use OC\Lock\MemcacheLockingProvider;
use OC\Memcache\ArrayCache;
use OCP\AppFramework\Utility\ITimeFactory;
+use OCP\IMemcache;
+use OCP\Lock\ILockingProvider;
+use OCP\Server;
class MemcacheLockingProviderTest extends LockingProvider {
/**
- * @var \OCP\IMemcache
+ * @var IMemcache
*/
private $memcache;
/**
- * @return \OCP\Lock\ILockingProvider
+ * @return ILockingProvider
*/
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..4f05f0ba892 100644
--- a/tests/lib/Lock/NonCachingDBLockingProviderTest.php
+++ b/tests/lib/Lock/NonCachingDBLockingProviderTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2018 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
@@ -6,7 +7,10 @@
namespace Test\Lock;
+use OC\Lock\DBLockingProvider;
+use OCP\IDBConnection;
use OCP\Lock\ILockingProvider;
+use OCP\Server;
/**
* @group DB
@@ -15,11 +19,11 @@ use OCP\Lock\ILockingProvider;
*/
class NonCachingDBLockingProviderTest extends DBLockingProviderTest {
/**
- * @return \OCP\Lock\ILockingProvider
+ * @return 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..b471f573fb7 100644
--- a/tests/lib/Lockdown/Filesystem/NoFSTest.php
+++ b/tests/lib/Lockdown/Filesystem/NoFSTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
@@ -10,6 +11,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 +25,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 +36,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/Lockdown/Filesystem/NullCacheTest.php b/tests/lib/Lockdown/Filesystem/NullCacheTest.php
index 5e120e9bdc7..505951ea2ef 100644
--- a/tests/lib/Lockdown/Filesystem/NullCacheTest.php
+++ b/tests/lib/Lockdown/Filesystem/NullCacheTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
@@ -27,7 +28,7 @@ class NulLCacheTest extends \Test\TestCase {
}
public function testGetEmpty(): void {
- $this->assertNull($this->cache->get('foo'));
+ $this->assertFalse($this->cache->get('foo'));
}
public function testGet(): void {
diff --git a/tests/lib/Lockdown/Filesystem/NullStorageTest.php b/tests/lib/Lockdown/Filesystem/NullStorageTest.php
index 21cb0f75bb6..fa019ada4e5 100644
--- a/tests/lib/Lockdown/Filesystem/NullStorageTest.php
+++ b/tests/lib/Lockdown/Filesystem/NullStorageTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
diff --git a/tests/lib/Lockdown/LockdownManagerTest.php b/tests/lib/Lockdown/LockdownManagerTest.php
index 1f747378c02..973dec6d1f2 100644
--- a/tests/lib/Lockdown/LockdownManagerTest.php
+++ b/tests/lib/Lockdown/LockdownManagerTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
diff --git a/tests/lib/Log/FileTest.php b/tests/lib/Log/FileTest.php
index b483da969f4..3f030665fb4 100644
--- a/tests/lib/Log/FileTest.php
+++ b/tests/lib/Log/FileTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
*
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
@@ -8,8 +9,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 +27,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 +35,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 +51,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 +72,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/Log/LogFactoryTest.php b/tests/lib/Log/LogFactoryTest.php
index 1d87c856061..b1adbd0e823 100644
--- a/tests/lib/Log/LogFactoryTest.php
+++ b/tests/lib/Log/LogFactoryTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2018 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
@@ -12,6 +13,7 @@ use OC\Log\LogFactory;
use OC\Log\Syslog;
use OC\Log\Systemdlog;
use OC\SystemConfig;
+use OCP\AppFramework\QueryException;
use OCP\IServerContainer;
use Test\TestCase;
@@ -58,9 +60,9 @@ class LogFactoryTest extends TestCase {
/**
* @param string $type
- * @dataProvider fileTypeProvider
- * @throws \OCP\AppFramework\QueryException
+ * @throws QueryException
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('fileTypeProvider')]
public function testFile(string $type): void {
$datadir = \OC::$SERVERROOT . '/data';
$defaultLog = $datadir . '/nextcloud.log';
@@ -91,9 +93,9 @@ class LogFactoryTest extends TestCase {
}
/**
- * @dataProvider logFilePathProvider
- * @throws \OCP\AppFramework\QueryException
+ * @throws QueryException
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('logFilePathProvider')]
public function testFileCustomPath($path, $expected): void {
$datadir = \OC::$SERVERROOT . '/data';
$defaultLog = $datadir . '/nextcloud.log';
@@ -112,7 +114,7 @@ class LogFactoryTest extends TestCase {
}
/**
- * @throws \OCP\AppFramework\QueryException
+ * @throws QueryException
*/
public function testErrorLog(): void {
$log = $this->factory->get('errorlog');
@@ -120,7 +122,7 @@ class LogFactoryTest extends TestCase {
}
/**
- * @throws \OCP\AppFramework\QueryException
+ * @throws QueryException
*/
public function testSystemLog(): void {
$this->c->expects($this->once())
@@ -133,7 +135,7 @@ class LogFactoryTest extends TestCase {
}
/**
- * @throws \OCP\AppFramework\QueryException
+ * @throws QueryException
*/
public function testSystemdLog(): void {
$this->c->expects($this->once())
diff --git a/tests/lib/Log/PsrLoggerAdapterTest.php b/tests/lib/Log/PsrLoggerAdapterTest.php
index cc9ddea378a..c11af7a12c2 100644
--- a/tests/lib/Log/PsrLoggerAdapterTest.php
+++ b/tests/lib/Log/PsrLoggerAdapterTest.php
@@ -28,9 +28,7 @@ class PsrLoggerAdapterTest extends TestCase {
$this->loggerAdapter = new PsrLoggerAdapter($this->logger);
}
- /**
- * @dataProvider dataPsrLoggingLevels
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataPsrLoggingLevels')]
public function testLoggingWithPsrLogLevels(string $level, int $expectedLevel): void {
$this->logger->expects(self::once())
->method('log')
@@ -38,14 +36,12 @@ class PsrLoggerAdapterTest extends TestCase {
$this->loggerAdapter->log($level, 'test message', ['app' => 'test']);
}
- /**
- * @dataProvider dataPsrLoggingLevels
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataPsrLoggingLevels')]
public function testLogLevelToInt(string $level, int $expectedLevel): void {
$this->assertEquals($expectedLevel, PsrLoggerAdapter::logLevelToInt($level));
}
- public function dataPsrLoggingLevels(): array {
+ public static function dataPsrLoggingLevels(): array {
return [
[LogLevel::ALERT, ILogger::ERROR],
[LogLevel::CRITICAL, ILogger::ERROR],
@@ -58,9 +54,7 @@ class PsrLoggerAdapterTest extends TestCase {
];
}
- /**
- * @dataProvider dataInvalidLoggingLevel
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataInvalidLoggingLevel')]
public function testInvalidLoggingLevel($level): void {
$this->logger->expects(self::never())
->method('log');
@@ -69,7 +63,7 @@ class PsrLoggerAdapterTest extends TestCase {
$this->loggerAdapter->log($level, 'valid message');
}
- public function dataInvalidLoggingLevel(): array {
+ public static function dataInvalidLoggingLevel(): array {
return [
// invalid string
['this is not a level'],
diff --git a/tests/lib/LoggerTest.php b/tests/lib/LoggerTest.php
index c7c60e892aa..7ad6638537f 100644
--- a/tests/lib/LoggerTest.php
+++ b/tests/lib/LoggerTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -38,9 +39,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 +56,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');
@@ -72,7 +73,7 @@ class LoggerTest extends TestCase implements IWriter {
$this->assertEquals($expected, $this->getLogs());
}
- public function dataMatchesCondition(): array {
+ public static function dataMatchesCondition(): array {
return [
[
'user0',
@@ -130,9 +131,7 @@ class LoggerTest extends TestCase implements IWriter {
];
}
- /**
- * @dataProvider dataMatchesCondition
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataMatchesCondition')]
public function testMatchesCondition(string $userId, array $conditions, array $expectedLogs): void {
$this->config->expects($this->any())
->method('getValue')
@@ -181,7 +180,7 @@ class LoggerTest extends TestCase implements IWriter {
$this->logs[] = $level . ' ' . $textMessage;
}
- public function userAndPasswordData(): array {
+ public static function userAndPasswordData(): array {
return [
['mySpecialUsername', 'MySuperSecretPassword'],
['my-user', '324324()#ä234'],
@@ -194,9 +193,7 @@ class LoggerTest extends TestCase implements IWriter {
];
}
- /**
- * @dataProvider userAndPasswordData
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('userAndPasswordData')]
public function testDetectlogin(string $user, string $password): void {
$this->mockDefaultLogLevel();
$e = new \Exception('test');
@@ -217,9 +214,7 @@ class LoggerTest extends TestCase implements IWriter {
}
}
- /**
- * @dataProvider userAndPasswordData
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('userAndPasswordData')]
public function testDetectcheckPassword(string $user, string $password): void {
$this->mockDefaultLogLevel();
$e = new \Exception('test');
@@ -240,9 +235,7 @@ class LoggerTest extends TestCase implements IWriter {
}
}
- /**
- * @dataProvider userAndPasswordData
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('userAndPasswordData')]
public function testDetectvalidateUserPass(string $user, string $password): void {
$this->mockDefaultLogLevel();
$e = new \Exception('test');
@@ -263,9 +256,7 @@ class LoggerTest extends TestCase implements IWriter {
}
}
- /**
- * @dataProvider userAndPasswordData
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('userAndPasswordData')]
public function testDetecttryLogin(string $user, string $password): void {
$this->mockDefaultLogLevel();
$e = new \Exception('test');
@@ -286,12 +277,10 @@ class LoggerTest extends TestCase implements IWriter {
}
}
- /**
- * @dataProvider userAndPasswordData
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('userAndPasswordData')]
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/EMailTemplateTest.php b/tests/lib/Mail/EMailTemplateTest.php
index 4943024043c..1912bf060e2 100644
--- a/tests/lib/Mail/EMailTemplateTest.php
+++ b/tests/lib/Mail/EMailTemplateTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2017 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
diff --git a/tests/lib/Mail/MailerTest.php b/tests/lib/Mail/MailerTest.php
index 02a2605fc77..7b911e5c4e2 100644
--- a/tests/lib/Mail/MailerTest.php
+++ b/tests/lib/Mail/MailerTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2017-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -18,6 +19,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;
@@ -66,7 +68,7 @@ class MailerTest extends TestCase {
/**
* @return array
*/
- public function sendmailModeProvider(): array {
+ public static function sendmailModeProvider(): array {
return [
'smtp' => ['smtp', ' -bs'],
'pipe' => ['pipe', ' -t -i'],
@@ -74,10 +76,10 @@ class MailerTest extends TestCase {
}
/**
- * @dataProvider sendmailModeProvider
* @param $sendmailMode
* @param $binaryParam
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('sendmailModeProvider')]
public function testGetSendmailInstanceSendMail($sendmailMode, $binaryParam): void {
$this->config
->expects($this->exactly(2))
@@ -87,7 +89,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';
}
@@ -97,10 +99,10 @@ class MailerTest extends TestCase {
}
/**
- * @dataProvider sendmailModeProvider
* @param $sendmailMode
* @param $binaryParam
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('sendmailModeProvider')]
public function testGetSendmailInstanceSendMailQmail($sendmailMode, $binaryParam): void {
$this->config
->expects($this->exactly(2))
@@ -170,7 +172,7 @@ class MailerTest extends TestCase {
['mail_smtpport', 25, 25],
]);
$this->mailer = $this->getMockBuilder(Mailer::class)
- ->setMethods(['getInstance'])
+ ->onlyMethods(['getInstance'])
->setConstructorArgs(
[
$this->config,
@@ -227,7 +229,7 @@ class MailerTest extends TestCase {
/**
* @return array
*/
- public function mailAddressProvider() {
+ public static function mailAddressProvider(): array {
return [
['lukas@owncloud.com', true, false],
['lukas@localhost', true, false],
@@ -241,9 +243,7 @@ class MailerTest extends TestCase {
];
}
- /**
- * @dataProvider mailAddressProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('mailAddressProvider')]
public function testValidateMailAddress($email, $expected, $strict): void {
$this->config
->expects($this->atMost(1))
diff --git a/tests/lib/Mail/MessageTest.php b/tests/lib/Mail/MessageTest.php
index 260d3aaff76..18ef9793b5b 100644
--- a/tests/lib/Mail/MessageTest.php
+++ b/tests/lib/Mail/MessageTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2018-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -27,7 +28,7 @@ class MessageTest extends TestCase {
/**
* @return array
*/
- public function mailAddressProvider() {
+ public static function mailAddressProvider(): array {
return [
[
['lukas@owncloud.com' => 'Lukas Reschke'],
@@ -65,18 +66,17 @@ class MessageTest extends TestCase {
protected function setUp(): void {
parent::setUp();
- $this->symfonyEmail = $this->getMockBuilder(Email::class)
- ->disableOriginalConstructor()->getMock();
+ $this->symfonyEmail = $this->createMock(Email::class);
$this->message = new Message($this->symfonyEmail, false);
}
/**
- * @dataProvider mailAddressProvider
*
* @param string $unconverted
* @param string $expected
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('mailAddressProvider')]
public function testConvertAddresses($unconverted, $expected): void {
$this->assertEquals($expected, self::invokePrivate($this->message, 'convertAddresses', [$unconverted]));
}
diff --git a/tests/lib/Mail/Provider/AddressTest.php b/tests/lib/Mail/Provider/AddressTest.php
index ee03f6f1e83..dc5e73526eb 100644
--- a/tests/lib/Mail/Provider/AddressTest.php
+++ b/tests/lib/Mail/Provider/AddressTest.php
@@ -24,7 +24,7 @@ class AddressTest extends TestCase {
}
public function testAddress(): void {
-
+
// test set by constructor
$this->assertEquals('user1@testing.com', $this->address->getAddress());
// test set by setter
@@ -34,7 +34,7 @@ class AddressTest extends TestCase {
}
public function testLabel(): void {
-
+
// test set by constructor
$this->assertEquals('User One', $this->address->getLabel());
// test set by setter
diff --git a/tests/lib/Mail/Provider/AttachmentTest.php b/tests/lib/Mail/Provider/AttachmentTest.php
index 283391650b5..f02b1d54a7b 100644
--- a/tests/lib/Mail/Provider/AttachmentTest.php
+++ b/tests/lib/Mail/Provider/AttachmentTest.php
@@ -29,7 +29,7 @@ class AttachmentTest extends TestCase {
}
public function testName(): void {
-
+
// test set by constructor
$this->assertEquals('example1.txt', $this->attachment->getName());
// test set by setter
@@ -39,7 +39,7 @@ class AttachmentTest extends TestCase {
}
public function testType(): void {
-
+
// test set by constructor
$this->assertEquals('text/plain', $this->attachment->getType());
// test set by setter
@@ -49,7 +49,7 @@ class AttachmentTest extends TestCase {
}
public function testContents(): void {
-
+
// test set by constructor
$this->assertEquals('This is the contents of a file', $this->attachment->getContents());
// test set by setter
@@ -59,7 +59,7 @@ class AttachmentTest extends TestCase {
}
public function testEmbedded(): void {
-
+
// test set by constructor
$this->assertEquals(false, $this->attachment->getEmbedded());
// test set by setter
diff --git a/tests/lib/Mail/Provider/MessageTest.php b/tests/lib/Mail/Provider/MessageTest.php
index 1791a03421c..6b387e5b010 100644
--- a/tests/lib/Mail/Provider/MessageTest.php
+++ b/tests/lib/Mail/Provider/MessageTest.php
@@ -56,14 +56,14 @@ class MessageTest extends TestCase {
}
public function testId(): void {
-
+
// test set by constructor
$this->assertEquals('cd02ea42-feac-4863-b9d8-484d16a587ea', $this->message->id());
}
public function testFrom(): void {
-
+
// test not set
$this->assertNull($this->message->getFrom());
// test set by setter
@@ -73,7 +73,7 @@ class MessageTest extends TestCase {
}
public function testReplyTo(): void {
-
+
// test not set
$this->assertNull($this->message->getReplyTo());
// test set by setter
@@ -83,7 +83,7 @@ class MessageTest extends TestCase {
}
public function testTo(): void {
-
+
// test not set
$this->assertEquals([], $this->message->getTo());
// test set by setter single
@@ -96,7 +96,7 @@ class MessageTest extends TestCase {
}
public function testCc(): void {
-
+
// test not set
$this->assertEquals([], $this->message->getCc());
// test set by setter single
@@ -109,7 +109,7 @@ class MessageTest extends TestCase {
}
public function testBcc(): void {
-
+
// test not set
$this->assertEquals([], $this->message->getBcc());
// test set by setter single
@@ -122,7 +122,7 @@ class MessageTest extends TestCase {
}
public function testSubject(): void {
-
+
// test not set
$this->assertNull($this->message->getSubject());
// test set by setter
@@ -132,7 +132,7 @@ class MessageTest extends TestCase {
}
public function testBody(): void {
-
+
// test not set
$this->assertNull($this->message->getBody());
// test set by setter - text body
@@ -149,7 +149,7 @@ class MessageTest extends TestCase {
}
public function testAttachments(): void {
-
+
// test not set
$this->assertEquals([], $this->message->getAttachments());
// test set by setter single
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/Cache.php b/tests/lib/Memcache/Cache.php
index 5845d426311..b48f5557faa 100644
--- a/tests/lib/Memcache/Cache.php
+++ b/tests/lib/Memcache/Cache.php
@@ -8,9 +8,11 @@
namespace Test\Memcache;
+use OCP\IMemcache;
+
abstract class Cache extends \Test\Cache\TestCache {
/**
- * @var \OCP\IMemcache cache;
+ * @var IMemcache cache;
*/
protected $instance;
diff --git a/tests/lib/Memcache/CasTraitTest.php b/tests/lib/Memcache/CasTraitTest.php
index 129819045f2..9de04fa2726 100644
--- a/tests/lib/Memcache/CasTraitTest.php
+++ b/tests/lib/Memcache/CasTraitTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -7,6 +8,7 @@
namespace Test\Memcache;
+use OC\Memcache\ArrayCache;
use Test\TestCase;
/**
@@ -17,7 +19,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 fa0d80c5153..e16e079349f 100644
--- a/tests/lib/Memcache/FactoryTest.php
+++ b/tests/lib/Memcache/FactoryTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -7,7 +8,9 @@
namespace Test\Memcache;
+use OC\Memcache\Factory;
use OC\Memcache\NullCache;
+use OCP\HintException;
use OCP\Profiler\IProfiler;
use Psr\Log\LoggerInterface;
@@ -56,37 +59,37 @@ class FactoryTest extends \Test\TestCase {
public const UNAVAILABLE1 = '\\Test\\Memcache\\Test_Factory_Unavailable_Cache1';
public const UNAVAILABLE2 = '\\Test\\Memcache\\Test_Factory_Unavailable_Cache2';
- public function cacheAvailabilityProvider() {
+ public static function cacheAvailabilityProvider(): array {
return [
[
// 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
]
];
}
- public function cacheUnavailableProvider() {
+ public static function cacheUnavailableProvider(): array {
return [
[
// local available, distributed unavailable
@@ -103,34 +106,30 @@ class FactoryTest extends \Test\TestCase {
];
}
- /**
- * @dataProvider cacheAvailabilityProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('cacheAvailabilityProvider')]
public function testCacheAvailability($localCache, $distributedCache, $lockingCache,
$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));
}
- /**
- * @dataProvider cacheUnavailableProvider
- */
+ #[\PHPUnit\Framework\Attributes\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/MemoryInfoTest.php b/tests/lib/MemoryInfoTest.php
index 2477de2d799..13e46c96601 100644
--- a/tests/lib/MemoryInfoTest.php
+++ b/tests/lib/MemoryInfoTest.php
@@ -37,12 +37,7 @@ class MemoryInfoTest extends TestCase {
ini_set('memory_limit', $this->iniSettingBeforeTest);
}
- /**
- * Provides test data.
- *
- * @return array
- */
- public function getMemoryLimitTestData(): array {
+ public static function getMemoryLimitTestData(): array {
return [
'unlimited' => ['-1', -1,],
'524288000 bytes' => ['524288000', 524288000,],
@@ -57,20 +52,15 @@ class MemoryInfoTest extends TestCase {
*
* @param string $iniValue The "memory_limit" ini data.
* @param int|float $expected The expected detected memory limit.
- * @dataProvider getMemoryLimitTestData
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('getMemoryLimitTestData')]
public function testMemoryLimit(string $iniValue, int|float $expected): void {
ini_set('memory_limit', $iniValue);
$memoryInfo = new MemoryInfo();
self::assertEquals($expected, $memoryInfo->getMemoryLimit());
}
- /**
- * Provides sufficient memory limit test data.
- *
- * @return array
- */
- public function getSufficientMemoryTestData(): array {
+ public static function getSufficientMemoryTestData(): array {
return [
'unlimited' => [-1, true,],
'512M' => [512 * 1024 * 1024, true,],
@@ -84,13 +74,12 @@ class MemoryInfoTest extends TestCase {
*
* @param int $memoryLimit The memory limit
* @param bool $expected If the memory limit is sufficient.
- * @dataProvider getSufficientMemoryTestData
- * @return void
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('getSufficientMemoryTestData')]
public function testIsMemoryLimitSufficient(int $memoryLimit, bool $expected): void {
/* @var MemoryInfo|MockObject $memoryInfo */
$memoryInfo = $this->getMockBuilder(MemoryInfo::class)
- ->setMethods(['getMemoryLimit',])
+ ->onlyMethods(['getMemoryLimit',])
->getMock();
$memoryInfo
diff --git a/tests/lib/Migration/BackgroundRepairTest.php b/tests/lib/Migration/BackgroundRepairTest.php
index 25ea6088072..5bc085eb7ec 100644
--- a/tests/lib/Migration/BackgroundRepairTest.php
+++ b/tests/lib/Migration/BackgroundRepairTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -54,22 +55,15 @@ class BackgroundRepairTest extends TestCase {
protected function setUp(): void {
parent::setUp();
- $this->jobList = $this->getMockBuilder(JobList::class)
- ->disableOriginalConstructor()
- ->getMock();
- $this->logger = $this->getMockBuilder(LoggerInterface::class)
- ->disableOriginalConstructor()
- ->getMock();
+ $this->jobList = $this->createMock(JobList::class);
+ $this->logger = $this->createMock(LoggerInterface::class);
$this->dispatcher = $this->createMock(IEventDispatcher::class);
$this->time = $this->createMock(ITimeFactory::class);
$this->time->method('getTime')
->willReturn(999999);
$this->appManager = $this->createMock(IAppManager::class);
$this->repair = new Repair($this->dispatcher, $this->logger);
- $this->job = $this->getMockBuilder(BackgroundRepair::class)
- ->setConstructorArgs([$this->repair, $this->time, $this->logger, $this->jobList, $this->appManager])
- ->setMethods(['loadApp'])
- ->getMock();
+ $this->job = new BackgroundRepair($this->repair, $this->time, $this->logger, $this->jobList, $this->appManager);
}
public function testNoArguments(): void {
diff --git a/tests/lib/NaturalSortTest.php b/tests/lib/NaturalSortTest.php
index 3a07c5ceb66..48d09f03087 100644
--- a/tests/lib/NaturalSortTest.php
+++ b/tests/lib/NaturalSortTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -7,25 +8,24 @@
namespace Test;
+use OC\NaturalSort;
+use OC\NaturalSort_DefaultCollator;
+
class NaturalSortTest extends \Test\TestCase {
- /**
- * @dataProvider naturalSortDataProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('naturalSortDataProvider')]
public function testNaturalSortCompare($array, $sorted): void {
if (!class_exists('Collator')) {
$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);
}
- /**
- * @dataProvider defaultCollatorDataProvider
- */
+ #[\PHPUnit\Framework\Attributes\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);
}
@@ -35,7 +35,7 @@ class NaturalSortTest extends \Test\TestCase {
* Must provide the same result as in core/js/tests/specs/coreSpec.js
* @return array test cases
*/
- public function naturalSortDataProvider() {
+ public static function naturalSortDataProvider(): array {
return [
// different casing
[
@@ -189,7 +189,7 @@ class NaturalSortTest extends \Test\TestCase {
* Must provide the same result as in core/js/tests/specs/coreSpec.js
* @return array test cases
*/
- public function defaultCollatorDataProvider() {
+ public static function defaultCollatorDataProvider(): array {
return [
// different casing
[
diff --git a/tests/lib/NavigationManagerTest.php b/tests/lib/NavigationManagerTest.php
index 48cfa972f2b..53d7e81302b 100644
--- a/tests/lib/NavigationManagerTest.php
+++ b/tests/lib/NavigationManagerTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -20,6 +21,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;
@@ -39,7 +41,7 @@ class NavigationManagerTest extends TestCase {
protected IEVentDispatcher|MockObject $dispatcher;
- /** @var \OC\NavigationManager */
+ /** @var NavigationManager */
protected $navigationManager;
protected LoggerInterface $logger;
@@ -68,10 +70,10 @@ class NavigationManagerTest extends TestCase {
$this->navigationManager->clear(false);
}
- public function addArrayData() {
+ public static function addArrayData(): array {
return [
[
- 'entry id' => [
+ 'entry' => [
'id' => 'entry id',
'name' => 'link text',
'order' => 1,
@@ -81,7 +83,7 @@ class NavigationManagerTest extends TestCase {
'classes' => '',
'unread' => 0
],
- 'entry id2' => [
+ 'expectedEntry' => [
'id' => 'entry id',
'name' => 'link text',
'order' => 1,
@@ -94,7 +96,7 @@ class NavigationManagerTest extends TestCase {
]
],
[
- 'entry id' => [
+ 'entry' => [
'id' => 'entry id',
'name' => 'link text',
'order' => 1,
@@ -103,7 +105,7 @@ class NavigationManagerTest extends TestCase {
'active' => true,
'unread' => 0,
],
- 'entry id2' => [
+ 'expectedEntry' => [
'id' => 'entry id',
'name' => 'link text',
'order' => 1,
@@ -120,11 +122,11 @@ class NavigationManagerTest extends TestCase {
}
/**
- * @dataProvider addArrayData
*
* @param array $entry
* @param array $expectedEntry
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('addArrayData')]
public function testAddArray(array $entry, array $expectedEntry): void {
$this->assertEmpty($this->navigationManager->getAll('all'), 'Expected no navigation entry exists');
$this->navigationManager->add($entry);
@@ -138,11 +140,11 @@ class NavigationManagerTest extends TestCase {
}
/**
- * @dataProvider addArrayData
*
* @param array $entry
* @param array $expectedEntry
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('addArrayData')]
public function testAddClosure(array $entry, array $expectedEntry): void {
global $testAddClosureNumberOfCalls;
$testAddClosureNumberOfCalls = 0;
@@ -213,9 +215,7 @@ class NavigationManagerTest extends TestCase {
$this->assertEquals(0, $testAddClosureNumberOfCalls, 'Expected that the closure is not called by getAll()');
}
- /**
- * @dataProvider providesNavigationConfig
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('providesNavigationConfig')]
public function testWithAppManager($expected, $navigation, $isAdmin = false): void {
$l = $this->createMock(IL10N::class);
$l->expects($this->any())->method('t')->willReturnCallback(function ($text, $parameters = []) {
@@ -265,14 +265,14 @@ 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');
$this->assertEquals($expected, $entries);
}
- public function providesNavigationConfig() {
+ public static function providesNavigationConfig(): array {
$apps = [
'core_apps' => [
'id' => 'core_apps',
@@ -323,7 +323,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 +572,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();
@@ -729,9 +729,7 @@ class NavigationManagerTest extends TestCase {
];
}
- /**
- * @dataProvider provideDefaultEntries
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('provideDefaultEntries')]
public function testGetDefaultEntryIdForUser(string $defaultApps, string $userDefaultApps, string $userApporder, bool $withFallbacks, string $expectedApp): void {
$this->navigationManager->add([
'id' => 'files',
diff --git a/tests/lib/Net/HostnameClassifierTest.php b/tests/lib/Net/HostnameClassifierTest.php
index 766246ed8ad..c03afdabe83 100644
--- a/tests/lib/Net/HostnameClassifierTest.php
+++ b/tests/lib/Net/HostnameClassifierTest.php
@@ -21,7 +21,7 @@ class HostnameClassifierTest extends TestCase {
$this->classifier = new HostnameClassifier();
}
- public function localHostnamesData():array {
+ public static function localHostnamesData(): array {
return [
['localhost'],
['localHost'],
@@ -32,16 +32,14 @@ class HostnameClassifierTest extends TestCase {
];
}
- /**
- * @dataProvider localHostnamesData
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('localHostnamesData')]
public function testLocalHostname(string $host): void {
$isLocal = $this->classifier->isLocalHostname($host);
self::assertTrue($isLocal);
}
- public function publicHostnamesData(): array {
+ public static function publicHostnamesData(): array {
return [
['example.com'],
['example.net'],
@@ -51,9 +49,7 @@ class HostnameClassifierTest extends TestCase {
];
}
- /**
- * @dataProvider publicHostnamesData
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('publicHostnamesData')]
public function testPublicHostname(string $host): void {
$isLocal = $this->classifier->isLocalHostname($host);
diff --git a/tests/lib/Net/IpAddressClassifierTest.php b/tests/lib/Net/IpAddressClassifierTest.php
index 803be00f740..f20e1ec1785 100644
--- a/tests/lib/Net/IpAddressClassifierTest.php
+++ b/tests/lib/Net/IpAddressClassifierTest.php
@@ -21,7 +21,7 @@ class IpAddressClassifierTest extends TestCase {
$this->classifier = new IpAddressClassifier();
}
- public function publicIpAddressData(): array {
+ public static function publicIpAddressData(): array {
return [
['8.8.8.8'],
['8.8.4.4'],
@@ -30,16 +30,14 @@ class IpAddressClassifierTest extends TestCase {
];
}
- /**
- * @dataProvider publicIpAddressData
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('publicIpAddressData')]
public function testPublicAddress(string $ip): void {
$isLocal = $this->classifier->isLocalAddress($ip);
self::assertFalse($isLocal);
}
- public function localIpAddressData(): array {
+ public static function localIpAddressData(): array {
return [
['192.168.0.1'],
['fe80::200:5aee:feaa:20a2'],
@@ -54,9 +52,7 @@ class IpAddressClassifierTest extends TestCase {
];
}
- /**
- * @dataProvider localIpAddressData
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('localIpAddressData')]
public function testLocalAddress(string $ip): void {
$isLocal = $this->classifier->isLocalAddress($ip);
diff --git a/tests/lib/Notification/ActionTest.php b/tests/lib/Notification/ActionTest.php
index 3ae4b1db7e7..252819f1e29 100644
--- a/tests/lib/Notification/ActionTest.php
+++ b/tests/lib/Notification/ActionTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -20,7 +21,7 @@ class ActionTest extends TestCase {
$this->action = new Action();
}
- public function dataSetLabel() {
+ public static function dataSetLabel(): array {
return [
['test1'],
[str_repeat('a', 1)],
@@ -29,16 +30,16 @@ class ActionTest extends TestCase {
}
/**
- * @dataProvider dataSetLabel
* @param string $label
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataSetLabel')]
public function testSetLabel($label): void {
$this->assertSame('', $this->action->getLabel());
$this->assertSame($this->action, $this->action->setLabel($label));
$this->assertSame($label, $this->action->getLabel());
}
- public function dataSetLabelInvalid() {
+ public static function dataSetLabelInvalid(): array {
return [
[''],
[str_repeat('a', 33)],
@@ -46,17 +47,17 @@ class ActionTest extends TestCase {
}
/**
- * @dataProvider dataSetLabelInvalid
* @param mixed $label
*
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataSetLabelInvalid')]
public function testSetLabelInvalid($label): void {
$this->expectException(\InvalidArgumentException::class);
$this->action->setLabel($label);
}
- public function dataSetParsedLabel() {
+ public static function dataSetParsedLabel(): array {
return [
['test1'],
[str_repeat('a', 1)],
@@ -65,33 +66,33 @@ class ActionTest extends TestCase {
}
/**
- * @dataProvider dataSetParsedLabel
* @param string $label
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataSetParsedLabel')]
public function testSetParsedLabel($label): void {
$this->assertSame('', $this->action->getParsedLabel());
$this->assertSame($this->action, $this->action->setParsedLabel($label));
$this->assertSame($label, $this->action->getParsedLabel());
}
- public function dataSetParsedLabelInvalid() {
+ public static function dataSetParsedLabelInvalid(): array {
return [
[''],
];
}
/**
- * @dataProvider dataSetParsedLabelInvalid
* @param mixed $label
*
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataSetParsedLabelInvalid')]
public function testSetParsedLabelInvalid($label): void {
$this->expectException(\InvalidArgumentException::class);
$this->action->setParsedLabel($label);
}
- public function dataSetLink() {
+ public static function dataSetLink(): array {
return [
['test1', 'GET'],
['test2', 'POST'],
@@ -101,10 +102,10 @@ class ActionTest extends TestCase {
}
/**
- * @dataProvider dataSetLink
* @param string $link
* @param string $type
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataSetLink')]
public function testSetLink($link, $type): void {
$this->assertSame('', $this->action->getLink());
$this->assertSame($this->action, $this->action->setLink($link, $type));
@@ -112,7 +113,7 @@ class ActionTest extends TestCase {
$this->assertSame($type, $this->action->getRequestType());
}
- public function dataSetLinkInvalid() {
+ public static function dataSetLinkInvalid(): array {
return [
// Invalid link
['', 'GET'],
@@ -124,18 +125,18 @@ class ActionTest extends TestCase {
}
/**
- * @dataProvider dataSetLinkInvalid
* @param mixed $link
* @param mixed $type
*
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataSetLinkInvalid')]
public function testSetLinkInvalid($link, $type): void {
$this->expectException(\InvalidArgumentException::class);
$this->action->setLink($link, $type);
}
- public function dataSetPrimary() {
+ public static function dataSetPrimary(): array {
return [
[true],
[false],
@@ -143,9 +144,9 @@ class ActionTest extends TestCase {
}
/**
- * @dataProvider dataSetPrimary
* @param bool $primary
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataSetPrimary')]
public function testSetPrimary($primary): void {
$this->assertSame(false, $this->action->isPrimary());
$this->assertSame($this->action, $this->action->setPrimary($primary));
diff --git a/tests/lib/Notification/ManagerTest.php b/tests/lib/Notification/ManagerTest.php
index 2a85316d7c4..cbd76989d24 100644
--- a/tests/lib/Notification/ManagerTest.php
+++ b/tests/lib/Notification/ManagerTest.php
@@ -153,7 +153,7 @@ class ManagerTest extends TestCase {
$this->coordinator,
$this->richTextFormatter,
])
- ->setMethods(['getApps'])
+ ->onlyMethods(['getApps'])
->getMock();
$manager->expects($this->once())
@@ -185,7 +185,7 @@ class ManagerTest extends TestCase {
$this->coordinator,
$this->richTextFormatter,
])
- ->setMethods(['getApps'])
+ ->onlyMethods(['getApps'])
->getMock();
$manager->expects($this->never())
@@ -210,7 +210,7 @@ class ManagerTest extends TestCase {
$this->coordinator,
$this->richTextFormatter,
])
- ->setMethods(['getApps'])
+ ->onlyMethods(['getApps'])
->getMock();
$manager->expects($this->once())
@@ -236,7 +236,7 @@ class ManagerTest extends TestCase {
$this->coordinator,
$this->richTextFormatter,
])
- ->setMethods(['getApps'])
+ ->onlyMethods(['getApps'])
->getMock();
$manager->expects($this->once())
@@ -246,7 +246,7 @@ class ManagerTest extends TestCase {
$manager->getCount($notification);
}
- public function dataIsFairUseOfFreePushService(): array {
+ public static function dataIsFairUseOfFreePushService(): array {
return [
[true, 999, true],
[true, 1000, true],
@@ -256,11 +256,11 @@ class ManagerTest extends TestCase {
}
/**
- * @dataProvider dataIsFairUseOfFreePushService
* @param bool $hasValidSubscription
* @param int $userCount
* @param bool $isFair
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataIsFairUseOfFreePushService')]
public function testIsFairUseOfFreePushService(bool $hasValidSubscription, int $userCount, bool $isFair): void {
$this->subscriptionRegistry->method('delegateHasValidSubscription')
->willReturn($hasValidSubscription);
diff --git a/tests/lib/Notification/NotificationTest.php b/tests/lib/Notification/NotificationTest.php
index 957d74233be..cebe9d51021 100644
--- a/tests/lib/Notification/NotificationTest.php
+++ b/tests/lib/Notification/NotificationTest.php
@@ -30,7 +30,7 @@ class NotificationTest extends TestCase {
$this->notification = new Notification($this->validator, $this->richTextFormatter);
}
- protected function dataValidString($maxLength) {
+ protected static function dataValidString($maxLength): array {
$dataSets = [
['test1'],
['1564'],
@@ -42,7 +42,7 @@ class NotificationTest extends TestCase {
return $dataSets;
}
- protected function dataInvalidString($maxLength) {
+ protected static function dataInvalidString($maxLength): array {
$dataSets = [
['']
];
@@ -52,29 +52,29 @@ class NotificationTest extends TestCase {
return $dataSets;
}
- public function dataSetApp() {
- return $this->dataValidString(32);
+ public static function dataSetApp(): array {
+ return self::dataValidString(32);
}
/**
- * @dataProvider dataSetApp
* @param string $app
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataSetApp')]
public function testSetApp($app): void {
$this->assertSame('', $this->notification->getApp());
$this->assertSame($this->notification, $this->notification->setApp($app));
$this->assertSame($app, $this->notification->getApp());
}
- public function dataSetAppInvalid() {
- return $this->dataInvalidString(32);
+ public static function dataSetAppInvalid(): array {
+ return self::dataInvalidString(32);
}
/**
- * @dataProvider dataSetAppInvalid
* @param mixed $app
*
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataSetAppInvalid')]
public function testSetAppInvalid($app): void {
$this->expectException(\InvalidArgumentException::class);
@@ -82,36 +82,36 @@ class NotificationTest extends TestCase {
}
- public function dataSetUser() {
- return $this->dataValidString(64);
+ public static function dataSetUser(): array {
+ return self::dataValidString(64);
}
/**
- * @dataProvider dataSetUser
* @param string $user
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataSetUser')]
public function testSetUser($user): void {
$this->assertSame('', $this->notification->getUser());
$this->assertSame($this->notification, $this->notification->setUser($user));
$this->assertSame($user, $this->notification->getUser());
}
- public function dataSetUserInvalid() {
- return $this->dataInvalidString(64);
+ public static function dataSetUserInvalid(): array {
+ return self::dataInvalidString(64);
}
/**
- * @dataProvider dataSetUserInvalid
* @param mixed $user
*
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataSetUserInvalid')]
public function testSetUserInvalid($user): void {
$this->expectException(\InvalidArgumentException::class);
$this->notification->setUser($user);
}
- public function dataSetDateTime() {
+ public static function dataSetDateTime(): array {
$past = new \DateTime();
$past->sub(new \DateInterval('P1Y'));
$current = new \DateTime();
@@ -126,16 +126,16 @@ class NotificationTest extends TestCase {
}
/**
- * @dataProvider dataSetDateTime
* @param \DateTime $dateTime
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataSetDateTime')]
public function testSetDateTime(\DateTime $dateTime): void {
$this->assertSame(0, $this->notification->getDateTime()->getTimestamp());
$this->assertSame($this->notification, $this->notification->setDateTime($dateTime));
$this->assertSame($dateTime, $this->notification->getDateTime());
}
- public function dataSetDateTimeZero() {
+ public static function dataSetDateTimeZero(): array {
$nineTeenSeventy = new \DateTime();
$nineTeenSeventy->setTimestamp(0);
return [
@@ -144,18 +144,17 @@ class NotificationTest extends TestCase {
}
/**
- * @dataProvider dataSetDateTimeZero
* @param \DateTime $dateTime
- *
* @expectedMessage 'The given date time is invalid'
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataSetDateTimeZero')]
public function testSetDateTimeZero($dateTime): void {
$this->expectException(\InvalidArgumentException::class);
$this->notification->setDateTime($dateTime);
}
- public function dataSetObject() {
+ public static function dataSetObject(): array {
return [
['a', '21'],
[str_repeat('a', 64), '42'],
@@ -163,10 +162,10 @@ class NotificationTest extends TestCase {
}
/**
- * @dataProvider dataSetObject
* @param string $type
* @param string $id
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataSetObject')]
public function testSetObject($type, $id): void {
$this->assertSame('', $this->notification->getObjectType());
$this->assertSame('', $this->notification->getObjectId());
@@ -175,11 +174,11 @@ class NotificationTest extends TestCase {
$this->assertSame($id, $this->notification->getObjectId());
}
- public function dataSetObjectTypeInvalid() {
- return $this->dataInvalidString(64);
+ public static function dataSetObjectTypeInvalid(): array {
+ return self::dataInvalidString(64);
}
- public function dataSetObjectIdInvalid() {
+ public static function dataSetObjectIdInvalid(): array {
return [
[''],
[str_repeat('a', 64 + 1)],
@@ -187,18 +186,17 @@ class NotificationTest extends TestCase {
}
/**
- * @dataProvider dataSetObjectIdInvalid
* @param mixed $id
- *
* @expectedMessage 'The given object id is invalid'
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataSetObjectIdInvalid')]
public function testSetObjectIdInvalid($id): void {
$this->expectException(\InvalidArgumentException::class);
$this->notification->setObject('object', $id);
}
- public function dataSetSubject() {
+ public static function dataSetSubject(): array {
return [
['a', []],
[str_repeat('a', 64), [str_repeat('a', 160)]],
@@ -207,10 +205,10 @@ class NotificationTest extends TestCase {
}
/**
- * @dataProvider dataSetSubject
* @param string $subject
* @param array $parameters
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataSetSubject')]
public function testSetSubject($subject, $parameters): void {
$this->assertSame('', $this->notification->getSubject());
$this->assertSame([], $this->notification->getSubjectParameters());
@@ -219,51 +217,51 @@ class NotificationTest extends TestCase {
$this->assertSame($parameters, $this->notification->getSubjectParameters());
}
- public function dataSetSubjectInvalidSubject() {
- return $this->dataInvalidString(64);
+ public static function dataSetSubjectInvalidSubject(): array {
+ return self::dataInvalidString(64);
}
/**
- * @dataProvider dataSetSubjectInvalidSubject
* @param mixed $subject
*
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataSetSubjectInvalidSubject')]
public function testSetSubjectInvalidSubject($subject): void {
$this->expectException(\InvalidArgumentException::class);
$this->notification->setSubject($subject, []);
}
- public function dataSetParsedSubject() {
- return $this->dataValidString(false);
+ public static function dataSetParsedSubject(): array {
+ return self::dataValidString(false);
}
/**
- * @dataProvider dataSetParsedSubject
* @param string $subject
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataSetParsedSubject')]
public function testSetParsedSubject($subject): void {
$this->assertSame('', $this->notification->getParsedSubject());
$this->assertSame($this->notification, $this->notification->setParsedSubject($subject));
$this->assertSame($subject, $this->notification->getParsedSubject());
}
- public function dataSetParsedSubjectInvalid() {
- return $this->dataInvalidString(false);
+ public static function dataSetParsedSubjectInvalid(): array {
+ return self::dataInvalidString(false);
}
/**
- * @dataProvider dataSetParsedSubjectInvalid
* @param mixed $subject
*
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataSetParsedSubjectInvalid')]
public function testSetParsedSubjectInvalid($subject): void {
$this->expectException(\InvalidArgumentException::class);
$this->notification->setParsedSubject($subject);
}
- public function dataSetMessage() {
+ public static function dataSetMessage(): array {
return [
['a', []],
[str_repeat('a', 64), [str_repeat('a', 160)]],
@@ -272,10 +270,10 @@ class NotificationTest extends TestCase {
}
/**
- * @dataProvider dataSetMessage
* @param string $message
* @param array $parameters
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataSetMessage')]
public function testSetMessage($message, $parameters): void {
$this->assertSame('', $this->notification->getMessage());
$this->assertSame([], $this->notification->getMessageParameters());
@@ -284,102 +282,102 @@ class NotificationTest extends TestCase {
$this->assertSame($parameters, $this->notification->getMessageParameters());
}
- public function dataSetMessageInvalidMessage() {
- return $this->dataInvalidString(64);
+ public static function dataSetMessageInvalidMessage(): array {
+ return self::dataInvalidString(64);
}
/**
- * @dataProvider dataSetMessageInvalidMessage
* @param mixed $message
*
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataSetMessageInvalidMessage')]
public function testSetMessageInvalidMessage($message): void {
$this->expectException(\InvalidArgumentException::class);
$this->notification->setMessage($message, []);
}
- public function dataSetParsedMessage() {
- return $this->dataValidString(false);
+ public static function dataSetParsedMessage(): array {
+ return self::dataValidString(false);
}
/**
- * @dataProvider dataSetParsedMessage
* @param string $message
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataSetParsedMessage')]
public function testSetParsedMessage($message): void {
$this->assertSame('', $this->notification->getParsedMessage());
$this->assertSame($this->notification, $this->notification->setParsedMessage($message));
$this->assertSame($message, $this->notification->getParsedMessage());
}
- public function dataSetParsedMessageInvalid() {
- return $this->dataInvalidString(false);
+ public static function dataSetParsedMessageInvalid(): array {
+ return self::dataInvalidString(false);
}
/**
- * @dataProvider dataSetParsedMessageInvalid
* @param mixed $message
*
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataSetParsedMessageInvalid')]
public function testSetParsedMessageInvalid($message): void {
$this->expectException(\InvalidArgumentException::class);
$this->notification->setParsedMessage($message);
}
- public function dataSetLink() {
- return $this->dataValidString(4000);
+ public static function dataSetLink(): array {
+ return self::dataValidString(4000);
}
/**
- * @dataProvider dataSetLink
* @param string $link
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataSetLink')]
public function testSetLink($link): void {
$this->assertSame('', $this->notification->getLink());
$this->assertSame($this->notification, $this->notification->setLink($link));
$this->assertSame($link, $this->notification->getLink());
}
- public function dataSetLinkInvalid() {
- return $this->dataInvalidString(4000);
+ public static function dataSetLinkInvalid(): array {
+ return self::dataInvalidString(4000);
}
/**
- * @dataProvider dataSetLinkInvalid
* @param mixed $link
*
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataSetLinkInvalid')]
public function testSetLinkInvalid($link): void {
$this->expectException(\InvalidArgumentException::class);
$this->notification->setLink($link);
}
- public function dataSetIcon() {
- return $this->dataValidString(4000);
+ public static function dataSetIcon(): array {
+ return self::dataValidString(4000);
}
/**
- * @dataProvider dataSetIcon
* @param string $icon
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataSetIcon')]
public function testSetIcon($icon): void {
$this->assertSame('', $this->notification->getIcon());
$this->assertSame($this->notification, $this->notification->setIcon($icon));
$this->assertSame($icon, $this->notification->getIcon());
}
- public function dataSetIconInvalid() {
- return $this->dataInvalidString(4000);
+ public static function dataSetIconInvalid(): array {
+ return self::dataInvalidString(4000);
}
/**
- * @dataProvider dataSetIconInvalid
* @param mixed $icon
*
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataSetIconInvalid')]
public function testSetIconInvalid($icon): void {
$this->expectException(\InvalidArgumentException::class);
@@ -392,7 +390,7 @@ class NotificationTest extends TestCase {
}
public function testAddAction(): void {
- /** @var \OCP\Notification\IAction|\PHPUnit\Framework\MockObject\MockObject $action */
+ /** @var IAction|\PHPUnit\Framework\MockObject\MockObject $action */
$action = $this->createMock(IAction::class);
$action->expects($this->once())
->method('isValid')
@@ -410,7 +408,7 @@ class NotificationTest extends TestCase {
public function testAddActionInvalid(): void {
$this->expectException(\InvalidArgumentException::class);
- /** @var \OCP\Notification\IAction|\PHPUnit\Framework\MockObject\MockObject $action */
+ /** @var IAction|\PHPUnit\Framework\MockObject\MockObject $action */
$action = $this->createMock(IAction::class);
$action->expects($this->once())
->method('isValid')
@@ -422,7 +420,7 @@ class NotificationTest extends TestCase {
}
public function testAddActionSecondPrimary(): void {
- /** @var \OCP\Notification\IAction|\PHPUnit\Framework\MockObject\MockObject $action */
+ /** @var IAction|\PHPUnit\Framework\MockObject\MockObject $action */
$action = $this->createMock(IAction::class);
$action->expects($this->exactly(2))
->method('isValid')
@@ -438,7 +436,7 @@ class NotificationTest extends TestCase {
}
public function testAddParsedAction(): void {
- /** @var \OCP\Notification\IAction|\PHPUnit\Framework\MockObject\MockObject $action */
+ /** @var IAction|\PHPUnit\Framework\MockObject\MockObject $action */
$action = $this->createMock(IAction::class);
$action->expects($this->once())
->method('isValidParsed')
@@ -456,7 +454,7 @@ class NotificationTest extends TestCase {
public function testAddParsedActionInvalid(): void {
$this->expectException(\InvalidArgumentException::class);
- /** @var \OCP\Notification\IAction|\PHPUnit\Framework\MockObject\MockObject $action */
+ /** @var IAction|\PHPUnit\Framework\MockObject\MockObject $action */
$action = $this->createMock(IAction::class);
$action->expects($this->once())
->method('isValidParsed')
@@ -468,7 +466,7 @@ class NotificationTest extends TestCase {
}
public function testAddActionSecondParsedPrimary(): void {
- /** @var \OCP\Notification\IAction|\PHPUnit\Framework\MockObject\MockObject $action */
+ /** @var IAction|\PHPUnit\Framework\MockObject\MockObject $action */
$action = $this->createMock(IAction::class);
$action->expects($this->exactly(2))
->method('isValidParsed')
@@ -484,7 +482,7 @@ class NotificationTest extends TestCase {
}
public function testAddActionParsedPrimaryEnd(): void {
- /** @var \OCP\Notification\IAction|\PHPUnit\Framework\MockObject\MockObject $action */
+ /** @var IAction|\PHPUnit\Framework\MockObject\MockObject $action */
$action1 = $this->createMock(IAction::class);
$action1->expects($this->exactly(2))
->method('isValidParsed')
@@ -492,7 +490,7 @@ class NotificationTest extends TestCase {
$action1->expects($this->exactly(2))
->method('isPrimary')
->willReturn(false);
- /** @var \OCP\Notification\IAction|\PHPUnit\Framework\MockObject\MockObject $action */
+ /** @var IAction|\PHPUnit\Framework\MockObject\MockObject $action */
$action2 = $this->createMock(IAction::class);
$action2->expects($this->once())
->method('isValidParsed')
@@ -508,7 +506,7 @@ class NotificationTest extends TestCase {
$this->assertEquals([$action2, $action1, $action1], $this->notification->getParsedActions());
}
- public function dataIsValid() {
+ public static function dataIsValid(): array {
return [
[false, '', false],
[true, '', false],
@@ -518,16 +516,16 @@ class NotificationTest extends TestCase {
}
/**
- * @dataProvider dataIsValid
*
* @param bool $isValidCommon
* @param string $subject
* @param bool $expected
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataIsValid')]
public function testIsValid($isValidCommon, $subject, $expected): void {
- /** @var \OCP\Notification\INotification|\PHPUnit\Framework\MockObject\MockObject $notification */
+ /** @var INotification|\PHPUnit\Framework\MockObject\MockObject $notification */
$notification = $this->getMockBuilder(Notification::class)
- ->setMethods([
+ ->onlyMethods([
'isValidCommon',
'getSubject',
'getParsedSubject',
@@ -551,16 +549,16 @@ class NotificationTest extends TestCase {
}
/**
- * @dataProvider dataIsValid
*
* @param bool $isValidCommon
* @param string $subject
* @param bool $expected
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataIsValid')]
public function testIsParsedValid($isValidCommon, $subject, $expected): void {
- /** @var \OCP\Notification\INotification|\PHPUnit\Framework\MockObject\MockObject $notification */
+ /** @var INotification|\PHPUnit\Framework\MockObject\MockObject $notification */
$notification = $this->getMockBuilder(Notification::class)
- ->setMethods([
+ ->onlyMethods([
'isValidCommon',
'getParsedSubject',
'getSubject',
@@ -583,7 +581,7 @@ class NotificationTest extends TestCase {
$this->assertEquals($expected, $notification->isValidParsed());
}
- public function dataIsValidCommon() {
+ public static function dataIsValidCommon(): array {
return [
['', '', 0, '', '', false],
['app', '', 0, '', '', false],
@@ -595,7 +593,6 @@ class NotificationTest extends TestCase {
}
/**
- * @dataProvider dataIsValidCommon
*
* @param string $app
* @param string $user
@@ -604,10 +601,11 @@ class NotificationTest extends TestCase {
* @param string $objectId
* @param bool $expected
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataIsValidCommon')]
public function testIsValidCommon($app, $user, $timestamp, $objectType, $objectId, $expected): void {
- /** @var \OCP\Notification\INotification|\PHPUnit\Framework\MockObject\MockObject $notification */
+ /** @var INotification|\PHPUnit\Framework\MockObject\MockObject $notification */
$notification = $this->getMockBuilder(Notification::class)
- ->setMethods([
+ ->onlyMethods([
'getApp',
'getUser',
'getDateTime',
diff --git a/tests/lib/OCS/ApiHelperTest.php b/tests/lib/OCS/ApiHelperTest.php
index fdbc1f4c538..334fca7169e 100644
--- a/tests/lib/OCS/ApiHelperTest.php
+++ b/tests/lib/OCS/ApiHelperTest.php
@@ -14,10 +14,7 @@ use OC\OCS\ApiHelper;
use OCP\IRequest;
class ApiHelperTest extends \Test\TestCase {
- /**
- * @return array
- */
- public function versionDataScriptNameProvider(): array {
+ public static function versionDataScriptNameProvider(): array {
return [
// Valid script name
[
@@ -37,9 +34,7 @@ class ApiHelperTest extends \Test\TestCase {
];
}
- /**
- * @dataProvider versionDataScriptNameProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('versionDataScriptNameProvider')]
public function testIsV2(string $scriptName, bool $expected): void {
$request = $this->getMockBuilder(IRequest::class)
->disableOriginalConstructor()
diff --git a/tests/lib/OCS/DiscoveryServiceTest.php b/tests/lib/OCS/DiscoveryServiceTest.php
index 3db3163e11d..422c97f4221 100644
--- a/tests/lib/OCS/DiscoveryServiceTest.php
+++ b/tests/lib/OCS/DiscoveryServiceTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2017 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
@@ -35,17 +36,17 @@ class DiscoveryServiceTest extends TestCase {
}
/**
- * @dataProvider dataTestIsSafeUrl
*
* @param string $url
* @param bool $expected
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataTestIsSafeUrl')]
public function testIsSafeUrl($url, $expected): void {
$result = $this->invokePrivate($this->discoveryService, 'isSafeUrl', [$url]);
$this->assertSame($expected, $result);
}
- public function dataTestIsSafeUrl() {
+ public static function dataTestIsSafeUrl(): array {
return [
['api/ocs/v1.php/foo', true],
['/api/ocs/v1.php/foo', true],
@@ -58,18 +59,18 @@ class DiscoveryServiceTest extends TestCase {
}
/**
- * @dataProvider dataTestGetEndpoints
*
* @param array $decodedServices
* @param string $service
* @param array $expected
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataTestGetEndpoints')]
public function testGetEndpoints($decodedServices, $service, $expected): void {
$result = $this->invokePrivate($this->discoveryService, 'getEndpoints', [$decodedServices, $service]);
$this->assertSame($expected, $result);
}
- public function dataTestGetEndpoints() {
+ public static function dataTestGetEndpoints(): array {
return [
[['services' => ['myService' => ['endpoints' => []]]], 'myService', []],
[['services' => ['myService' => ['endpoints' => ['foo' => '/bar']]]], 'myService', ['foo' => '/bar']],
diff --git a/tests/lib/OCS/ProviderTest.php b/tests/lib/OCS/ProviderTest.php
index ce028ce764a..87e01d8301b 100644
--- a/tests/lib/OCS/ProviderTest.php
+++ b/tests/lib/OCS/ProviderTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2017-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -8,11 +9,14 @@
namespace Test\OCS;
use OC\OCS\Provider;
+use OCP\App\IAppManager;
+use OCP\AppFramework\Http\JSONResponse;
+use OCP\IRequest;
class ProviderTest extends \Test\TestCase {
- /** @var \OCP\IRequest */
+ /** @var IRequest */
private $request;
- /** @var \OCP\App\IAppManager */
+ /** @var IAppManager */
private $appManager;
/** @var Provider */
private $ocsProvider;
@@ -36,7 +40,7 @@ class ProviderTest extends \Test\TestCase {
['provisioning_api', null, false],
]);
- $expected = new \OCP\AppFramework\Http\JSONResponse(
+ $expected = new JSONResponse(
[
'version' => 2,
'services' => [
@@ -66,7 +70,7 @@ class ProviderTest extends \Test\TestCase {
['provisioning_api', null, false],
]);
- $expected = new \OCP\AppFramework\Http\JSONResponse(
+ $expected = new JSONResponse(
[
'version' => 2,
'services' => [
@@ -109,7 +113,7 @@ class ProviderTest extends \Test\TestCase {
['provisioning_api', null, false],
]);
- $expected = new \OCP\AppFramework\Http\JSONResponse(
+ $expected = new JSONResponse(
[
'version' => 2,
'services' => [
@@ -142,7 +146,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..36e768010a9 100644
--- a/tests/lib/Preview/BitmapTest.php
+++ b/tests/lib/Preview/BitmapTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -7,6 +8,8 @@
namespace Test\Preview;
+use OC\Preview\Postscript;
+
/**
* Class BitmapTest
*
@@ -22,6 +25,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/GeneratorTest.php b/tests/lib/Preview/GeneratorTest.php
index 607127a6495..edf5418da6e 100644
--- a/tests/lib/Preview/GeneratorTest.php
+++ b/tests/lib/Preview/GeneratorTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
@@ -343,7 +344,7 @@ class GeneratorTest extends \Test\TestCase {
return $image;
}
- public function dataSize() {
+ public static function dataSize(): array {
return [
[1024, 2048, 512, 512, false, IPreview::MODE_FILL, 256, 512],
[1024, 2048, 512, 512, false, IPreview::MODE_COVER, 512, 1024],
@@ -380,7 +381,6 @@ class GeneratorTest extends \Test\TestCase {
}
/**
- * @dataProvider dataSize
*
* @param int $maxX
* @param int $maxY
@@ -391,6 +391,7 @@ class GeneratorTest extends \Test\TestCase {
* @param int $expectedX
* @param int $expectedY
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataSize')]
public function testCorrectSize($maxX, $maxY, $reqX, $reqY, $crop, $mode, $expectedX, $expectedY): void {
$file = $this->createMock(File::class);
$file->method('isReadable')
diff --git a/tests/lib/Preview/HEICTest.php b/tests/lib/Preview/HEICTest.php
index 5df7b63dd03..def113fbf08 100644
--- a/tests/lib/Preview/HEICTest.php
+++ b/tests/lib/Preview/HEICTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2018 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
@@ -6,6 +7,8 @@
namespace Test\Preview;
+use OC\Preview\HEIC;
+
/**
* Class BitmapTest
*
@@ -24,7 +27,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..88c3090557f 100644
--- a/tests/lib/Preview/ImageTest.php
+++ b/tests/lib/Preview/ImageTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -7,6 +8,8 @@
namespace Test\Preview;
+use OC\Preview\JPEG;
+
/**
* Class ImageTest
*
@@ -22,6 +25,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..faa06fe42a1 100644
--- a/tests/lib/Preview/MP3Test.php
+++ b/tests/lib/Preview/MP3Test.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -7,6 +8,8 @@
namespace Test\Preview;
+use OC\Preview\MP3;
+
/**
* Class MP3Test
*
@@ -22,6 +25,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/MovieBrokenStuckFfmpegTest.php b/tests/lib/Preview/MovieBrokenStuckFfmpegTest.php
new file mode 100644
index 00000000000..e66d5e64649
--- /dev/null
+++ b/tests/lib/Preview/MovieBrokenStuckFfmpegTest.php
@@ -0,0 +1,20 @@
+<?php
+
+declare(strict_types=1);
+/**
+ * SPDX-FileCopyrightText: 2025 Nextcloud GmbH and Nextcloud contributors
+ * SPDX-License-Identifier: AGPL-3.0-or-later
+ */
+
+namespace Test\Preview;
+
+/**
+ * Class MovieTest
+ *
+ * @group DB
+ *
+ * @package Test\Preview
+ */
+class MovieBrokenStuckFfmpegTest extends MovieTest {
+ protected string $fileName = 'broken-video.webm';
+}
diff --git a/tests/lib/Preview/MovieTest.php b/tests/lib/Preview/MovieTest.php
index b8946ad4c5e..c85a9f99748 100644
--- a/tests/lib/Preview/MovieTest.php
+++ b/tests/lib/Preview/MovieTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -7,6 +8,7 @@
namespace Test\Preview;
+use OC\Preview\Movie;
use OCP\IBinaryFinder;
use OCP\Server;
@@ -18,6 +20,10 @@ use OCP\Server;
* @package Test\Preview
*/
class MovieTest extends Provider {
+ protected string $fileName = 'testimage.mp4';
+ protected int $width = 560;
+ protected int $height = 320;
+
protected function setUp(): void {
$binaryFinder = Server::get(IBinaryFinder::class);
$movieBinary = $binaryFinder->findBinaryPath('avconv');
@@ -28,11 +34,8 @@ class MovieTest extends Provider {
if (is_string($movieBinary)) {
parent::setUp();
- $fileName = 'testimage.mp4';
- $this->imgPath = $this->prepareTestFile($fileName, \OC::$SERVERROOT . '/tests/data/' . $fileName);
- $this->width = 560;
- $this->height = 320;
- $this->provider = new \OC\Preview\Movie(['movieBinary' => $movieBinary]);
+ $this->imgPath = $this->prepareTestFile($this->fileName, \OC::$SERVERROOT . '/tests/data/' . $this->fileName);
+ $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 c9019d017a3..62a4767fd2e 100644
--- a/tests/lib/Preview/OfficeTest.php
+++ b/tests/lib/Preview/OfficeTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -7,6 +8,10 @@
namespace Test\Preview;
+use OC\Preview\OpenDocument;
+use OCP\IBinaryFinder;
+use OCP\Server;
+
/**
* Class OfficeTest
*
@@ -16,17 +21,18 @@ namespace Test\Preview;
*/
class OfficeTest extends Provider {
protected function setUp(): void {
- $libreofficeBinary = \OC_Helper::findBinaryPath('libreoffice');
- $openofficeBinary = ($libreofficeBinary) ? null : \OC_Helper::findBinaryPath('openoffice');
+ $binaryFinder = Server::get(IBinaryFinder::class);
+ $libreofficeBinary = $binaryFinder->findBinaryPath('libreoffice');
+ $openofficeBinary = $libreofficeBinary === false ? $binaryFinder->findBinaryPath('openoffice') : false;
- if ($libreofficeBinary || $openofficeBinary) {
+ if ($libreofficeBinary !== false || $openofficeBinary !== false) {
parent::setUp();
$fileName = 'testimage.odt';
$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..d8f10c430e4 100644
--- a/tests/lib/Preview/Provider.php
+++ b/tests/lib/Preview/Provider.php
@@ -8,9 +8,16 @@
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\IImage;
use OCP\IUserManager;
+use OCP\Server;
abstract class Provider extends \Test\TestCase {
protected string $imgPath;
@@ -22,13 +29,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 +44,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');
@@ -65,12 +72,12 @@ abstract class Provider extends \Test\TestCase {
/**
* Launches all the tests we have
*
- * @dataProvider dimensionsDataProvider
* @requires extension imagick
*
* @param int $widthAdjustment
* @param int $heightAdjustment
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dimensionsDataProvider')]
public function testGetThumbnail($widthAdjustment, $heightAdjustment): void {
$ratio = round($this->width / $this->height, 2);
$this->maxWidth = $this->width - $widthAdjustment;
@@ -84,7 +91,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);
@@ -114,10 +121,10 @@ abstract class Provider extends \Test\TestCase {
*
* @param \OC\Preview\Provider $provider
*
- * @return bool|\OCP\IImage
+ * @return bool|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) {
@@ -133,7 +140,7 @@ abstract class Provider extends \Test\TestCase {
/**
* Checks if the preview ratio matches the original ratio
*
- * @param \OCP\IImage $preview
+ * @param IImage $preview
* @param int $ratio
*/
private function doesRatioMatch($preview, $ratio) {
@@ -144,7 +151,7 @@ abstract class Provider extends \Test\TestCase {
/**
* Tests if a max size preview of smaller dimensions can be created
*
- * @param \OCP\IImage $preview
+ * @param IImage $preview
*/
private function doesPreviewFit($preview) {
$maxDimRatio = round($this->maxWidth / $this->maxHeight, 2);
diff --git a/tests/lib/Preview/SVGTest.php b/tests/lib/Preview/SVGTest.php
index 6a0e93e5f79..8c6d9bb6691 100644
--- a/tests/lib/Preview/SVGTest.php
+++ b/tests/lib/Preview/SVGTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -7,6 +8,9 @@
namespace Test\Preview;
+use OC\Preview\SVG;
+use OCP\Files\File;
+
/**
* Class SVGTest
*
@@ -24,13 +28,13 @@ 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');
}
}
- public function dataGetThumbnailSVGHref(): array {
+ public static function dataGetThumbnailSVGHref(): array {
return [
['href'],
[' href'],
@@ -42,9 +46,9 @@ class SVGTest extends Provider {
}
/**
- * @dataProvider dataGetThumbnailSVGHref
* @requires extension imagick
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataGetThumbnailSVGHref')]
public function testGetThumbnailSVGHref(string $content): void {
$handle = fopen('php://temp', 'w+');
fwrite($handle, '<svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">
@@ -52,7 +56,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..d722495136c 100644
--- a/tests/lib/Preview/TXTTest.php
+++ b/tests/lib/Preview/TXTTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -7,6 +8,8 @@
namespace Test\Preview;
+use OC\Preview\TXT;
+
/**
* Class TXTTest
*
@@ -23,6 +26,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/Profile/Actions/FediverseActionTest.php b/tests/lib/Profile/Actions/FediverseActionTest.php
index c0e2e6e6309..7f4c7d96301 100644
--- a/tests/lib/Profile/Actions/FediverseActionTest.php
+++ b/tests/lib/Profile/Actions/FediverseActionTest.php
@@ -105,7 +105,7 @@ class FediverseActionTest extends TestCase {
];
}
- /** @dataProvider dataGetTitle */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataGetTitle')]
public function testGetTitle(string $value): void {
$property = $this->createMock(IAccountProperty::class);
$property->method('getValue')
@@ -154,7 +154,7 @@ class FediverseActionTest extends TestCase {
];
}
- /** @dataProvider dataGetTarget */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataGetTarget')]
public function testGetTarget(?string $value, ?string $expected): void {
$user = $this->createMock(IUser::class);
diff --git a/tests/lib/Remote/Api/OCSTest.php b/tests/lib/Remote/Api/OCSTest.php
index 3fcc486f246..89fd45f0791 100644
--- a/tests/lib/Remote/Api/OCSTest.php
+++ b/tests/lib/Remote/Api/OCSTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2017 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
@@ -6,6 +7,7 @@
namespace Test\Remote\Api;
+use OC\ForbiddenException;
use OC\Memcache\ArrayCache;
use OC\Remote\Api\OCS;
use OC\Remote\Credentials;
@@ -52,7 +54,7 @@ class OCSTest extends TestCase {
$this->assertEquals('user', $user->getUserId());
}
-
+
public function testGetUserInvalidResponse(): void {
$this->expectException(\Exception::class);
$this->expectExceptionMessage('Invalid user response, expected field email not found');
@@ -66,9 +68,9 @@ class OCSTest extends TestCase {
$client->getUser('user');
}
-
+
public function testInvalidPassword(): void {
- $this->expectException(\OC\ForbiddenException::class);
+ $this->expectException(ForbiddenException::class);
$client = $this->getOCSClient();
diff --git a/tests/lib/Remote/InstanceTest.php b/tests/lib/Remote/InstanceTest.php
index 027a67010be..560706e4572 100644
--- a/tests/lib/Remote/InstanceTest.php
+++ b/tests/lib/Remote/InstanceTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2017 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
@@ -57,7 +58,7 @@ class InstanceTest extends TestCase {
$this->assertEquals(false, $instance2->isActive());
}
-
+
public function testPreventDowngradeAttach(): void {
$this->expectException(\Exception::class);
$this->expectExceptionMessage('refusing to connect to remote instance(example.com) over http that was previously accessible over https');
diff --git a/tests/lib/Repair/CleanTagsTest.php b/tests/lib/Repair/CleanTagsTest.php
index adb14b16fc4..04afabb87d9 100644
--- a/tests/lib/Repair/CleanTagsTest.php
+++ b/tests/lib/Repair/CleanTagsTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -7,10 +8,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 +26,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 +43,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..3e5927565fe 100644
--- a/tests/lib/Repair/ClearFrontendCachesTest.php
+++ b/tests/lib/Repair/ClearFrontendCachesTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2018 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
@@ -6,6 +7,7 @@
namespace Test\Repair;
+use OC\Repair\ClearFrontendCaches;
use OC\Template\JSCombiner;
use OCP\ICache;
use OCP\ICacheFactory;
@@ -18,7 +20,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 +30,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/ClearGeneratedAvatarCacheTest.php b/tests/lib/Repair/ClearGeneratedAvatarCacheTest.php
index 810fa1fe4e8..43203d489e6 100644
--- a/tests/lib/Repair/ClearGeneratedAvatarCacheTest.php
+++ b/tests/lib/Repair/ClearGeneratedAvatarCacheTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2018 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
@@ -30,7 +31,7 @@ class ClearGeneratedAvatarCacheTest extends \Test\TestCase {
$this->repair = new ClearGeneratedAvatarCache($this->config, $this->avatarManager, $this->jobList);
}
- public function shouldRunDataProvider() {
+ public static function shouldRunDataProvider(): array {
return [
['11.0.0.0', true],
['15.0.0.3', true],
@@ -44,11 +45,11 @@ class ClearGeneratedAvatarCacheTest extends \Test\TestCase {
}
/**
- * @dataProvider shouldRunDataProvider
*
* @param string $from
* @param boolean $expected
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('shouldRunDataProvider')]
public function testShouldRun($from, $expected): void {
$this->config->expects($this->any())
->method('getSystemValueString')
diff --git a/tests/lib/Repair/NC29/SanitizeAccountPropertiesJobTest.php b/tests/lib/Repair/NC29/SanitizeAccountPropertiesJobTest.php
index e0f4eb3cbc1..2a4f6e9ecf1 100644
--- a/tests/lib/Repair/NC29/SanitizeAccountPropertiesJobTest.php
+++ b/tests/lib/Repair/NC29/SanitizeAccountPropertiesJobTest.php
@@ -24,7 +24,7 @@ class SanitizeAccountPropertiesJobTest extends TestCase {
private IUserManager&MockObject $userManager;
private IAccountManager&MockObject $accountManager;
private LoggerInterface&MockObject $logger;
-
+
private SanitizeAccountPropertiesJob $job;
protected function setUp(): void {
@@ -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..099290b18ed 100644
--- a/tests/lib/Repair/OldGroupMembershipSharesTest.php
+++ b/tests/lib/Repair/OldGroupMembershipSharesTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -11,6 +12,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 +34,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..fc88ee5d226 100644
--- a/tests/lib/Repair/Owncloud/CleanPreviewsBackgroundJobTest.php
+++ b/tests/lib/Repair/Owncloud/CleanPreviewsBackgroundJobTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
@@ -71,8 +72,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 +84,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 +118,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 +126,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 +149,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 +177,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 +212,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 +224,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..e5a4441a4fa 100644
--- a/tests/lib/Repair/Owncloud/CleanPreviewsTest.php
+++ b/tests/lib/Repair/Owncloud/CleanPreviewsTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
@@ -52,15 +53,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..a3eb163b0d6 100644
--- a/tests/lib/Repair/Owncloud/UpdateLanguageCodesTest.php
+++ b/tests/lib/Repair/Owncloud/UpdateLanguageCodesTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
@@ -11,6 +12,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 +31,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 +93,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..3c51325562d 100644
--- a/tests/lib/Repair/RepairCollationTest.php
+++ b/tests/lib/Repair/RepairCollationTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -12,6 +13,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 +47,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 dfcdce3801a..72103976da5 100644
--- a/tests/lib/Repair/RepairInvalidSharesTest.php
+++ b/tests/lib/Repair/RepairInvalidSharesTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -8,9 +9,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 +40,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);
@@ -122,7 +125,7 @@ class RepairInvalidSharesTest extends TestCase {
$result->closeCursor();
}
- public function fileSharePermissionsProvider() {
+ public static function fileSharePermissionsProvider(): array {
return [
// unchanged for folder
[
@@ -133,23 +136,22 @@ 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,
],
];
}
/**
* Test adjusting file share permissions
- *
- * @dataProvider fileSharePermissionsProvider
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('fileSharePermissionsProvider')]
public function testFileSharePermissions($itemType, $testPerms, $expectedPerms): void {
$qb = $this->connection->getQueryBuilder();
$qb->insert('share')
diff --git a/tests/lib/Repair/RepairMimeTypesTest.php b/tests/lib/Repair/RepairMimeTypesTest.php
index 4f044c054d3..0261b56ebe9 100644
--- a/tests/lib/Repair/RepairMimeTypesTest.php
+++ b/tests/lib/Repair/RepairMimeTypesTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2017-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -14,6 +15,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 +34,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 +57,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..fd1f6b42e41 100644
--- a/tests/lib/RepairTest.php
+++ b/tests/lib/RepairTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -13,21 +14,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 +46,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 +93,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 9299a556972..60ea820e844 100644
--- a/tests/lib/RichObjectStrings/DefinitionsTest.php
+++ b/tests/lib/RichObjectStrings/DefinitionsTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
@@ -7,10 +8,11 @@
namespace Test\RichObjectStrings;
use OCP\RichObjectStrings\Definitions;
+use OCP\RichObjectStrings\InvalidObjectExeption;
use Test\TestCase;
class DefinitionsTest extends TestCase {
- public function dataGetDefinition() {
+ public static function dataGetDefinition() {
$definitions = new Definitions();
$testsuite = [];
foreach ($definitions->definitions as $type => $definition) {
@@ -19,9 +21,9 @@ class DefinitionsTest extends TestCase {
return $testsuite;
}
-
+
public function testGetDefinitionNotExisting(): void {
- $this->expectException(\OCP\RichObjectStrings\InvalidObjectExeption::class);
+ $this->expectException(InvalidObjectExeption::class);
$this->expectExceptionMessage('Object type is undefined');
$definitions = new Definitions();
@@ -29,10 +31,10 @@ class DefinitionsTest extends TestCase {
}
/**
- * @dataProvider dataGetDefinition
* @param string $type
* @param array $expected
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataGetDefinition')]
public function testGetDefinition($type, array $expected): void {
$definitions = new Definitions();
$definition = $definitions->getDefinition($type);
diff --git a/tests/lib/RichObjectStrings/ValidatorTest.php b/tests/lib/RichObjectStrings/ValidatorTest.php
index c5f88394a33..26688d3401a 100644
--- a/tests/lib/RichObjectStrings/ValidatorTest.php
+++ b/tests/lib/RichObjectStrings/ValidatorTest.php
@@ -80,9 +80,7 @@ class ValidatorTest extends TestCase {
];
}
- /**
- * @dataProvider dataValidateParameterKeys
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataValidateParameterKeys')]
public function testValidateParameterKeys(mixed $key, ?string $throws): void {
if ($throws !== null) {
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/Bruteforce/Backend/MemoryCacheBackendTest.php b/tests/lib/Security/Bruteforce/Backend/MemoryCacheBackendTest.php
index 82bffb74e01..e0289fa7ca9 100644
--- a/tests/lib/Security/Bruteforce/Backend/MemoryCacheBackendTest.php
+++ b/tests/lib/Security/Bruteforce/Backend/MemoryCacheBackendTest.php
@@ -36,7 +36,7 @@ class MemoryCacheBackendTest extends TestCase {
$this->cacheFactory
->expects($this->once())
->method('createDistributed')
- ->with('OC\Security\Bruteforce\Backend\MemoryCacheBackend')
+ ->with(MemoryCacheBackend::class)
->willReturn($this->cache);
$this->backend = new MemoryCacheBackend(
@@ -55,7 +55,7 @@ class MemoryCacheBackendTest extends TestCase {
$this->assertSame(0, $this->backend->getAttempts('10.10.10.10/32', 0));
}
- public function dataGetAttempts(): array {
+ public static function dataGetAttempts(): array {
return [
[0, null, null, 4],
[100, null, null, 2],
@@ -67,9 +67,7 @@ class MemoryCacheBackendTest extends TestCase {
];
}
- /**
- * @dataProvider dataGetAttempts
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataGetAttempts')]
public function testGetAttempts(int $maxAge, ?string $action, ?array $metadata, int $expected): void {
$this->cache
->expects($this->once())
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..86f458d8ea8 100644
--- a/tests/lib/Security/CSRF/CsrfTokenGeneratorTest.php
+++ b/tests/lib/Security/CSRF/CsrfTokenGeneratorTest.php
@@ -10,8 +10,11 @@ declare(strict_types=1);
namespace Test\Security\CSRF;
+use OC\Security\CSRF\CsrfTokenGenerator;
+use OCP\Security\ISecureRandom;
+
class CsrfTokenGeneratorTest extends \Test\TestCase {
- /** @var \OCP\Security\ISecureRandom */
+ /** @var ISecureRandom */
private $random;
/** @var \OC\Security\CSRF\CsrfTokenGenerator */
private $csrfTokenGenerator;
@@ -20,7 +23,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 f8386124626..2b2c4af0444 100644
--- a/tests/lib/Security/CSRF/TokenStorage/SessionStorageTest.php
+++ b/tests/lib/Security/CSRF/TokenStorage/SessionStorageTest.php
@@ -10,10 +10,11 @@ declare(strict_types=1);
namespace Test\Security\CSRF\TokenStorage;
+use OC\Security\CSRF\TokenStorage\SessionStorage;
use OCP\ISession;
class SessionStorageTest extends \Test\TestCase {
- /** @var \OCP\ISession */
+ /** @var ISession */
private $session;
/** @var \OC\Security\CSRF\TokenStorage\SessionStorage */
private $sessionStorage;
@@ -22,13 +23,13 @@ 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);
}
/**
* @return array
*/
- public function getTokenDataProvider() {
+ public static function getTokenDataProvider(): array {
return [
[
'',
@@ -41,9 +42,9 @@ class SessionStorageTest extends \Test\TestCase {
/**
* @param string $token
- * @dataProvider getTokenDataProvider
*
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('getTokenDataProvider')]
public function testGetTokenWithEmptyToken($token): void {
$this->expectException(\Exception::class);
$this->expectExceptionMessage('Session does not contain a requesttoken');
diff --git a/tests/lib/Security/CertificateManagerTest.php b/tests/lib/Security/CertificateManagerTest.php
index 1c168228b6a..4dadc824ef6 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());
}
@@ -100,10 +105,7 @@ class CertificateManagerTest extends \Test\TestCase {
$this->certificateManager->addCertificate('InvalidCertificate', 'invalidCertificate');
}
- /**
- * @return array
- */
- public function dangerousFileProvider() {
+ public static function dangerousFileProvider(): array {
return [
['.htaccess'],
['../../foo.txt'],
@@ -112,9 +114,9 @@ class CertificateManagerTest extends \Test\TestCase {
}
/**
- * @dataProvider dangerousFileProvider
* @param string $filename
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dangerousFileProvider')]
public function testAddDangerousFile($filename): void {
$this->expectException(InvalidPathException::class);
$this->certificateManager->addCertificate(file_get_contents(__DIR__ . '/../../data/certificates/expiredCertificate.crt'), $filename);
@@ -134,13 +136,13 @@ class CertificateManagerTest extends \Test\TestCase {
}
/**
- * @dataProvider dataTestNeedRebundling
*
* @param int $CaBundleMtime
* @param int $targetBundleMtime
* @param int $targetBundleExists
* @param bool $expected
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataTestNeedRebundling')]
public function testNeedRebundling($CaBundleMtime,
$targetBundleMtime,
$targetBundleExists,
@@ -153,7 +155,7 @@ class CertificateManagerTest extends \Test\TestCase {
/** @var CertificateManager | \PHPUnit\Framework\MockObject\MockObject $certificateManager */
$certificateManager = $this->getMockBuilder('OC\Security\CertificateManager')
->setConstructorArgs([$view, $config, $this->createMock(LoggerInterface::class), $this->random])
- ->setMethods(['getFilemtimeOfCaBundle', 'getCertificateBundle'])
+ ->onlyMethods(['getFilemtimeOfCaBundle', 'getCertificateBundle'])
->getMock();
$certificateManager->expects($this->any())->method('getFilemtimeOfCaBundle')
@@ -181,7 +183,7 @@ class CertificateManagerTest extends \Test\TestCase {
);
}
- public function dataTestNeedRebundling() {
+ public static function dataTestNeedRebundling(): array {
return [
//values: CaBundleMtime, targetBundleMtime, targetBundleExists, expected
diff --git a/tests/lib/Security/CertificateTest.php b/tests/lib/Security/CertificateTest.php
index 3b833974321..732b431d73e 100644
--- a/tests/lib/Security/CertificateTest.php
+++ b/tests/lib/Security/CertificateTest.php
@@ -31,7 +31,7 @@ class CertificateTest extends \Test\TestCase {
$this->expiredCertificate = new Certificate($expiredCertificate, 'ExpiredCertificate');
}
-
+
public function testBogusData(): void {
$this->expectException(\Exception::class);
$this->expectExceptionMessage('Certificate could not get parsed.');
diff --git a/tests/lib/Security/CredentialsManagerTest.php b/tests/lib/Security/CredentialsManagerTest.php
index ce60a2f62a2..4dfe8c5681d 100644
--- a/tests/lib/Security/CredentialsManagerTest.php
+++ b/tests/lib/Security/CredentialsManagerTest.php
@@ -17,9 +17,7 @@ use OCP\Server;
* @group DB
*/
class CredentialsManagerTest extends \Test\TestCase {
- /**
- * @dataProvider credentialsProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('credentialsProvider')]
public function testWithDB($userId, $identifier): void {
$credentialsManager = Server::get(ICredentialsManager::class);
@@ -34,9 +32,7 @@ class CredentialsManagerTest extends \Test\TestCase {
$this->assertSame(1, $removedRows);
}
- /**
- * @dataProvider credentialsProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('credentialsProvider')]
public function testUpdate($userId, $identifier): void {
$credentialsManager = Server::get(ICredentialsManager::class);
@@ -50,7 +46,7 @@ class CredentialsManagerTest extends \Test\TestCase {
$this->assertSame($secretsRev, $received);
}
- public function credentialsProvider(): array {
+ public static function credentialsProvider(): array {
return [
[
'alice',
diff --git a/tests/lib/Security/CryptoTest.php b/tests/lib/Security/CryptoTest.php
index 79140b34456..0f8575ab0b5 100644
--- a/tests/lib/Security/CryptoTest.php
+++ b/tests/lib/Security/CryptoTest.php
@@ -11,9 +11,11 @@ declare(strict_types=1);
namespace Test\Security;
use OC\Security\Crypto;
+use OCP\IConfig;
+use OCP\Server;
class CryptoTest extends \Test\TestCase {
- public function defaultEncryptionProvider() {
+ public static function defaultEncryptionProvider(): array {
return [
['Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt.'],
[''],
@@ -26,12 +28,10 @@ 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));
}
- /**
- * @dataProvider defaultEncryptionProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('defaultEncryptionProvider')]
public function testDefaultEncrypt($stringToEncrypt): void {
$ciphertext = $this->crypto->encrypt($stringToEncrypt);
$this->assertEquals($stringToEncrypt, $this->crypto->decrypt($ciphertext));
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/HasherTest.php b/tests/lib/Security/HasherTest.php
index 41cad7f323f..33130f86a73 100644
--- a/tests/lib/Security/HasherTest.php
+++ b/tests/lib/Security/HasherTest.php
@@ -17,10 +17,7 @@ use OCP\IConfig;
* Class HasherTest
*/
class HasherTest extends \Test\TestCase {
- /**
- * @return array
- */
- public function versionHashProvider() {
+ public static function versionHashProvider(): array {
return [
['asf32äà$$a.|3', null],
['asf32äà$$a.|3|5', null],
@@ -30,7 +27,7 @@ class HasherTest extends \Test\TestCase {
];
}
- public function hashProviders70_71(): array {
+ public static function hashProviders70_71(): array {
return [
// Valid SHA1 strings
['password', '5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8', true],
@@ -66,7 +63,7 @@ class HasherTest extends \Test\TestCase {
];
}
- public function hashProviders72(): array {
+ public static function hashProviders72(): array {
return [
// Valid ARGON2 hashes
['password', '2|$argon2i$v=19$m=1024,t=2,p=2$T3JGcEkxVFNOVktNSjZUcg$4/hyLtSejxNgAuzSFFV/HLM3qRQKBwEtKw61qPN4zWA', true],
@@ -83,7 +80,7 @@ class HasherTest extends \Test\TestCase {
];
}
- public function hashProviders73(): array {
+ public static function hashProviders73(): array {
return [
// Valid ARGON2ID hashes
['password', '2|$argon2id$v=19$m=65536,t=4,p=1$TEtIMnhUczliQzI0Y01WeA$BpMUDrApy25iagIogUAnlc0rNTPJmGs8lOEeVHujJ9Q', true],
@@ -127,18 +124,14 @@ class HasherTest extends \Test\TestCase {
$this->assertNotNull($hash);
}
- /**
- * @dataProvider versionHashProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('versionHashProvider')]
public function testSplitHash($hash, $expected): void {
$relativePath = self::invokePrivate($this->hasher, 'splitHash', [$hash]);
$this->assertSame($expected, $relativePath);
}
- /**
- * @dataProvider hashProviders70_71
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('hashProviders70_71')]
public function testVerify($password, $hash, $expected): void {
$this->config
->expects($this->any())
@@ -154,9 +147,7 @@ class HasherTest extends \Test\TestCase {
$this->assertSame($expected, $result);
}
- /**
- * @dataProvider hashProviders72
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('hashProviders72')]
public function testVerifyArgon2i($password, $hash, $expected): void {
if (!\defined('PASSWORD_ARGON2I')) {
$this->markTestSkipped('Need ARGON2 support to test ARGON2 hashes');
@@ -166,9 +157,7 @@ class HasherTest extends \Test\TestCase {
$this->assertSame($expected, $result);
}
- /**
- * @dataProvider hashProviders73
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('hashProviders73')]
public function testVerifyArgon2id(string $password, string $hash, bool $expected): void {
if (!\defined('PASSWORD_ARGON2ID')) {
$this->markTestSkipped('Need ARGON2ID support to test ARGON2ID hashes');
diff --git a/tests/lib/Security/Ip/BruteforceAllowListTest.php b/tests/lib/Security/Ip/BruteforceAllowListTest.php
index f7ef9e3df72..0cffc128d64 100644
--- a/tests/lib/Security/Ip/BruteforceAllowListTest.php
+++ b/tests/lib/Security/Ip/BruteforceAllowListTest.php
@@ -42,7 +42,7 @@ class BruteforceAllowListTest extends TestCase {
);
}
- public function dataIsBypassListed(): array {
+ public static function dataIsBypassListed(): array {
return [
[
'10.10.10.10',
@@ -130,10 +130,9 @@ class BruteforceAllowListTest extends TestCase {
}
/**
- * @dataProvider dataIsBypassListed
- *
* @param string[] $allowList
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataIsBypassListed')]
public function testIsBypassListed(
string $ip,
array $allowList,
diff --git a/tests/lib/Security/Ip/RemoteAddressTest.php b/tests/lib/Security/Ip/RemoteAddressTest.php
index d1f621796fe..a6619cffe8e 100644
--- a/tests/lib/Security/Ip/RemoteAddressTest.php
+++ b/tests/lib/Security/Ip/RemoteAddressTest.php
@@ -25,8 +25,8 @@ class RemoteAddressTest extends \Test\TestCase {
/**
* @param mixed $allowedRanges
- * @dataProvider dataProvider
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataProvider')]
public function testAllowedIps(string $remoteIp, $allowedRanges, bool $expected): void {
$this->request
->method('getRemoteAddress')
@@ -44,7 +44,7 @@ class RemoteAddressTest extends \Test\TestCase {
/**
* @return array<string, mixed, bool>
*/
- public function dataProvider(): array {
+ public static function dataProvider(): array {
return [
// No IP (ie. CLI)
['', ['192.168.1.2/24'], true],
diff --git a/tests/lib/Security/Normalizer/IpAddressTest.php b/tests/lib/Security/Normalizer/IpAddressTest.php
index 33a8b4d28f1..f7adfb4a0dd 100644
--- a/tests/lib/Security/Normalizer/IpAddressTest.php
+++ b/tests/lib/Security/Normalizer/IpAddressTest.php
@@ -13,7 +13,7 @@ use OC\Security\Normalizer\IpAddress;
use Test\TestCase;
class IpAddressTest extends TestCase {
- public function subnetDataProvider() {
+ public static function subnetDataProvider(): array {
return [
[
'64.233.191.254',
@@ -55,11 +55,11 @@ class IpAddressTest extends TestCase {
}
/**
- * @dataProvider subnetDataProvider
*
* @param string $input
* @param string $expected
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('subnetDataProvider')]
public function testGetSubnet($input, $expected): void {
$this->assertSame($expected, (new IpAddress($input))->getSubnet());
}
diff --git a/tests/lib/Security/RateLimiting/LimiterTest.php b/tests/lib/Security/RateLimiting/LimiterTest.php
index 92600e22de8..b19d5c6feba 100644
--- a/tests/lib/Security/RateLimiting/LimiterTest.php
+++ b/tests/lib/Security/RateLimiting/LimiterTest.php
@@ -10,29 +10,35 @@ 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;
+use PHPUnit\Framework\MockObject\MockObject;
+use Psr\Log\LoggerInterface;
use Test\TestCase;
class LimiterTest extends TestCase {
- /** @var IBackend|\PHPUnit\Framework\MockObject\MockObject */
- private $backend;
- /** @var Limiter */
- private $limiter;
+
+ private IBackend&MockObject $backend;
+ private ILimiter $limiter;
+ private LoggerInterface $logger;
protected function setUp(): void {
parent::setUp();
$this->backend = $this->createMock(IBackend::class);
+ $this->logger = $this->createMock(LoggerInterface::class);
$this->limiter = new Limiter(
- $this->backend
+ $this->backend,
+ $this->logger,
);
}
public function testRegisterAnonRequestExceeded(): void {
- $this->expectException(\OC\Security\RateLimiting\Exception\RateLimitExceededException::class);
+ $this->expectException(RateLimitExceededException::class);
$this->expectExceptionMessage('Rate limit exceeded');
$this->backend
@@ -43,6 +49,8 @@ class LimiterTest extends TestCase {
'4664f0d9c88dcb7552be47b37bb52ce35977b2e60e1ac13757cf625f31f87050a41f3da064887fa87d49fd042e4c8eb20de8f10464877d3959677ab011b73a47'
)
->willReturn(101);
+ $this->logger->expects($this->once())
+ ->method('info');
$this->limiter->registerAnonRequest('MyIdentifier', 100, 100, '127.0.0.1');
}
@@ -64,13 +72,15 @@ class LimiterTest extends TestCase {
'4664f0d9c88dcb7552be47b37bb52ce35977b2e60e1ac13757cf625f31f87050a41f3da064887fa87d49fd042e4c8eb20de8f10464877d3959677ab011b73a47',
100
);
+ $this->logger->expects($this->never())
+ ->method('info');
$this->limiter->registerAnonRequest('MyIdentifier', 100, 100, '127.0.0.1');
}
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 */
@@ -87,6 +97,8 @@ class LimiterTest extends TestCase {
'ddb2ec50fa973fd49ecf3d816f677c8095143e944ad10485f30fb3dac85c13a346dace4dae2d0a15af91867320957bfd38a43d9eefbb74fe6919e15119b6d805'
)
->willReturn(101);
+ $this->logger->expects($this->once())
+ ->method('info');
$this->limiter->registerUserRequest('MyIdentifier', 100, 100, $user);
}
@@ -115,6 +127,8 @@ class LimiterTest extends TestCase {
'ddb2ec50fa973fd49ecf3d816f677c8095143e944ad10485f30fb3dac85c13a346dace4dae2d0a15af91867320957bfd38a43d9eefbb74fe6919e15119b6d805',
100
);
+ $this->logger->expects($this->never())
+ ->method('info');
$this->limiter->registerUserRequest('MyIdentifier', 100, 100, $user);
}
diff --git a/tests/lib/Security/RemoteHostValidatorIntegrationTest.php b/tests/lib/Security/RemoteHostValidatorIntegrationTest.php
index 6cddb8b4ce9..913acfa054d 100644
--- a/tests/lib/Security/RemoteHostValidatorIntegrationTest.php
+++ b/tests/lib/Security/RemoteHostValidatorIntegrationTest.php
@@ -37,7 +37,7 @@ class RemoteHostValidatorIntegrationTest extends TestCase {
);
}
- public function localHostsData(): array {
+ public static function localHostsData(): array {
return [
['[::1]'],
['[::]'],
@@ -73,9 +73,7 @@ class RemoteHostValidatorIntegrationTest extends TestCase {
];
}
- /**
- * @dataProvider localHostsData
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('localHostsData')]
public function testLocalHostsWhenNotAllowed(string $host): void {
$this->config
->method('getSystemValueBool')
@@ -87,9 +85,7 @@ class RemoteHostValidatorIntegrationTest extends TestCase {
self::assertFalse($isValid);
}
- /**
- * @dataProvider localHostsData
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('localHostsData')]
public function testLocalHostsWhenAllowed(string $host): void {
$this->config
->method('getSystemValueBool')
@@ -101,7 +97,7 @@ class RemoteHostValidatorIntegrationTest extends TestCase {
self::assertTrue($isValid);
}
- public function externalAddressesData():array {
+ public static function externalAddressesData():array {
return [
['8.8.8.8'],
['8.8.4.4'],
@@ -111,9 +107,7 @@ class RemoteHostValidatorIntegrationTest extends TestCase {
];
}
- /**
- * @dataProvider externalAddressesData
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('externalAddressesData')]
public function testExternalHost(string $host): void {
$this->config
->method('getSystemValueBool')
diff --git a/tests/lib/Security/RemoteHostValidatorTest.php b/tests/lib/Security/RemoteHostValidatorTest.php
index c698ebbc3c6..b048b9dafd1 100644
--- a/tests/lib/Security/RemoteHostValidatorTest.php
+++ b/tests/lib/Security/RemoteHostValidatorTest.php
@@ -44,16 +44,14 @@ class RemoteHostValidatorTest extends TestCase {
);
}
- public function dataValid(): array {
+ public static function dataValid(): array {
return [
['nextcloud.com', true],
['com.one-.nextcloud-one.com', false],
];
}
- /**
- * @dataProvider dataValid
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataValid')]
public function testValid(string $host, bool $expected): void {
$this->hostnameClassifier
->method('isLocalHostname')
diff --git a/tests/lib/Security/SecureRandomTest.php b/tests/lib/Security/SecureRandomTest.php
index 8000917579b..954fd85eaf1 100644
--- a/tests/lib/Security/SecureRandomTest.php
+++ b/tests/lib/Security/SecureRandomTest.php
@@ -13,7 +13,7 @@ namespace Test\Security;
use OC\Security\SecureRandom;
class SecureRandomTest extends \Test\TestCase {
- public function stringGenerationProvider() {
+ public static function stringGenerationProvider(): array {
return [
[1, 1],
[128, 128],
@@ -24,7 +24,7 @@ class SecureRandomTest extends \Test\TestCase {
];
}
- public static function charCombinations() {
+ public static function charCombinations(): array {
return [
['CHAR_LOWER', '[a-z]'],
['CHAR_UPPER', '[A-Z]'],
@@ -37,37 +37,29 @@ class SecureRandomTest extends \Test\TestCase {
protected function setUp(): void {
parent::setUp();
- $this->rng = new \OC\Security\SecureRandom();
+ $this->rng = new SecureRandom();
}
- /**
- * @dataProvider stringGenerationProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('stringGenerationProvider')]
public function testGetLowStrengthGeneratorLength($length, $expectedLength): void {
$generator = $this->rng;
$this->assertEquals($expectedLength, strlen($generator->generate($length)));
}
- /**
- * @dataProvider stringGenerationProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('stringGenerationProvider')]
public function testMediumLowStrengthGeneratorLength($length, $expectedLength): void {
$generator = $this->rng;
$this->assertEquals($expectedLength, strlen($generator->generate($length)));
}
- /**
- * @dataProvider stringGenerationProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('stringGenerationProvider')]
public function testUninitializedGenerate($length, $expectedLength): void {
$this->assertEquals($expectedLength, strlen($this->rng->generate($length)));
}
- /**
- * @dataProvider charCombinations
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('charCombinations')]
public function testScheme($charName, $chars): void {
$generator = $this->rng;
$scheme = constant('OCP\Security\ISecureRandom::' . $charName);
@@ -76,16 +68,14 @@ class SecureRandomTest extends \Test\TestCase {
$this->assertSame(1, $matchesRegex);
}
- public static function invalidLengths() {
+ public static function invalidLengths(): array {
return [
[0],
[-1],
];
}
- /**
- * @dataProvider invalidLengths
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('invalidLengths')]
public function testInvalidLengths($length): void {
$this->expectException(\LengthException::class);
$generator = $this->rng;
diff --git a/tests/lib/Security/TrustedDomainHelperTest.php b/tests/lib/Security/TrustedDomainHelperTest.php
index 656b7a77206..8b671a93d06 100644
--- a/tests/lib/Security/TrustedDomainHelperTest.php
+++ b/tests/lib/Security/TrustedDomainHelperTest.php
@@ -27,11 +27,11 @@ class TrustedDomainHelperTest extends \Test\TestCase {
}
/**
- * @dataProvider trustedDomainDataProvider
* @param string $trustedDomains
* @param string $testDomain
* @param bool $result
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('trustedDomainDataProvider')]
public function testIsTrustedUrl($trustedDomains, $testDomain, $result): void {
$this->config->method('getSystemValue')
->willReturnMap([
@@ -44,11 +44,11 @@ class TrustedDomainHelperTest extends \Test\TestCase {
}
/**
- * @dataProvider trustedDomainDataProvider
* @param string $trustedDomains
* @param string $testDomain
* @param bool $result
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('trustedDomainDataProvider')]
public function testIsTrustedDomain($trustedDomains, $testDomain, $result): void {
$this->config->method('getSystemValue')
->willReturnMap([
@@ -63,7 +63,7 @@ class TrustedDomainHelperTest extends \Test\TestCase {
/**
* @return array
*/
- public function trustedDomainDataProvider() {
+ public static function trustedDomainDataProvider(): array {
$trustedHostTestList = [
'host.one.test',
'host.two.test',
diff --git a/tests/lib/ServerTest.php b/tests/lib/ServerTest.php
index eb9b1dab9f5..b070641e856 100644
--- a/tests/lib/ServerTest.php
+++ b/tests/lib/ServerTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -8,6 +9,8 @@
namespace Test;
use OC\App\AppStore\Fetcher\AppFetcher;
+use OC\Config;
+use OC\Server;
use OCP\Comments\ICommentsManager;
/**
@@ -18,17 +21,17 @@ use OCP\Comments\ICommentsManager;
* @package Test
*/
class ServerTest extends \Test\TestCase {
- /** @var \OC\Server */
+ /** @var Server */
protected $server;
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 function dataTestQuery() {
+ public static function dataTestQuery(): array {
return [
['\OCP\Activity\IManager', '\OC\Activity\Manager'],
['\OCP\IConfig', '\OC\AllConfig'],
@@ -41,11 +44,11 @@ class ServerTest extends \Test\TestCase {
}
/**
- * @dataProvider dataTestQuery
*
* @param string $serviceName
* @param string $instanceOf
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataTestQuery')]
public function testQuery($serviceName, $instanceOf): void {
$this->assertInstanceOf($instanceOf, $this->server->query($serviceName), 'Service "' . $serviceName . '"" did not return the right class');
}
diff --git a/tests/lib/Session/CryptoSessionDataTest.php b/tests/lib/Session/CryptoSessionDataTest.php
index 6c1536f4769..a30a3297094 100644
--- a/tests/lib/Session/CryptoSessionDataTest.php
+++ b/tests/lib/Session/CryptoSessionDataTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -8,19 +9,21 @@
namespace Test\Session;
use OC\Session\CryptoSessionData;
+use OC\Session\Memory;
+use OCP\ISession;
use OCP\Security\ICrypto;
class CryptoSessionDataTest extends Session {
- /** @var \PHPUnit\Framework\MockObject\MockObject|\OCP\Security\ICrypto */
+ /** @var \PHPUnit\Framework\MockObject\MockObject|ICrypto */
protected $crypto;
- /** @var \OCP\ISession */
+ /** @var ISession */
protected $wrappedSession;
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/CryptoWrappingTest.php b/tests/lib/Session/CryptoWrappingTest.php
index 8afbf61bddc..2bc09e0903a 100644
--- a/tests/lib/Session/CryptoWrappingTest.php
+++ b/tests/lib/Session/CryptoWrappingTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2017-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -9,13 +10,14 @@ namespace Test\Session;
use OC\Session\CryptoSessionData;
use OCP\ISession;
+use OCP\Security\ICrypto;
use Test\TestCase;
class CryptoWrappingTest extends TestCase {
- /** @var \PHPUnit\Framework\MockObject\MockObject|\OCP\Security\ICrypto */
+ /** @var \PHPUnit\Framework\MockObject\MockObject|ICrypto */
protected $crypto;
- /** @var \PHPUnit\Framework\MockObject\MockObject|\OCP\ISession */
+ /** @var \PHPUnit\Framework\MockObject\MockObject|ISession */
protected $wrappedSession;
/** @var \OC\Session\CryptoSessionData */
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/DeclarativeManagerTest.php b/tests/lib/Settings/DeclarativeManagerTest.php
index 522264acd8c..59411e1f825 100644
--- a/tests/lib/Settings/DeclarativeManagerTest.php
+++ b/tests/lib/Settings/DeclarativeManagerTest.php
@@ -18,6 +18,7 @@ use OCP\IAppConfig;
use OCP\IConfig;
use OCP\IGroupManager;
use OCP\IUser;
+use OCP\Security\ICrypto;
use OCP\Settings\DeclarativeSettingsTypes;
use OCP\Settings\Events\DeclarativeSettingsSetValueEvent;
use OCP\Settings\IDeclarativeManager;
@@ -50,6 +51,9 @@ class DeclarativeManagerTest extends TestCase {
/** @var LoggerInterface|MockObject */
private $logger;
+ /** @var ICrypto|MockObject */
+ private $crypto;
+
/** @var IUser|MockObject */
private $user;
@@ -215,6 +219,36 @@ class DeclarativeManagerTest extends TestCase {
],
],
],
+ [
+ 'id' => 'test_sensitive_field',
+ 'title' => 'Sensitive text field',
+ 'description' => 'Set some secure value setting that is stored encrypted',
+ 'type' => DeclarativeSettingsTypes::TEXT,
+ 'label' => 'Sensitive field',
+ 'placeholder' => 'Set secure value',
+ 'default' => '',
+ 'sensitive' => true, // only for TEXT, PASSWORD types
+ ],
+ [
+ 'id' => 'test_sensitive_field_2',
+ 'title' => 'Sensitive password field',
+ 'description' => 'Set some password setting that is stored encrypted',
+ 'type' => DeclarativeSettingsTypes::PASSWORD,
+ 'label' => 'Sensitive field',
+ 'placeholder' => 'Set secure value',
+ 'default' => '',
+ 'sensitive' => true, // only for TEXT, PASSWORD types
+ ],
+ [
+ 'id' => 'test_non_sensitive_field',
+ 'title' => 'Password field',
+ 'description' => 'Set some password setting',
+ 'type' => DeclarativeSettingsTypes::PASSWORD,
+ 'label' => 'Password field',
+ 'placeholder' => 'Set secure value',
+ 'default' => '',
+ 'sensitive' => false,
+ ],
],
];
@@ -229,6 +263,7 @@ class DeclarativeManagerTest extends TestCase {
$this->config = $this->createMock(IConfig::class);
$this->appConfig = $this->createMock(IAppConfig::class);
$this->logger = $this->createMock(LoggerInterface::class);
+ $this->crypto = $this->createMock(ICrypto::class);
$this->declarativeManager = new DeclarativeManager(
$this->eventDispatcher,
@@ -236,7 +271,8 @@ class DeclarativeManagerTest extends TestCase {
$this->coordinator,
$this->config,
$this->appConfig,
- $this->logger
+ $this->logger,
+ $this->crypto,
);
$this->user = $this->createMock(IUser::class);
@@ -309,9 +345,7 @@ class DeclarativeManagerTest extends TestCase {
$this->assertFalse(isset($formIds[$app]) && in_array($schemaDuplicateFields['id'], $formIds[$app]));
}
- /**
- * @dataProvider dataValidateSchema
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataValidateSchema')]
public function testValidateSchema(bool $expected, bool $expectException, string $app, array $schema): void {
if ($expectException) {
$this->expectException(\Exception::class);
diff --git a/tests/lib/Settings/ManagerTest.php b/tests/lib/Settings/ManagerTest.php
index 38b0262bb55..91277cc7f1e 100644
--- a/tests/lib/Settings/ManagerTest.php
+++ b/tests/lib/Settings/ManagerTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
@@ -8,6 +9,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 +17,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 +68,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 +81,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 +205,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/Settings/SectionTest.php b/tests/lib/Settings/SectionTest.php
index dd69f8ae110..ecd654ba748 100644
--- a/tests/lib/Settings/SectionTest.php
+++ b/tests/lib/Settings/SectionTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
diff --git a/tests/lib/SetupCheck/CheckServerResponseTraitTest.php b/tests/lib/SetupCheck/CheckServerResponseTraitTest.php
index 32fbce64ce6..3f7b498bfeb 100644
--- a/tests/lib/SetupCheck/CheckServerResponseTraitTest.php
+++ b/tests/lib/SetupCheck/CheckServerResponseTraitTest.php
@@ -19,7 +19,7 @@ use Test\TestCase;
class CheckServerResponseTraitTest extends TestCase {
protected const BASE_URL = 'https://nextcloud.local';
-
+
private IL10N&MockObject $l10n;
private IConfig&MockObject $config;
private IURLGenerator&MockObject $urlGenerator;
@@ -38,7 +38,7 @@ class CheckServerResponseTraitTest extends TestCase {
$this->urlGenerator = $this->createMock(IURLGenerator::class);
$this->clientService = $this->createMock(IClientService::class);
$this->logger = $this->createMock(LoggerInterface::class);
-
+
$this->trait = new CheckServerResponseTraitImplementation(
$this->l10n,
$this->config,
@@ -48,9 +48,7 @@ class CheckServerResponseTraitTest extends TestCase {
);
}
- /**
- * @dataProvider dataNormalizeUrl
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataNormalizeUrl')]
public function testNormalizeUrl(string $url, bool $isRootRequest, string $expected): void {
$this->assertEquals($expected, $this->trait->normalizeUrl($url, $isRootRequest));
}
@@ -75,9 +73,7 @@ class CheckServerResponseTraitTest extends TestCase {
];
}
- /**
- * @dataProvider dataGetTestUrls
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataGetTestUrls')]
public function testGetTestUrls(
string $url,
bool $isRootRequest,
@@ -103,7 +99,7 @@ class CheckServerResponseTraitTest extends TestCase {
$this->urlGenerator->expects(self::atLeastOnce())
->method('getBaseUrl')
->willReturn(self::BASE_URL . $webRoot);
-
+
$result = $this->trait->getTestUrls($url, $isRootRequest);
$this->assertEquals($expected, $result);
}
diff --git a/tests/lib/SetupTest.php b/tests/lib/SetupTest.php
index b5e1b7000c3..0be7eab36f6 100644
--- a/tests/lib/SetupTest.php
+++ b/tests/lib/SetupTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -42,7 +43,7 @@ class SetupTest extends \Test\TestCase {
$this->random = $this->createMock(ISecureRandom::class);
$this->installer = $this->createMock(Installer::class);
$this->setupClass = $this->getMockBuilder(Setup::class)
- ->setMethods(['class_exists', 'is_callable', 'getAvailableDbDriversForPdo'])
+ ->onlyMethods(['class_exists', 'is_callable', 'getAvailableDbDriversForPdo'])
->setConstructorArgs([$this->config, $this->iniWrapper, $this->l10nFactory, $this->defaults, $this->logger, $this->random, $this->installer])
->getMock();
}
@@ -128,10 +129,10 @@ class SetupTest extends \Test\TestCase {
}
/**
- * @dataProvider findWebRootProvider
* @param $url
* @param $expected
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('findWebRootProvider')]
public function testFindWebRootCli($url, $expected): void {
$cliState = \OC::$CLI;
@@ -151,7 +152,7 @@ class SetupTest extends \Test\TestCase {
$this->assertSame($webRoot, $expected);
}
- public function findWebRootProvider(): array {
+ public static function findWebRootProvider(): array {
return [
'https://www.example.com/nextcloud/' => ['https://www.example.com/nextcloud/', '/nextcloud'],
'https://www.example.com/nextcloud' => ['https://www.example.com/nextcloud', '/nextcloud'],
diff --git a/tests/lib/Share/Backend.php b/tests/lib/Share/Backend.php
index 489f4a9bfd1..94ac25111c2 100644
--- a/tests/lib/Share/Backend.php
+++ b/tests/lib/Share/Backend.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2017-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -10,8 +11,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 c923bb0480a..3438f108749 100644
--- a/tests/lib/Share/HelperTest.php
+++ b/tests/lib/Share/HelperTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -7,12 +8,14 @@
namespace Test\Share;
+use OC\Share\Helper;
+
/**
* @group DB
* Class Helper
*/
class HelperTest extends \Test\TestCase {
- public function expireDateProvider() {
+ public static function expireDateProvider(): array {
return [
// no default expire date, we take the users expire date
[['defaultExpireDateSet' => false], 2000000000, 2000010000, 2000010000],
@@ -33,28 +36,26 @@ class HelperTest extends \Test\TestCase {
];
}
- /**
- * @dataProvider expireDateProvider
- */
+ #[\PHPUnit\Framework\Attributes\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);
}
/**
- * @dataProvider dataTestCompareServerAddresses
*
* @param string $server1
* @param string $server2
* @param bool $expected
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataTestCompareServerAddresses')]
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)
);
}
- public function dataTestCompareServerAddresses() {
+ public static function dataTestCompareServerAddresses(): array {
return [
['user1', 'http://server1', 'user1', 'http://server1', true],
['user1', 'https://server1', 'user1', 'http://server1', true],
diff --git a/tests/lib/Share/ShareTest.php b/tests/lib/Share/ShareTest.php
index 60891e10ca2..9690d242067 100644
--- a/tests/lib/Share/ShareTest.php
+++ b/tests/lib/Share/ShareTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -8,11 +9,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 +50,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 +71,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 +83,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 +98,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();
@@ -122,17 +127,17 @@ class ShareTest extends \Test\TestCase {
}
/**
- * @dataProvider urls
* @param string $url
* @param string $expectedResult
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('urls')]
public function testRemoveProtocolFromUrl($url, $expectedResult): void {
$share = new Share();
$result = self::invokePrivate($share, 'removeProtocolFromUrl', [$url]);
$this->assertSame($expectedResult, $result);
}
- public function urls() {
+ public static function urls(): array {
return [
['http://owncloud.org', 'owncloud.org'],
['https://owncloud.org', 'owncloud.org'],
@@ -141,10 +146,10 @@ class ShareTest extends \Test\TestCase {
}
/**
- * @dataProvider dataProviderTestGroupItems
* @param array $ungrouped
* @param array $grouped
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataProviderTestGroupItems')]
public function testGroupItems($ungrouped, $grouped): void {
$result = DummyShareClass::groupItemsTest($ungrouped);
@@ -161,25 +166,25 @@ class ShareTest extends \Test\TestCase {
}
}
- public function dataProviderTestGroupItems() {
+ public static function dataProviderTestGroupItems(): array {
return [
// 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 +192,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 75a70d558c1..eaf17fa1a26 100644
--- a/tests/lib/Share20/DefaultShareProviderTest.php
+++ b/tests/lib/Share20/DefaultShareProviderTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -9,8 +10,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 +29,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 +82,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 +183,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);
}
@@ -472,7 +478,7 @@ class DefaultShareProviderTest extends \Test\TestCase {
$this->logger,
$this->shareManager,
])
- ->setMethods(['getShareById'])
+ ->onlyMethods(['getShareById'])
->getMock();
$provider->delete($share);
@@ -569,7 +575,7 @@ class DefaultShareProviderTest extends \Test\TestCase {
$this->logger,
$this->shareManager,
])
- ->setMethods(['getShareById'])
+ ->onlyMethods(['getShareById'])
->getMock();
$provider->delete($share);
@@ -674,7 +680,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 +752,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 +822,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 +946,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');
}
@@ -968,7 +974,7 @@ class DefaultShareProviderTest extends \Test\TestCase {
return $qb->getLastInsertId();
}
- public function storageAndFileNameProvider() {
+ public static function storageAndFileNameProvider(): array {
return [
// regular file on regular storage
['home::shareOwner', 'files/test.txt', 'files/test2.txt'],
@@ -979,9 +985,7 @@ class DefaultShareProviderTest extends \Test\TestCase {
];
}
- /**
- * @dataProvider storageAndFileNameProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('storageAndFileNameProvider')]
public function testGetSharedWithUser($storageStringId, $fileName1, $fileName2): void {
$storageId = $this->createTestStorageEntry($storageStringId);
$fileId = $this->createTestFileEntry($fileName1, $storageId);
@@ -1030,9 +1034,7 @@ class DefaultShareProviderTest extends \Test\TestCase {
$this->assertEquals(IShare::TYPE_USER, $share->getShareType());
}
- /**
- * @dataProvider storageAndFileNameProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('storageAndFileNameProvider')]
public function testGetSharedWithGroup($storageStringId, $fileName1, $fileName2): void {
$storageId = $this->createTestStorageEntry($storageStringId);
$fileId = $this->createTestFileEntry($fileName1, $storageId);
@@ -1104,9 +1106,7 @@ class DefaultShareProviderTest extends \Test\TestCase {
$this->assertEquals(IShare::TYPE_GROUP, $share->getShareType());
}
- /**
- * @dataProvider storageAndFileNameProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('storageAndFileNameProvider')]
public function testGetSharedWithGroupUserModified($storageStringId, $fileName1, $fileName2): void {
$storageId = $this->createTestStorageEntry($storageStringId);
$fileId = $this->createTestFileEntry($fileName1, $storageId);
@@ -1196,9 +1196,7 @@ class DefaultShareProviderTest extends \Test\TestCase {
$this->assertSame('userTarget', $share->getTarget());
}
- /**
- * @dataProvider storageAndFileNameProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('storageAndFileNameProvider')]
public function testGetSharedWithUserWithNode($storageStringId, $fileName1, $fileName2): void {
$storageId = $this->createTestStorageEntry($storageStringId);
$fileId = $this->createTestFileEntry($fileName1, $storageId);
@@ -1238,9 +1236,7 @@ class DefaultShareProviderTest extends \Test\TestCase {
$this->assertEquals(IShare::TYPE_USER, $share->getShareType());
}
- /**
- * @dataProvider storageAndFileNameProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('storageAndFileNameProvider')]
public function testGetSharedWithGroupWithNode($storageStringId, $fileName1, $fileName2): void {
$storageId = $this->createTestStorageEntry($storageStringId);
$fileId = $this->createTestFileEntry($fileName1, $storageId);
@@ -1281,7 +1277,7 @@ class DefaultShareProviderTest extends \Test\TestCase {
$this->assertEquals(IShare::TYPE_GROUP, $share->getShareType());
}
- public function shareTypesProvider() {
+ public static function shareTypesProvider(): array {
return [
[IShare::TYPE_USER, false],
[IShare::TYPE_GROUP, false],
@@ -1290,9 +1286,7 @@ class DefaultShareProviderTest extends \Test\TestCase {
];
}
- /**
- * @dataProvider shareTypesProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('shareTypesProvider')]
public function testGetSharedWithWithDeletedFile($shareType, $trashed): void {
if ($trashed) {
// exists in database but is in trash
@@ -1679,7 +1673,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 +1764,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 +1807,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();
@@ -2276,7 +2270,7 @@ class DefaultShareProviderTest extends \Test\TestCase {
$this->assertSame('/ultraNewTarget', $share->getTarget());
}
- public function dataDeleteUser() {
+ public static function dataDeleteUser(): array {
return [
[IShare::TYPE_USER, 'a', 'b', 'c', 'a', true],
[IShare::TYPE_USER, 'a', 'b', 'c', 'b', false],
@@ -2296,7 +2290,6 @@ class DefaultShareProviderTest extends \Test\TestCase {
}
/**
- * @dataProvider dataDeleteUser
*
* @param int $type The shareType (user/group/link)
* @param string $owner The owner of the share (uid)
@@ -2305,6 +2298,7 @@ class DefaultShareProviderTest extends \Test\TestCase {
* @param string $deletedUser The user that is deleted
* @param bool $rowDeleted Is the row deleted in this setup
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataDeleteUser')]
public function testDeleteUser($type, $owner, $initiator, $recipient, $deletedUser, $rowDeleted): void {
$qb = $this->dbConn->getQueryBuilder();
$qb->insert('share')
@@ -2334,7 +2328,7 @@ class DefaultShareProviderTest extends \Test\TestCase {
$this->assertCount($rowDeleted ? 0 : 1, $data);
}
- public function dataDeleteUserGroup() {
+ public static function dataDeleteUserGroup(): array {
return [
['a', 'b', 'c', 'a', true, true],
['a', 'b', 'c', 'b', false, false],
@@ -2344,7 +2338,6 @@ class DefaultShareProviderTest extends \Test\TestCase {
}
/**
- * @dataProvider dataDeleteUserGroup
*
* @param string $owner The owner of the share (uid)
* @param string $initiator The initiator of the share (uid)
@@ -2353,6 +2346,7 @@ class DefaultShareProviderTest extends \Test\TestCase {
* @param bool $groupShareDeleted
* @param bool $userGroupShareDeleted
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataDeleteUserGroup')]
public function testDeleteUserGroup($owner, $initiator, $recipient, $deletedUser, $groupShareDeleted, $userGroupShareDeleted): void {
$qb = $this->dbConn->getQueryBuilder();
$qb->insert('share')
@@ -2403,7 +2397,7 @@ class DefaultShareProviderTest extends \Test\TestCase {
$this->assertCount($groupShareDeleted ? 0 : 1, $data);
}
- public function dataGroupDeleted() {
+ public static function dataGroupDeleted(): array {
return [
[
[
@@ -2450,12 +2444,12 @@ class DefaultShareProviderTest extends \Test\TestCase {
}
/**
- * @dataProvider dataGroupDeleted
*
* @param $shares
* @param $groupToDelete
* @param $shouldBeDeleted
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataGroupDeleted')]
public function testGroupDeleted($shares, $groupToDelete, $shouldBeDeleted): void {
$qb = $this->dbConn->getQueryBuilder();
$qb->insert('share')
@@ -2497,7 +2491,7 @@ class DefaultShareProviderTest extends \Test\TestCase {
$this->assertCount($shouldBeDeleted ? 0 : count($ids), $data);
}
- public function dataUserDeletedFromGroup() {
+ public static function dataUserDeletedFromGroup(): array {
return [
['group1', 'user1', true],
['group1', 'user2', false],
@@ -2510,12 +2504,12 @@ class DefaultShareProviderTest extends \Test\TestCase {
* And a user specific group share with 'user1'.
* User $user is deleted from group $gid.
*
- * @dataProvider dataUserDeletedFromGroup
*
* @param string $group
* @param string $user
* @param bool $toDelete
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataUserDeletedFromGroup')]
public function testUserDeletedFromGroup($group, $user, $toDelete): void {
$qb = $this->dbConn->getQueryBuilder();
$qb->insert('share')
@@ -2556,9 +2550,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 +2581,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 +2597,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 +2605,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 +2614,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 +2650,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 +2687,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 +2704,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 +2717,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 +2726,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 +2753,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 +2790,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 +2807,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 +2819,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 +2828,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 0761eed592b..2ce72b3fc1c 100644
--- a/tests/lib/Share20/LegacyHooksTest.php
+++ b/tests/lib/Share20/LegacyHooksTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2017 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
@@ -6,6 +7,7 @@
namespace Test\Share20;
+use OC\EventDispatcher\EventDispatcher;
use OC\Share20\LegacyHooks;
use OC\Share20\Manager;
use OCP\Constants;
@@ -13,6 +15,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,9 +23,23 @@ 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;
+class Dummy {
+ public function postShare() {
+ }
+ public function preShare() {
+ }
+ public function postFromSelf() {
+ }
+ public function post() {
+ }
+ public function pre() {
+ }
+}
+
class LegacyHooksTest extends TestCase {
/** @var LegacyHooks */
private $hooks;
@@ -38,9 +55,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 {
@@ -60,8 +77,8 @@ class LegacyHooksTest extends TestCase {
->setTarget('myTarget')
->setNodeCacheEntry($info);
- $hookListner = $this->getMockBuilder('Dummy')->setMethods(['pre'])->getMock();
- \OCP\Util::connectHook('OCP\Share', 'pre_unshare', $hookListner, 'pre');
+ $hookListner = $this->getMockBuilder(Dummy::class)->onlyMethods(['pre'])->getMock();
+ Util::connectHook('OCP\Share', 'pre_unshare', $hookListner, 'pre');
$hookListnerExpectsPre = [
'id' => 42,
@@ -101,8 +118,8 @@ class LegacyHooksTest extends TestCase {
->setTarget('myTarget')
->setNodeCacheEntry($info);
- $hookListner = $this->getMockBuilder('Dummy')->setMethods(['post'])->getMock();
- \OCP\Util::connectHook('OCP\Share', 'post_unshare', $hookListner, 'post');
+ $hookListner = $this->getMockBuilder(Dummy::class)->onlyMethods(['post'])->getMock();
+ Util::connectHook('OCP\Share', 'post_unshare', $hookListner, 'post');
$hookListnerExpectsPost = [
'id' => 42,
@@ -155,8 +172,8 @@ class LegacyHooksTest extends TestCase {
->setTarget('myTarget')
->setNodeCacheEntry($info);
- $hookListner = $this->getMockBuilder('Dummy')->setMethods(['postFromSelf'])->getMock();
- \OCP\Util::connectHook('OCP\Share', 'post_unshareFromSelf', $hookListner, 'postFromSelf');
+ $hookListner = $this->getMockBuilder(Dummy::class)->onlyMethods(['postFromSelf'])->getMock();
+ Util::connectHook('OCP\Share', 'post_unshareFromSelf', $hookListner, 'postFromSelf');
$hookListnerExpectsPostFromSelf = [
'id' => 42,
@@ -212,8 +229,8 @@ class LegacyHooksTest extends TestCase {
->setToken('token');
- $hookListner = $this->getMockBuilder('Dummy')->setMethods(['preShare'])->getMock();
- \OCP\Util::connectHook('OCP\Share', 'pre_shared', $hookListner, 'preShare');
+ $hookListner = $this->getMockBuilder(Dummy::class)->onlyMethods(['preShare'])->getMock();
+ Util::connectHook('OCP\Share', 'pre_shared', $hookListner, 'preShare');
$run = true;
$error = '';
@@ -260,8 +277,8 @@ class LegacyHooksTest extends TestCase {
->setToken('token');
- $hookListner = $this->getMockBuilder('Dummy')->setMethods(['preShare'])->getMock();
- \OCP\Util::connectHook('OCP\Share', 'pre_shared', $hookListner, 'preShare');
+ $hookListner = $this->getMockBuilder(Dummy::class)->onlyMethods(['preShare'])->getMock();
+ Util::connectHook('OCP\Share', 'pre_shared', $hookListner, 'preShare');
$run = true;
$error = '';
@@ -285,7 +302,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';
});
@@ -316,8 +333,8 @@ class LegacyHooksTest extends TestCase {
->setToken('token');
- $hookListner = $this->getMockBuilder('Dummy')->setMethods(['postShare'])->getMock();
- \OCP\Util::connectHook('OCP\Share', 'post_shared', $hookListner, 'postShare');
+ $hookListner = $this->getMockBuilder(Dummy::class)->onlyMethods(['postShare'])->getMock();
+ 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 9e778207a8e..7859407651f 100644
--- a/tests/lib/Share20/ManagerTest.php
+++ b/tests/lib/Share20/ManagerTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -12,10 +13,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;
@@ -55,6 +57,8 @@ use OCP\Share\IManager;
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;
@@ -241,9 +245,7 @@ class ManagerTest extends \Test\TestCase {
];
}
- /**
- * @dataProvider dataTestDelete
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataTestDelete')]
public function testDelete($shareType, $sharedWith): void {
$manager = $this->createManagerMock()
->onlyMethods(['getShareById', 'deleteChildren', 'promoteReshares'])
@@ -277,7 +279,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());
@@ -320,7 +322,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());
@@ -380,7 +382,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);
});
@@ -395,7 +397,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());
@@ -475,7 +477,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);
});
@@ -572,7 +574,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);
});
@@ -666,7 +668,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);
});
@@ -688,7 +690,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'])
@@ -773,7 +775,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());
@@ -795,7 +797,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());
@@ -890,7 +892,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');
@@ -914,10 +916,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');
@@ -932,7 +934,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];
@@ -941,7 +943,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);
@@ -949,13 +951,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);
@@ -982,7 +984,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);
@@ -996,12 +998,12 @@ class ManagerTest extends \Test\TestCase {
}
/**
- * @dataProvider dataGeneralChecks
*
* @param $share
* @param $exceptionMessage
* @param $exception
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataGeneralChecks')]
public function testGeneralChecks($share, $exceptionMessage, $exception): void {
$thrown = null;
@@ -1031,7 +1033,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) {
@@ -1072,11 +1074,9 @@ class ManagerTest extends \Test\TestCase {
return [[IShare::TYPE_USER], [IShare::TYPE_REMOTE], [IShare::TYPE_REMOTE_GROUP]];
}
- /**
- * @dataProvider validateExpirationDateInternalProvider
- */
+ #[\PHPUnit\Framework\Attributes\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
@@ -1090,9 +1090,7 @@ class ManagerTest extends \Test\TestCase {
self::invokePrivate($this->manager, 'validateExpirationDateInternal', [$share]);
}
- /**
- * @dataProvider validateExpirationDateInternalProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('validateExpirationDateInternalProvider')]
public function testValidateExpirationDateInternalEnforceButNotSet($shareType): void {
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage('Expiration date is enforced');
@@ -1117,9 +1115,7 @@ class ManagerTest extends \Test\TestCase {
self::invokePrivate($this->manager, 'validateExpirationDateInternal', [$share]);
}
- /**
- * @dataProvider validateExpirationDateInternalProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('validateExpirationDateInternalProvider')]
public function testValidateExpirationDateInternalEnforceButNotEnabledAndNotSet($shareType): void {
$share = $this->manager->newShare();
$share->setProviderId('foo')->setId('bar');
@@ -1142,9 +1138,7 @@ class ManagerTest extends \Test\TestCase {
$this->assertNull($share->getExpirationDate());
}
- /**
- * @dataProvider validateExpirationDateInternalProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('validateExpirationDateInternalProvider')]
public function testValidateExpirationDateInternalEnforceButNotSetNewShare($shareType): void {
$share = $this->manager->newShare();
$share->setShareType($shareType);
@@ -1177,9 +1171,7 @@ class ManagerTest extends \Test\TestCase {
$this->assertEquals($expected, $share->getExpirationDate());
}
- /**
- * @dataProvider validateExpirationDateInternalProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('validateExpirationDateInternalProvider')]
public function testValidateExpirationDateInternalEnforceRelaxedDefaultButNotSetNewShare($shareType): void {
$share = $this->manager->newShare();
$share->setShareType($shareType);
@@ -1212,11 +1204,9 @@ class ManagerTest extends \Test\TestCase {
$this->assertEquals($expected, $share->getExpirationDate());
}
- /**
- * @dataProvider validateExpirationDateInternalProvider
- */
+ #[\PHPUnit\Framework\Attributes\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();
@@ -1245,9 +1235,7 @@ class ManagerTest extends \Test\TestCase {
self::invokePrivate($this->manager, 'validateExpirationDateInternal', [$share]);
}
- /**
- * @dataProvider validateExpirationDateInternalProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('validateExpirationDateInternalProvider')]
public function testValidateExpirationDateInternalEnforceValid($shareType): void {
$future = new \DateTime('now', $this->dateTimeZone->getTimeZone());
$future->add(new \DateInterval('P2D'));
@@ -1277,7 +1265,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;
}));
@@ -1287,9 +1275,7 @@ class ManagerTest extends \Test\TestCase {
$this->assertEquals($expected, $share->getExpirationDate());
}
- /**
- * @dataProvider validateExpirationDateInternalProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('validateExpirationDateInternalProvider')]
public function testValidateExpirationDateInternalNoDefault($shareType): void {
$date = new \DateTime('now', $this->dateTimeZone->getTimeZone());
$date->add(new \DateInterval('P5D'));
@@ -1303,7 +1289,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;
}));
@@ -1313,12 +1299,10 @@ class ManagerTest extends \Test\TestCase {
$this->assertEquals($expected, $share->getExpirationDate());
}
- /**
- * @dataProvider validateExpirationDateInternalProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('validateExpirationDateInternalProvider')]
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;
}));
@@ -1332,9 +1316,7 @@ class ManagerTest extends \Test\TestCase {
$this->assertNull($share->getExpirationDate());
}
- /**
- * @dataProvider validateExpirationDateInternalProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('validateExpirationDateInternalProvider')]
public function testValidateExpirationDateInternalNoDateDefault($shareType): void {
$share = $this->manager->newShare();
$share->setShareType($shareType);
@@ -1361,7 +1343,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;
}));
@@ -1371,9 +1353,7 @@ class ManagerTest extends \Test\TestCase {
$this->assertEquals($expected, $share->getExpirationDate());
}
- /**
- * @dataProvider validateExpirationDateInternalProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('validateExpirationDateInternalProvider')]
public function testValidateExpirationDateInternalDefault($shareType): void {
$future = new \DateTime('now', $this->timezone);
$future->add(new \DateInterval('P5D'));
@@ -1403,7 +1383,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;
}));
@@ -1413,9 +1393,7 @@ class ManagerTest extends \Test\TestCase {
$this->assertEquals($expected, $share->getExpirationDate());
}
- /**
- * @dataProvider validateExpirationDateInternalProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('validateExpirationDateInternalProvider')]
public function testValidateExpirationDateInternalHookModification($shareType): void {
$nextWeek = new \DateTime('now', $this->timezone);
$nextWeek->add(new \DateInterval('P7D'));
@@ -1424,8 +1402,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'));
});
@@ -1439,9 +1417,7 @@ class ManagerTest extends \Test\TestCase {
$this->assertEquals($save, $share->getExpirationDate());
}
- /**
- * @dataProvider validateExpirationDateInternalProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('validateExpirationDateInternalProvider')]
public function testValidateExpirationDateInternalHookException($shareType): void {
$this->expectException(\Exception::class);
$this->expectExceptionMessage('Invalid date!');
@@ -1455,8 +1431,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!';
});
@@ -1464,9 +1440,7 @@ class ManagerTest extends \Test\TestCase {
self::invokePrivate($this->manager, 'validateExpirationDateInternal', [$share]);
}
- /**
- * @dataProvider validateExpirationDateInternalProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('validateExpirationDateInternalProvider')]
public function testValidateExpirationDateInternalExistingShareNoDefault($shareType): void {
$share = $this->manager->newShare();
$share->setShareType($shareType);
@@ -1492,7 +1466,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
@@ -1578,7 +1552,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();
@@ -1616,7 +1590,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;
}));
@@ -1639,7 +1613,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;
}));
@@ -1651,7 +1625,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;
}));
@@ -1680,7 +1654,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;
}));
@@ -1710,7 +1684,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;
}));
@@ -1741,7 +1715,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;
}));
@@ -1761,8 +1735,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'));
});
@@ -1786,8 +1760,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!';
});
@@ -2203,7 +2177,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
@@ -2223,7 +2197,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
@@ -2239,7 +2213,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);
@@ -2258,7 +2232,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);
@@ -2352,7 +2326,6 @@ class ManagerTest extends \Test\TestCase {
}
/**
- * @dataProvider dataIsSharingDisabledForUser
*
* @param string $excludeGroups
* @param string $groupList
@@ -2360,6 +2333,7 @@ class ManagerTest extends \Test\TestCase {
* @param string[] $groupIds
* @param bool $expected
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataIsSharingDisabledForUser')]
public function testIsSharingDisabledForUser($excludeGroups, $groupList, $setList, $groupIds, $expected): void {
$user = $this->createMock(IUser::class);
@@ -2404,12 +2378,12 @@ class ManagerTest extends \Test\TestCase {
}
/**
- * @dataProvider dataCanShare
*
* @param bool $expected
* @param string $sharingEnabled
* @param bool $disabledForUser
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataCanShare')]
public function testCanShare($expected, $sharingEnabled, $disabledForUser): void {
$this->config->method('getAppValue')
->willReturnMap([
@@ -2459,7 +2433,7 @@ class ManagerTest extends \Test\TestCase {
'sharedWith',
'sharedBy',
null,
- \OCP\Constants::PERMISSION_ALL);
+ Constants::PERMISSION_ALL);
$manager->expects($this->once())
->method('canShare')
@@ -2514,7 +2488,7 @@ class ManagerTest extends \Test\TestCase {
'sharedWith',
'sharedBy',
null,
- \OCP\Constants::PERMISSION_ALL);
+ Constants::PERMISSION_ALL);
$manager->expects($this->once())
->method('canShare')
@@ -2577,7 +2551,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');
@@ -2629,7 +2603,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();
@@ -2637,7 +2611,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');
@@ -2685,7 +2659,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')
@@ -2726,7 +2700,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();
@@ -2734,7 +2708,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');
@@ -2783,7 +2757,7 @@ class ManagerTest extends \Test\TestCase {
'sharedWith',
'sharedBy',
null,
- \OCP\Constants::PERMISSION_ALL);
+ Constants::PERMISSION_ALL);
$manager->expects($this->once())
->method('canShare')
@@ -2813,7 +2787,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();
}
@@ -2862,7 +2836,7 @@ class ManagerTest extends \Test\TestCase {
'sharedWith',
'sharedBy',
null,
- \OCP\Constants::PERMISSION_ALL);
+ Constants::PERMISSION_ALL);
$manager->expects($this->once())
->method('canShare')
@@ -2956,7 +2930,7 @@ class ManagerTest extends \Test\TestCase {
->onlyMethods(['deleteShare'])
->getMock();
- /** @var \OCP\Share\IShare[] $shares */
+ /** @var IShare[] $shares */
$shares = [];
/*
@@ -2979,7 +2953,7 @@ class ManagerTest extends \Test\TestCase {
$shares[4]->setExpirationDate($today);
$shares[5]->setExpirationDate($today);
- /** @var \OCP\Share\IShare[] $i */
+ /** @var IShare[] $i */
$shares2 = [];
for ($i = 0; $i < 8; $i++) {
$shares2[] = clone $shares[$i];
@@ -3000,7 +2974,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);
@@ -3074,7 +3048,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;
@@ -3130,7 +3104,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
@@ -3185,7 +3159,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
@@ -3246,7 +3220,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())
@@ -3268,7 +3242,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);
@@ -3280,7 +3254,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 {
@@ -3332,7 +3306,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';
}));
@@ -3468,14 +3442,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,
@@ -3526,11 +3500,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);
@@ -3588,7 +3562,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,
@@ -3597,7 +3571,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,
@@ -3607,7 +3581,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');
@@ -3669,15 +3643,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);
@@ -3698,7 +3672,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);
@@ -3717,7 +3691,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);
@@ -3738,7 +3712,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,
@@ -3747,7 +3721,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,
@@ -3757,7 +3731,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);
@@ -3778,7 +3752,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);
@@ -3800,7 +3774,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);
@@ -3821,7 +3795,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,
@@ -3830,7 +3804,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,
@@ -3840,7 +3814,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);
@@ -3861,7 +3835,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);
@@ -3883,7 +3857,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);
@@ -3909,7 +3883,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,
@@ -3918,7 +3892,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,
@@ -3928,7 +3902,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);
@@ -3952,7 +3926,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);
@@ -3974,7 +3948,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);
@@ -3992,15 +3966,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);
@@ -4025,7 +3999,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);
@@ -4047,7 +4021,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);
@@ -4065,15 +4039,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);
@@ -4098,7 +4072,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);
@@ -4120,7 +4094,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);
@@ -4138,15 +4112,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);
@@ -4171,7 +4145,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);
@@ -4193,7 +4167,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);
@@ -4213,15 +4187,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);
@@ -4245,7 +4219,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);
@@ -4267,7 +4241,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);
@@ -4287,15 +4261,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);
@@ -4319,7 +4293,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);
@@ -4341,7 +4315,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);
@@ -4361,15 +4335,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);
@@ -4472,9 +4446,7 @@ class ManagerTest extends \Test\TestCase {
$this->addToAssertionCount(1);
}
- /**
- * @dataProvider dataTestShareProviderExists
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataTestShareProviderExists')]
public function testShareProviderExists($shareType, $expected): void {
$factory = $this->getMockBuilder('OCP\Share\IProviderFactory')->getMock();
$factory->expects($this->any())->method('getProviderForType')
@@ -4482,7 +4454,7 @@ class ManagerTest extends \Test\TestCase {
if ($id === IShare::TYPE_USER) {
return true;
}
- throw new Exception\ProviderException();
+ throw new ProviderException();
});
$manager = $this->createManager($factory);
@@ -4551,7 +4523,7 @@ class ManagerTest extends \Test\TestCase {
$manager = $this->createManager($factory);
$factory->setProvider($this->defaultProvider);
- $extraProvider = $this->createMock(IShareProvider::class);
+ $extraProvider = $this->createMock(IShareProviderSupportsAllSharesInFolder::class);
$factory->setSecondProvider($extraProvider);
$share1 = $this->createMock(IShare::class);
@@ -4559,28 +4531,20 @@ class ManagerTest extends \Test\TestCase {
$mount = $this->createMock(IShareOwnerlessMount::class);
- $file = $this->createMock(File::class);
- $file
- ->method('getId')
- ->willReturn(1);
-
$folder = $this->createMock(Folder::class);
$folder
->method('getMountPoint')
->willReturn($mount);
- $folder
- ->method('getDirectoryListing')
- ->willReturn([$file]);
$this->defaultProvider
- ->method('getSharesByPath')
- ->with($file)
- ->willReturn([$share1]);
+ ->method('getAllSharesInFolder')
+ ->with($folder)
+ ->willReturn([1 => [$share1]]);
$extraProvider
- ->method('getSharesByPath')
- ->with($file)
- ->willReturn([$share2]);
+ ->method('getAllSharesInFolder')
+ ->with($folder)
+ ->willReturn([1 => [$share2]]);
$this->assertSame([
1 => [$share1, $share2],
@@ -4853,9 +4817,9 @@ class ManagerTest extends \Test\TestCase {
}
/**
- * @dataProvider dataCurrentUserCanEnumerateTargetUser
* @param bool $expected
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataCurrentUserCanEnumerateTargetUser')]
public function testCurrentUserCanEnumerateTargetUser(bool $currentUserIsGuest, bool $allowEnumerationFullMatch, bool $allowEnumeration, bool $limitEnumerationToPhone, bool $limitEnumerationToGroups, bool $isKnownToUser, bool $haveCommonGroup, bool $expected): void {
/** @var IManager|MockObject $manager */
$manager = $this->createManagerMock()
@@ -4912,7 +4876,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/ShareHelperTest.php b/tests/lib/Share20/ShareHelperTest.php
index 8aaa8350ea9..3928843cf7d 100644
--- a/tests/lib/Share20/ShareHelperTest.php
+++ b/tests/lib/Share20/ShareHelperTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2017 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
@@ -27,7 +28,7 @@ class ShareHelperTest extends TestCase {
$this->helper = new ShareHelper($this->manager);
}
- public function dataGetPathsForAccessList() {
+ public static function dataGetPathsForAccessList(): array {
return [
[[], [], false, [], [], false, [
'users' => [],
@@ -48,9 +49,7 @@ class ShareHelperTest extends TestCase {
];
}
- /**
- * @dataProvider dataGetPathsForAccessList
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataGetPathsForAccessList')]
public function testGetPathsForAccessList(array $userList, array $userMap, $resolveUsers, array $remoteList, array $remoteMap, $resolveRemotes, array $expected): void {
$this->manager->expects($this->once())
->method('getAccessList')
@@ -64,7 +63,7 @@ class ShareHelperTest extends TestCase {
/** @var ShareHelper|\PHPUnit\Framework\MockObject\MockObject $helper */
$helper = $this->getMockBuilder(ShareHelper::class)
->setConstructorArgs([$this->manager])
- ->setMethods(['getPathsForUsers', 'getPathsForRemotes'])
+ ->onlyMethods(['getPathsForUsers', 'getPathsForRemotes'])
->getMock();
$helper->expects($resolveUsers ? $this->once() : $this->never())
@@ -80,7 +79,7 @@ class ShareHelperTest extends TestCase {
$this->assertSame($expected, $helper->getPathsForAccessList($node));
}
- public function dataGetPathsForUsers() {
+ public static function dataGetPathsForUsers(): array {
return [
[[], [23 => 'TwentyThree', 42 => 'FortyTwo'], []],
[
@@ -101,12 +100,12 @@ class ShareHelperTest extends TestCase {
}
/**
- * @dataProvider dataGetPathsForUsers
*
* @param array $users
* @param array $nodes
* @param array $expected
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataGetPathsForUsers')]
public function testGetPathsForUsers(array $users, array $nodes, array $expected): void {
$lastNode = null;
foreach ($nodes as $nodeId => $nodeName) {
@@ -133,7 +132,7 @@ class ShareHelperTest extends TestCase {
$this->assertEquals($expected, self::invokePrivate($this->helper, 'getPathsForUsers', [$lastNode, $users]));
}
- public function dataGetPathsForRemotes() {
+ public static function dataGetPathsForRemotes(): array {
return [
[[], [23 => 'TwentyThree', 42 => 'FortyTwo'], []],
[
@@ -158,12 +157,12 @@ class ShareHelperTest extends TestCase {
}
/**
- * @dataProvider dataGetPathsForRemotes
*
* @param array $remotes
* @param array $nodes
* @param array $expected
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataGetPathsForRemotes')]
public function testGetPathsForRemotes(array $remotes, array $nodes, array $expected): void {
$lastNode = null;
foreach ($nodes as $nodeId => $nodePath) {
@@ -190,7 +189,7 @@ class ShareHelperTest extends TestCase {
$this->assertEquals($expected, self::invokePrivate($this->helper, 'getPathsForRemotes', [$lastNode, $remotes]));
}
- public function dataGetMountedPath() {
+ public static function dataGetMountedPath(): array {
return [
['/admin/files/foobar', '/foobar'],
['/admin/files/foo/bar', '/foo/bar'],
@@ -198,10 +197,10 @@ class ShareHelperTest extends TestCase {
}
/**
- * @dataProvider dataGetMountedPath
* @param string $path
* @param string $expected
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataGetMountedPath')]
public function testGetMountedPath($path, $expected): void {
/** @var Node|\PHPUnit\Framework\MockObject\MockObject $node */
$node = $this->createMock(Node::class);
diff --git a/tests/lib/Share20/ShareTest.php b/tests/lib/Share20/ShareTest.php
index 72f3b46190c..f15fbb860db 100644
--- a/tests/lib/Share20/ShareTest.php
+++ b/tests/lib/Share20/ShareTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -7,8 +8,11 @@
namespace Test\Share20;
+use OC\Share20\Share;
use OCP\Files\IRootFolder;
use OCP\IUserManager;
+use OCP\Share\Exceptions\IllegalIDChangeException;
+use OCP\Share\IShare;
use PHPUnit\Framework\MockObject\MockObject;
/**
@@ -21,13 +25,13 @@ class ShareTest extends \Test\TestCase {
protected $rootFolder;
/** @var IUserManager|MockObject */
protected $userManager;
- /** @var \OCP\Share\IShare */
+ /** @var IShare */
protected $share;
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 +55,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 +79,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..39bb72b445c 100644
--- a/tests/lib/SubAdminTest.php
+++ b/tests/lib/SubAdminTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -7,30 +8,37 @@
namespace Test;
+use OC\SubAdmin;
use OCP\EventDispatcher\IEventDispatcher;
use OCP\Group\Events\SubAdminAddedEvent;
use OCP\Group\Events\SubAdminRemovedEvent;
+use OCP\IDBConnection;
+use OCP\IGroup;
+use OCP\IGroupManager;
+use OCP\IUser;
+use OCP\IUserManager;
+use OCP\Server;
/**
* @group DB
*/
class SubAdminTest extends \Test\TestCase {
- /** @var \OCP\IUserManager */
+ /** @var IUserManager */
private $userManager;
- /** @var \OCP\IGroupManager */
+ /** @var IGroupManager */
private $groupManager;
- /** @var \OCP\IDBConnection */
+ /** @var IDBConnection */
private $dbConn;
/** @var IEventDispatcher */
private $eventDispatcher;
- /** @var \OCP\IUser[] */
+ /** @var IUser[] */
private $users;
- /** @var \OCP\IGroup[] */
+ /** @var IGroup[] */
private $groups;
protected function setUp(): void {
@@ -39,10 +47,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 +103,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 +128,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 +144,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 +160,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 +176,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 +191,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 +202,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 +212,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 +235,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 +248,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 +260,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 +272,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 b3a0f8e603e..e6e83d6038b 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);
@@ -157,7 +158,7 @@ class RegistryTest extends TestCase {
$this->assertSame(false, $this->registry->delegateIsHardUserLimitReached($this->notificationManager));
}
- public function dataForUserLimitCheck() {
+ public static function dataForUserLimitCheck(): array {
return [
// $userLimit, $userCount, $disabledUsers, $expectedResult
[35, 15, 2, false],
@@ -167,9 +168,7 @@ class RegistryTest extends TestCase {
];
}
- /**
- * @dataProvider dataForUserLimitCheck
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataForUserLimitCheck')]
public function testDelegateIsHardUserLimitReachedWithoutSupportAppAndUserCount($userLimit, $userCount, $disabledUsers, $expectedResult): void {
$this->config->expects($this->once())
->method('getSystemValueBool')
diff --git a/tests/lib/SystemTag/SystemTagManagerTest.php b/tests/lib/SystemTag/SystemTagManagerTest.php
index 94103c52cb1..7bbe86aabe7 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);
@@ -66,7 +69,7 @@ class SystemTagManagerTest extends TestCase {
$query->delete(SystemTagManager::TAG_TABLE)->execute();
}
- public static function getAllTagsDataProvider() {
+ public static function getAllTagsDataProvider(): array {
return [
[
// no tags at all
@@ -93,9 +96,7 @@ class SystemTagManagerTest extends TestCase {
];
}
- /**
- * @dataProvider getAllTagsDataProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('getAllTagsDataProvider')]
public function testGetAllTags($testTags): void {
$testTagsById = [];
foreach ($testTags as $testTag) {
@@ -113,7 +114,7 @@ class SystemTagManagerTest extends TestCase {
}
}
- public static function getAllTagsFilteredDataProvider() {
+ public static function getAllTagsFilteredDataProvider(): array {
return [
[
[
@@ -202,9 +203,7 @@ class SystemTagManagerTest extends TestCase {
];
}
- /**
- * @dataProvider getAllTagsFilteredDataProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('getAllTagsFilteredDataProvider')]
public function testGetAllTagsFiltered($testTags, $visibilityFilter, $nameSearch, $expectedResults): void {
foreach ($testTags as $testTag) {
$this->tagManager->createTag($testTag[0], $testTag[1], $testTag[2]);
@@ -226,7 +225,7 @@ class SystemTagManagerTest extends TestCase {
}
}
- public static function oneTagMultipleFlagsProvider() {
+ public static function oneTagMultipleFlagsProvider(): array {
return [
['one', false, false],
['one', true, false],
@@ -235,11 +234,9 @@ class SystemTagManagerTest extends TestCase {
];
}
- /**
- * @dataProvider oneTagMultipleFlagsProvider
- */
+ #[\PHPUnit\Framework\Attributes\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);
@@ -254,9 +251,7 @@ class SystemTagManagerTest extends TestCase {
$this->assertSame('Zona circundante do Palácio Nacional da Ajuda (Jardim das Damas', $tag->getName()); // 63 characters but 64 bytes due to "á"
}
- /**
- * @dataProvider oneTagMultipleFlagsProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('oneTagMultipleFlagsProvider')]
public function testGetExistingTag($name, $userVisible, $userAssignable): void {
$tag1 = $this->tagManager->createTag($name, $userVisible, $userAssignable);
$tag2 = $this->tagManager->getTag($name, $userVisible, $userAssignable);
@@ -278,14 +273,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]);
@@ -299,7 +294,7 @@ class SystemTagManagerTest extends TestCase {
$this->tagManager->getTagsByIds([$tag1->getId() . 'suffix']);
}
- public static function updateTagProvider() {
+ public static function updateTagProvider(): array {
return [
[
// update name
@@ -324,9 +319,7 @@ class SystemTagManagerTest extends TestCase {
];
}
- /**
- * @dataProvider updateTagProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('updateTagProvider')]
public function testUpdateTag($tagCreate, $tagUpdated): void {
$tag1 = $this->tagManager->createTag(
$tagCreate[0],
@@ -356,11 +349,9 @@ class SystemTagManagerTest extends TestCase {
}
- /**
- * @dataProvider updateTagProvider
- */
+ #[\PHPUnit\Framework\Attributes\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 +387,7 @@ class SystemTagManagerTest extends TestCase {
public function testDeleteNonExistingTag(): void {
- $this->expectException(\OCP\SystemTag\TagNotFoundException::class);
+ $this->expectException(TagNotFoundException::class);
$this->tagManager->deleteTags([100]);
}
@@ -424,7 +415,7 @@ class SystemTagManagerTest extends TestCase {
], $tagIdMapping);
}
- public static function visibilityCheckProvider() {
+ public static function visibilityCheckProvider(): array {
return [
[false, false, false, false],
[true, false, false, true],
@@ -433,9 +424,7 @@ class SystemTagManagerTest extends TestCase {
];
}
- /**
- * @dataProvider visibilityCheckProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('visibilityCheckProvider')]
public function testVisibilityCheck($userVisible, $userAssignable, $isAdmin, $expectedResult): void {
$user = $this->getMockBuilder(IUser::class)->getMock();
$user->expects($this->any())
@@ -451,7 +440,7 @@ class SystemTagManagerTest extends TestCase {
$this->assertEquals($expectedResult, $this->tagManager->canUserSeeTag($tag1, $user));
}
- public static function assignabilityCheckProvider() {
+ public static function assignabilityCheckProvider(): array {
return [
// no groups
[false, false, false, false],
@@ -480,9 +469,7 @@ class SystemTagManagerTest extends TestCase {
];
}
- /**
- * @dataProvider assignabilityCheckProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('assignabilityCheckProvider')]
public function testAssignabilityCheck($userVisible, $userAssignable, $isAdmin, $expectedResult, $userGroupIds = [], $tagGroupIds = []): void {
$user = $this->getMockBuilder(IUser::class)->getMock();
$user->expects($this->any())
@@ -529,7 +516,7 @@ class SystemTagManagerTest extends TestCase {
$this->assertEquals([], $this->tagManager->getTagGroups($tag1));
}
- private function allowedToCreateProvider(): array {
+ public static function allowedToCreateProvider(): array {
return [
[true, null, true],
[true, null, false],
@@ -539,9 +526,7 @@ class SystemTagManagerTest extends TestCase {
];
}
- /**
- * @dataProvider allowedToCreateProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('allowedToCreateProvider')]
public function testAllowedToCreateTag(bool $isCli, ?bool $isAdmin, bool $isRestricted): void {
$oldCli = \OC::$CLI;
\OC::$CLI = $isCli;
@@ -570,16 +555,14 @@ class SystemTagManagerTest extends TestCase {
\OC::$CLI = $oldCli;
}
- private function disallowedToCreateProvider(): array {
+ public static function disallowedToCreateProvider(): array {
return [
[false],
[null],
];
}
- /**
- * @dataProvider disallowedToCreateProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('disallowedToCreateProvider')]
public function testDisallowedToCreateTag(?bool $isAdmin): void {
$oldCli = \OC::$CLI;
\OC::$CLI = false;
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..d47ce2d2178 100644
--- a/tests/lib/TagsTest.php
+++ b/tests/lib/TagsTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -7,8 +8,11 @@
namespace Test;
+use OC\Tagging\TagMapper;
+use OC\TagManager;
use OCP\EventDispatcher\IEventDispatcher;
use OCP\IDBConnection;
+use OCP\ITagManager;
use OCP\IUser;
use OCP\IUserManager;
use OCP\IUserSession;
@@ -22,14 +26,14 @@ use Psr\Log\LoggerInterface;
*/
class TagsTest extends \Test\TestCase {
protected $objectType;
- /** @var \OCP\IUser */
+ /** @var IUser */
protected $user;
- /** @var \OCP\IUserSession */
+ /** @var IUserSession */
protected $userSession;
protected $backupGlobals = false;
/** @var \OC\Tagging\TagMapper */
protected $tagMapper;
- /** @var \OCP\ITagManager */
+ /** @var ITagManager */
protected $tagMgr;
protected function setUp(): void {
@@ -50,12 +54,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 +72,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,11 +198,11 @@ 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 ' .
- '(?, ?, ?)'
+ 'INSERT INTO `*PREFIX*vcategory_to_object` '
+ . '(`objid`, `categoryid`, `type`) VALUES '
+ . '(?, ?, ?)'
);
// insert lots of entries
diff --git a/tests/lib/TaskProcessing/TaskProcessingTest.php b/tests/lib/TaskProcessing/TaskProcessingTest.php
index 73f67b07266..db474a00687 100644
--- a/tests/lib/TaskProcessing/TaskProcessingTest.php
+++ b/tests/lib/TaskProcessing/TaskProcessingTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
@@ -12,6 +13,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 +21,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 +30,14 @@ use OCP\IDBConnection;
use OCP\IServerContainer;
use OCP\IUser;
use OCP\IUserManager;
+use OCP\IUserSession;
+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 +557,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 +570,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 +591,36 @@ 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),
+ $userManager,
+ Server::get(IUserSession::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 +630,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 +645,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 +702,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 +730,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 +775,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 +811,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 +862,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 +873,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 +912,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 +925,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 +941,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 +955,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 +970,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 +995,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 +1026,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 +1056,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 +1073,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 +1092,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 +1245,30 @@ 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(IUserManager::class),
+ Server::get(IUserSession::class),
+ Server::get(ICacheFactory::class),
);
}
@@ -1271,7 +1281,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 63cffc0dcae..ee7778c7e88 100644
--- a/tests/lib/TempManagerTest.php
+++ b/tests/lib/TempManagerTest.php
@@ -9,6 +9,8 @@
namespace Test;
use bantu\IniGetWrapper\IniGetWrapper;
+use OC\TempManager;
+use OCP\Files;
use OCP\IConfig;
use Psr\Log\LoggerInterface;
@@ -26,7 +28,7 @@ class TempManagerTest extends \Test\TestCase {
protected function tearDown(): void {
if ($this->baseDir !== null) {
- \OC_Helper::rmdirr($this->baseDir);
+ Files::rmdirr($this->baseDir);
}
$this->baseDir = null;
parent::tearDown();
@@ -48,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/CSSResourceLocatorTest.php b/tests/lib/Template/CSSResourceLocatorTest.php
index ed02358a8c9..2ae37999b32 100644
--- a/tests/lib/Template/CSSResourceLocatorTest.php
+++ b/tests/lib/Template/CSSResourceLocatorTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2017 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
diff --git a/tests/lib/Template/JSCombinerTest.php b/tests/lib/Template/JSCombinerTest.php
index e4e6594c05c..bc286695bc7 100644
--- a/tests/lib/Template/JSCombinerTest.php
+++ b/tests/lib/Template/JSCombinerTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2017 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
@@ -15,7 +16,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 {
@@ -471,8 +474,8 @@ var b = \'world\';
* @param $appName
* @param $fileName
* @param $result
- * @dataProvider dataGetCachedSCSS
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataGetCachedSCSS')]
public function testGetCachedSCSS($appName, $fileName, $result): void {
$this->urlGenerator->expects($this->once())
->method('linkToRoute')
@@ -488,7 +491,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 +506,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/JSResourceLocatorTest.php b/tests/lib/Template/JSResourceLocatorTest.php
index bb2c2bec6c4..89ab8e66dd7 100644
--- a/tests/lib/Template/JSResourceLocatorTest.php
+++ b/tests/lib/Template/JSResourceLocatorTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2017 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
diff --git a/tests/lib/Template/ResourceLocatorTest.php b/tests/lib/Template/ResourceLocatorTest.php
index 65d4c7938f9..599c8391ade 100644
--- a/tests/lib/Template/ResourceLocatorTest.php
+++ b/tests/lib/Template/ResourceLocatorTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -60,11 +61,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/TemplateFunctionsTest.php b/tests/lib/TemplateFunctionsTest.php
index 5b23ef434c2..8c1523628ab 100644
--- a/tests/lib/TemplateFunctionsTest.php
+++ b/tests/lib/TemplateFunctionsTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
diff --git a/tests/lib/TemplateLayoutTest.php b/tests/lib/TemplateLayoutTest.php
index b3895525408..c1cafcd6b93 100644
--- a/tests/lib/TemplateLayoutTest.php
+++ b/tests/lib/TemplateLayoutTest.php
@@ -40,7 +40,7 @@ class TemplateLayoutTest extends \Test\TestCase {
$this->serverVersion = $this->createMock(ServerVersion::class);
}
- /** @dataProvider dataVersionHash */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataVersionHash')]
public function testVersionHash($path, $file, $installed, $debug, $expected): void {
$this->appManager->expects(self::any())
->method('getAppVersion')
diff --git a/tests/lib/TestCase.php b/tests/lib/TestCase.php
index 918edf7150e..e91e847e859 100644
--- a/tests/lib/TestCase.php
+++ b/tests/lib/TestCase.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -10,12 +11,15 @@ 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;
use OC\Files\Mount\LocalHomeMountProvider;
use OC\Files\Mount\RootMountProvider;
+use OC\Files\ObjectStore\PrimaryObjectStoreConfig;
use OC\Files\SetupManager;
+use OC\Files\View;
use OC\Template\Base;
use OCP\Command\IBus;
use OCP\DB\QueryBuilder\IQueryBuilder;
@@ -23,9 +27,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 Psr\Log\LoggerInterface;
+use OCP\Server;
if (version_compare(\PHPUnit\Runner\Version::id(), 10, '>=')) {
trait OnNotSuccessfulTestTrait {
@@ -84,7 +91,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 +161,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 +190,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 +203,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 +271,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 +310,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 +328,19 @@ 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());
- $mountProviderCollection->registerRootProvider(new RootMountProvider($config, \OC::$server->get(LoggerInterface::class)));
+ $objectStoreConfig = Server::get(PrimaryObjectStoreConfig::class);
+ $mountProviderCollection->registerRootProvider(new RootMountProvider($objectStoreConfig, $config));
$setupManager->setupRoot();
@@ -403,7 +411,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;
@@ -429,7 +437,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();
}
/**
@@ -440,14 +448,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);
}
}
@@ -459,7 +467,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);
}
/**
@@ -486,7 +494,7 @@ abstract class TestCase extends \PHPUnit\Framework\TestCase {
/**
* Check if the given path is locked with a given type
*
- * @param \OC\Files\View $view view
+ * @param View $view view
* @param string $path path to check
* @param int $type lock type
* @param bool $onMountPoint true to check the mount point instead of the
@@ -500,12 +508,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);
@@ -513,7 +521,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..5906a90ee18 100644
--- a/tests/lib/TestMoveableMountPoint.php
+++ b/tests/lib/TestMoveableMountPoint.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -8,11 +9,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 84c5492a4a2..bdcb4a57d7c 100644
--- a/tests/lib/TextProcessing/TextProcessingTest.php
+++ b/tests/lib/TextProcessing/TextProcessingTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2023 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
@@ -23,6 +24,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 +120,7 @@ class TextProcessingTest 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);
@@ -158,14 +160,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,11 +178,11 @@ class TextProcessingTest extends \Test\TestCase {
$this->manager = new Manager(
$this->serverContainer,
$this->coordinator,
- \OC::$server->get(LoggerInterface::class),
+ Server::get(LoggerInterface::class),
$this->jobList,
$this->taskMapper,
$config,
- \OC::$server->get(\OCP\TaskProcessing\IManager::class),
+ $this->createMock(\OCP\TaskProcessing\IManager::class),
);
}
@@ -239,7 +241,7 @@ class TextProcessingTest extends \Test\TestCase {
// run background job
$bgJob = new TaskBackgroundJob(
- \OC::$server->get(ITimeFactory::class),
+ Server::get(ITimeFactory::class),
$this->manager,
$this->eventDispatcher,
);
@@ -314,7 +316,7 @@ class TextProcessingTest extends \Test\TestCase {
// run background job
$bgJob = new TaskBackgroundJob(
- \OC::$server->get(ITimeFactory::class),
+ Server::get(ITimeFactory::class),
$this->manager,
$this->eventDispatcher,
);
@@ -343,9 +345,9 @@ class TextProcessingTest extends \Test\TestCase {
$this->currentTime = $this->currentTime->add(new \DateInterval('P1Y'));
// run background job
$bgJob = new RemoveOldTasksBackgroundJob(
- \OC::$server->get(ITimeFactory::class),
+ Server::get(ITimeFactory::class),
$this->taskMapper,
- \OC::$server->get(LoggerInterface::class),
+ Server::get(LoggerInterface::class),
);
$bgJob->setArgument([]);
$bgJob->start($this->jobList);
diff --git a/tests/lib/Traits/ClientServiceTrait.php b/tests/lib/Traits/ClientServiceTrait.php
index 3f0d71aeb28..5a091544889 100644
--- a/tests/lib/Traits/ClientServiceTrait.php
+++ b/tests/lib/Traits/ClientServiceTrait.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2017 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
diff --git a/tests/lib/Traits/EncryptionTrait.php b/tests/lib/Traits/EncryptionTrait.php
index e435a286685..50c20befc4d 100644
--- a/tests/lib/Traits/EncryptionTrait.php
+++ b/tests/lib/Traits/EncryptionTrait.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2017-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -11,10 +12,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;
/**
@@ -38,12 +43,12 @@ trait EncryptionTrait {
private $setupManager;
/**
- * @var \OCP\IConfig
+ * @var IConfig
*/
private $config;
/**
- * @var \OCA\Encryption\AppInfo\Application
+ * @var Application
*/
private $encryptionApp;
@@ -51,7 +56,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 +86,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 6d947d645dd..b680c71b2d6 100644
--- a/tests/lib/Traits/MountProviderTrait.php
+++ b/tests/lib/Traits/MountProviderTrait.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -9,14 +10,17 @@ namespace Test\Traits;
use OC\Files\Mount\MountPoint;
use OC\Files\Storage\StorageFactory;
+use OCP\Files\Config\IMountProvider;
+use OCP\Files\Config\IMountProviderCollection;
use OCP\IUser;
+use OCP\Server;
/**
* Allow setting mounts for users
*/
trait MountProviderTrait {
/**
- * @var \OCP\Files\Config\IMountProvider
+ * @var IMountProvider
*/
protected $mountProvider;
@@ -49,7 +53,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 +61,7 @@ trait MountProviderTrait {
} else {
return [];
}
- }));
- \OC::$server->getMountProviderCollection()->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..f80adb76be8 100644
--- a/tests/lib/Traits/UserTrait.php
+++ b/tests/lib/Traits/UserTrait.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2022-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -10,14 +11,15 @@ namespace Test\Traits;
use OC\User\User;
use OCP\EventDispatcher\IEventDispatcher;
use OCP\IUser;
+use OCP\IUserManager;
use OCP\Server;
+use OCP\UserInterface;
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 {
@@ -30,7 +32,7 @@ class DummyUser extends User {
*/
trait UserTrait {
/**
- * @var \Test\Util\User\Dummy|\OCP\UserInterface
+ * @var \Test\Util\User\Dummy|UserInterface
*/
protected $userBackend;
@@ -41,10 +43,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..dd0d97a9e80 100644
--- a/tests/lib/Updater/ChangesCheckTest.php
+++ b/tests/lib/Updater/ChangesCheckTest.php
@@ -51,9 +51,7 @@ class ChangesCheckTest extends TestCase {
];
}
- /**
- * @dataProvider statusCodeProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('statusCodeProvider')]
public function testEvaluateResponse(int $statusCode, int $expected): void {
$response = $this->createMock(IResponse::class);
$response->expects($this->atLeastOnce())
@@ -271,9 +269,7 @@ class ChangesCheckTest extends TestCase {
];
}
- /**
- * @dataProvider changesXMLProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('changesXMLProvider')]
public function testExtractData(string $body, array $expected): void {
$actual = $this->invokePrivate($this->checker, 'extractData', [$body]);
$this->assertSame($expected, $actual);
@@ -286,9 +282,7 @@ class ChangesCheckTest extends TestCase {
];
}
- /**
- * @dataProvider etagProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('etagProvider')]
public function testQueryChangesServer(string $etag): void {
$uri = 'https://changes.nextcloud.server/?13.0.5';
$entry = $this->createMock(Changes::class);
@@ -323,9 +317,7 @@ class ChangesCheckTest extends TestCase {
];
}
- /**
- * @dataProvider versionProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('versionProvider')]
public function testNormalizeVersion(string $input, string $expected): void {
$normalized = $this->checker->normalizeVersion($input);
$this->assertSame($expected, $normalized);
@@ -333,19 +325,16 @@ 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);
}
- /**
- * @dataProvider changeDataProvider
- *
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('changeDataProvider')]
public function testGetChangesForVersion(string $inputVersion, string $normalizedVersion, bool $isFound): void {
$mocker = $this->mapper->expects($this->once())
->method('getChanges')
diff --git a/tests/lib/Updater/ReleaseMetadataTest.php b/tests/lib/Updater/ReleaseMetadataTest.php
index 72c6da5064d..e93d9fe64be 100644
--- a/tests/lib/Updater/ReleaseMetadataTest.php
+++ b/tests/lib/Updater/ReleaseMetadataTest.php
@@ -17,9 +17,7 @@ class ReleaseMetadataTest extends \Test\TestCase {
protected function setUp(): void {
parent::setUp();
- $this->clientService = $this->getMockBuilder(IClientService::class)
- ->disableOriginalConstructor()
- ->getMock();
+ $this->clientService = $this->createMock(IClientService::class);
}
public function testDownloadMetadata(): void {
@@ -39,15 +37,15 @@ class ReleaseMetadataTest extends \Test\TestCase {
$releaseMetadata = new ReleaseMetadata($this->clientService);
- $this->assertSame($this->resultRequestArray(), $releaseMetadata->downloadMetadata('ouila'));
+ $this->assertSame(self::resultRequestArray(), $releaseMetadata->downloadMetadata('ouila'));
}
/**
- * @dataProvider getMetadataUrlProvider
*
* @param string $version
* @param string $url
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('getMetadataUrlProvider')]
public function testGetMetadata(string $version, string $url): void {
$client = $this->createMock(IClient::class);
$response = $this->createMock(IResponse::class);
@@ -72,7 +70,7 @@ class ReleaseMetadataTest extends \Test\TestCase {
/**
* @return array
*/
- public function getMetadataUrlProvider(): array {
+ public static function getMetadataUrlProvider(): array {
return [
[
'30.0.0',
@@ -89,11 +87,11 @@ class ReleaseMetadataTest extends \Test\TestCase {
];
}
- private function resultRequest(): string {
- return json_encode($this->resultRequestArray());
+ private static function resultRequest(): string {
+ return json_encode(self::resultRequestArray());
}
- private function resultRequestArray(): array {
+ private static function resultRequestArray(): array {
return [
'migrations' => [
'core' => [],
diff --git a/tests/lib/Updater/VersionCheckTest.php b/tests/lib/Updater/VersionCheckTest.php
index 51d1625ea4d..1936062a5d0 100644
--- a/tests/lib/Updater/VersionCheckTest.php
+++ b/tests/lib/Updater/VersionCheckTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -12,6 +13,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;
@@ -45,7 +47,7 @@ class VersionCheckTest extends \Test\TestCase {
->willReturn(false);
$this->logger = $this->createMock(LoggerInterface::class);
$this->updater = $this->getMockBuilder(VersionCheck::class)
- ->setMethods(['getUrlContent'])
+ ->onlyMethods(['getUrlContent'])
->setConstructorArgs([
$this->serverVersion,
$clientService,
@@ -63,7 +65,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/UpdaterTest.php b/tests/lib/UpdaterTest.php
index 81babee7029..37a4a105628 100644
--- a/tests/lib/UpdaterTest.php
+++ b/tests/lib/UpdaterTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -54,7 +55,7 @@ class UpdaterTest extends TestCase {
/**
* @return array
*/
- public function versionCompatibilityTestData() {
+ public static function versionCompatibilityTestData(): array {
return [
// Upgrade with invalid version
['9.1.1.13', '11.0.2.25', ['nextcloud' => ['11.0' => true]], false],
@@ -81,7 +82,6 @@ class UpdaterTest extends TestCase {
}
/**
- * @dataProvider versionCompatibilityTestData
*
* @param string $oldVersion
* @param string $newVersion
@@ -90,6 +90,7 @@ class UpdaterTest extends TestCase {
* @param bool $debug
* @param string $vendor
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('versionCompatibilityTestData')]
public function testIsUpgradePossible($oldVersion, $newVersion, $allowedVersions, $result, $debug = false, $vendor = 'nextcloud'): void {
$this->config->expects($this->any())
->method('getSystemValueBool')
diff --git a/tests/lib/UrlGeneratorTest.php b/tests/lib/UrlGeneratorTest.php
index ed7b797d809..4320efc4190 100644
--- a/tests/lib/UrlGeneratorTest.php
+++ b/tests/lib/UrlGeneratorTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -8,6 +9,7 @@
namespace Test;
use OC\Route\Router;
+use OC\URLGenerator;
use OCP\ICacheFactory;
use OCP\IConfig;
use OCP\IRequest;
@@ -42,7 +44,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,
@@ -69,8 +71,8 @@ class UrlGeneratorTest extends \Test\TestCase {
/**
* @small
* test linkTo URL construction
- * @dataProvider provideDocRootAppUrlParts
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('provideDocRootAppUrlParts')]
public function testLinkToDocRoot($app, $file, $args, $expectedResult): void {
\OC::$WEBROOT = '';
$result = $this->urlGenerator->linkTo($app, $file, $args);
@@ -80,17 +82,15 @@ class UrlGeneratorTest extends \Test\TestCase {
/**
* @small
* test linkTo URL construction in sub directory
- * @dataProvider provideSubDirAppUrlParts
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('provideSubDirAppUrlParts')]
public function testLinkToSubDir($app, $file, $args, $expectedResult): void {
\OC::$WEBROOT = '/nextcloud';
$result = $this->urlGenerator->linkTo($app, $file, $args);
$this->assertEquals($expectedResult, $result);
}
- /**
- * @dataProvider provideRoutes
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('provideRoutes')]
public function testLinkToRouteAbsolute($route, $expected): void {
$this->mockBaseUrl();
\OC::$WEBROOT = '/nextcloud';
@@ -107,14 +107,14 @@ class UrlGeneratorTest extends \Test\TestCase {
$this->assertEquals($expected, $result);
}
- public static function provideRoutes() {
+ public static function provideRoutes(): array {
return [
['core.Preview.getPreview', 'http://localhost/nextcloud/index.php/core/preview.png'],
['cloud_federation_api.requesthandlercontroller.addShare', 'http://localhost/nextcloud/index.php/ocm/shares'],
];
}
- public static function provideDocRootAppUrlParts() {
+ public static function provideDocRootAppUrlParts(): array {
return [
['files_external', 'ajax/oauth2.php', [], '/index.php/apps/files_external/ajax/oauth2.php'],
['files_external', 'ajax/oauth2.php', ['trut' => 'trat', 'dut' => 'dat'], '/index.php/apps/files_external/ajax/oauth2.php?trut=trat&dut=dat'],
@@ -122,7 +122,7 @@ class UrlGeneratorTest extends \Test\TestCase {
];
}
- public static function provideSubDirAppUrlParts() {
+ public static function provideSubDirAppUrlParts(): array {
return [
['files_external', 'ajax/oauth2.php', [], '/nextcloud/index.php/apps/files_external/ajax/oauth2.php'],
['files_external', 'ajax/oauth2.php', ['trut' => 'trat', 'dut' => 'dat'], '/nextcloud/index.php/apps/files_external/ajax/oauth2.php?trut=trat&dut=dat'],
@@ -133,8 +133,8 @@ class UrlGeneratorTest extends \Test\TestCase {
/**
* @small
* test absolute URL construction
- * @dataProvider provideDocRootURLs
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('provideDocRootURLs')]
public function testGetAbsoluteURLDocRoot($url, $expectedResult): void {
$this->mockBaseUrl();
\OC::$WEBROOT = '';
@@ -145,8 +145,8 @@ class UrlGeneratorTest extends \Test\TestCase {
/**
* @small
* test absolute URL construction
- * @dataProvider provideSubDirURLs
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('provideSubDirURLs')]
public function testGetAbsoluteURLSubDir($url, $expectedResult): void {
$this->mockBaseUrl();
\OC::$WEBROOT = '/nextcloud';
@@ -154,7 +154,7 @@ class UrlGeneratorTest extends \Test\TestCase {
$this->assertEquals($expectedResult, $result);
}
- public function provideDocRootURLs() {
+ public static function provideDocRootURLs(): array {
return [
['index.php', 'http://localhost/index.php'],
['/index.php', 'http://localhost/index.php'],
@@ -163,7 +163,7 @@ class UrlGeneratorTest extends \Test\TestCase {
];
}
- public function provideSubDirURLs() {
+ public static function provideSubDirURLs(): array {
return [
['', 'http://localhost/nextcloud/'],
['/', 'http://localhost/nextcloud/'],
@@ -188,9 +188,7 @@ class UrlGeneratorTest extends \Test\TestCase {
$this->assertEquals(\OC::$WEBROOT, $actual);
}
- /**
- * @dataProvider provideOCSRoutes
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('provideOCSRoutes')]
public function testLinkToOCSRouteAbsolute(string $route, bool $ignoreFrontController, string $expected): void {
$this->mockBaseUrl();
\OC::$WEBROOT = '/nextcloud';
@@ -213,7 +211,7 @@ class UrlGeneratorTest extends \Test\TestCase {
$this->assertEquals($expected, $result);
}
- public function provideOCSRoutes(): array {
+ public static function provideOCSRoutes(): array {
return [
['core.OCS.getCapabilities', false, 'http://localhost/nextcloud/ocs/v2.php/cloud/capabilities'],
['core.OCS.getCapabilities', true, 'http://localhost/nextcloud/ocs/v2.php/cloud/capabilities'],
@@ -268,16 +266,14 @@ class UrlGeneratorTest extends \Test\TestCase {
$this->assertSame('http://localhost' . \OC::$WEBROOT . '/apps/dashboard/', $this->urlGenerator->linkToDefaultPageUrl());
}
- public function imagePathProvider(): array {
+ public static function imagePathProvider(): array {
return [
['core', 'favicon-mask.svg', \OC::$WEBROOT . '/core/img/favicon-mask.svg'],
['files', 'folder.svg', \OC::$WEBROOT . '/apps/files/img/folder.svg'],
];
}
- /**
- * @dataProvider imagePathProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('imagePathProvider')]
public function testImagePath(string $appName, string $file, string $result): void {
$this->assertSame($result, $this->urlGenerator->imagePath($appName, $file));
}
diff --git a/tests/lib/User/AvatarUserDummy.php b/tests/lib/User/AvatarUserDummy.php
index d443a31e3f0..001dabd24c6 100644
--- a/tests/lib/User/AvatarUserDummy.php
+++ b/tests/lib/User/AvatarUserDummy.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2020-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
diff --git a/tests/lib/User/Backend.php b/tests/lib/User/Backend.php
index ed17776476a..dc5b245fa06 100644
--- a/tests/lib/User/Backend.php
+++ b/tests/lib/User/Backend.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2017-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
diff --git a/tests/lib/User/DatabaseTest.php b/tests/lib/User/DatabaseTest.php
index 900f0ddd3fa..33101173c0a 100644
--- a/tests/lib/User/DatabaseTest.php
+++ b/tests/lib/User/DatabaseTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -7,6 +8,7 @@
namespace Test\User;
+use OC\User\Database;
use OC\User\User;
use OCP\EventDispatcher\Event;
use OCP\EventDispatcher\IEventDispatcher;
@@ -39,7 +41,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 +60,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 +73,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 +81,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/Dummy.php b/tests/lib/User/Dummy.php
index ffc5d343200..ec5be8ec60a 100644
--- a/tests/lib/User/Dummy.php
+++ b/tests/lib/User/Dummy.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
diff --git a/tests/lib/User/ManagerTest.php b/tests/lib/User/ManagerTest.php
index 5d3966cf4d8..d5872787d0a 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 {
@@ -365,9 +368,7 @@ class ManagerTest extends TestCase {
];
}
- /**
- * @dataProvider dataCreateUserInvalid
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataCreateUserInvalid')]
public function testCreateUserInvalid($uid, $password, $exception): void {
/** @var \Test\Util\User\Dummy|\PHPUnit\Framework\MockObject\MockObject $backend */
$backend = $this->createMock(\Test\Util\User\Dummy::class);
@@ -545,7 +546,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 +575,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 +588,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 +610,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 +635,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 +661,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 +699,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 7ed02571460..50c449559a0 100644
--- a/tests/lib/User/SessionTest.php
+++ b/tests/lib/User/SessionTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -96,7 +97,7 @@ class SessionTest extends \Test\TestCase {
$this->logger,
$this->dispatcher
])
- ->setMethods([
+ ->onlyMethods([
'setMagicInCookie',
])
->getMock();
@@ -104,16 +105,14 @@ class SessionTest extends \Test\TestCase {
\OC_User::setIncognitoMode(false);
}
- public function isLoggedInData() {
+ public static function isLoggedInData(): array {
return [
[true],
[false],
];
}
- /**
- * @dataProvider isLoggedInData
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('isLoggedInData')]
public function testIsLoggedIn($isLoggedIn): void {
$session = $this->createMock(Memory::class);
@@ -121,7 +120,7 @@ class SessionTest extends \Test\TestCase {
$userSession = $this->getMockBuilder(Session::class)
->setConstructorArgs([$manager, $session, $this->timeFactory, $this->tokenProvider, $this->config, $this->random, $this->lockdownManager, $this->logger, $this->dispatcher])
- ->setMethods([
+ ->onlyMethods([
'getUser'
])
->getMock();
@@ -158,7 +157,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) {
@@ -177,7 +176,7 @@ class SessionTest extends \Test\TestCase {
//keep following methods intact in order to ensure hooks are working
$mockedManagerMethods = array_diff($managerMethods, ['__construct', 'emit', 'listen']);
$manager = $this->getMockBuilder(Manager::class)
- ->setMethods($mockedManagerMethods)
+ ->onlyMethods($mockedManagerMethods)
->setConstructorArgs([
$this->config,
$this->createMock(ICacheFactory::class),
@@ -205,7 +204,7 @@ class SessionTest extends \Test\TestCase {
$userSession = $this->getMockBuilder(Session::class)
->setConstructorArgs([$manager, $session, $this->timeFactory, $this->tokenProvider, $this->config, $this->random, $this->lockdownManager, $this->logger, $this->dispatcher])
- ->setMethods([
+ ->onlyMethods([
'prepareUserLogin'
])
->getMock();
@@ -216,9 +215,9 @@ class SessionTest extends \Test\TestCase {
->method('dispatchTyped')
->with(
$this->callback(function (PostLoginEvent $e) {
- return $e->getUser()->getUID() === 'foo' &&
- $e->getPassword() === 'bar' &&
- $e->isTokenLogin() === false;
+ return $e->getUser()->getUID() === 'foo'
+ && $e->getPassword() === 'bar'
+ && $e->isTokenLogin() === false;
})
);
@@ -238,13 +237,13 @@ 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
$mockedManagerMethods = array_diff($managerMethods, ['__construct', 'emit', 'listen']);
$manager = $this->getMockBuilder(Manager::class)
- ->setMethods($mockedManagerMethods)
+ ->onlyMethods($mockedManagerMethods)
->setConstructorArgs([
$this->config,
$this->createMock(ICacheFactory::class),
@@ -278,7 +277,7 @@ class SessionTest extends \Test\TestCase {
//keep following methods intact in order to ensure hooks are working
$mockedManagerMethods = array_diff($managerMethods, ['__construct', 'emit', 'listen']);
$manager = $this->getMockBuilder(Manager::class)
- ->setMethods($mockedManagerMethods)
+ ->onlyMethods($mockedManagerMethods)
->setConstructorArgs([
$this->config,
$this->createMock(ICacheFactory::class),
@@ -298,7 +297,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');
@@ -322,7 +321,7 @@ class SessionTest extends \Test\TestCase {
// Keep following methods intact in order to ensure hooks are working
$mockedManagerMethods = array_diff($managerMethods, ['__construct', 'emit', 'listen']);
$manager = $this->getMockBuilder(Manager::class)
- ->setMethods($mockedManagerMethods)
+ ->onlyMethods($mockedManagerMethods)
->setConstructorArgs([
$this->config,
$this->createMock(ICacheFactory::class),
@@ -360,7 +359,7 @@ class SessionTest extends \Test\TestCase {
// Keep following methods intact in order to ensure hooks are working
$mockedManagerMethods = array_diff($managerMethods, ['__construct', 'emit', 'listen']);
$manager = $this->getMockBuilder(Manager::class)
- ->setMethods($mockedManagerMethods)
+ ->onlyMethods($mockedManagerMethods)
->setConstructorArgs([
$this->config,
$this->createMock(ICacheFactory::class),
@@ -404,7 +403,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')
@@ -424,13 +423,13 @@ class SessionTest extends \Test\TestCase {
/** @var Session $userSession */
$userSession = $this->getMockBuilder(Session::class)
->setConstructorArgs([$manager, $session, $this->timeFactory, $this->tokenProvider, $this->config, $this->random, $this->lockdownManager, $this->logger, $this->dispatcher])
- ->setMethods(['login', 'supportsCookies', 'createSessionToken', 'getUser'])
+ ->onlyMethods(['login', 'supportsCookies', 'createSessionToken', 'getUser'])
->getMock();
$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)
@@ -460,13 +459,13 @@ class SessionTest extends \Test\TestCase {
/** @var Session $userSession */
$userSession = $this->getMockBuilder(Session::class)
->setConstructorArgs([$manager, $session, $this->timeFactory, $this->tokenProvider, $this->config, $this->random, $this->lockdownManager, $this->logger, $this->dispatcher])
- ->setMethods(['login', 'supportsCookies', 'createSessionToken', 'getUser'])
+ ->onlyMethods(['login', 'supportsCookies', 'createSessionToken', 'getUser'])
->getMock();
$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)
@@ -486,7 +485,7 @@ class SessionTest extends \Test\TestCase {
/** @var Session $userSession */
$userSession = $this->getMockBuilder(Session::class)
->setConstructorArgs([$manager, $session, $this->timeFactory, $this->tokenProvider, $this->config, $this->random, $this->lockdownManager, $this->logger, $this->dispatcher])
- ->setMethods(['isTokenPassword', 'login', 'supportsCookies', 'createSessionToken', 'getUser'])
+ ->onlyMethods(['isTokenPassword', 'login', 'supportsCookies', 'createSessionToken', 'getUser'])
->getMock();
$userSession->expects($this->once())
@@ -528,13 +527,13 @@ class SessionTest extends \Test\TestCase {
/** @var Session $userSession */
$userSession = $this->getMockBuilder(Session::class)
->setConstructorArgs([$manager, $session, $this->timeFactory, $this->tokenProvider, $this->config, $this->random, $this->lockdownManager, $this->logger, $this->dispatcher])
- ->setMethods(['login', 'isTwoFactorEnforced'])
+ ->onlyMethods(['login', 'isTwoFactorEnforced'])
->getMock();
$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 +634,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');
}
@@ -657,7 +656,7 @@ class SessionTest extends \Test\TestCase {
//keep following methods intact in order to ensure hooks are working
$mockedManagerMethods = array_diff($managerMethods, ['__construct', 'emit', 'listen']);
$manager = $this->getMockBuilder(Manager::class)
- ->setMethods($mockedManagerMethods)
+ ->onlyMethods($mockedManagerMethods)
->setConstructorArgs([
$this->config,
$this->createMock(ICacheFactory::class),
@@ -667,7 +666,7 @@ class SessionTest extends \Test\TestCase {
->getMock();
$userSession = $this->getMockBuilder(Session::class)
//override, otherwise tests will fail because of setcookie()
- ->setMethods(['setMagicInCookie', 'setLoginName'])
+ ->onlyMethods(['setMagicInCookie', 'setLoginName'])
->setConstructorArgs([$manager, $session, $this->timeFactory, $this->tokenProvider, $this->config, $this->random, $this->lockdownManager, $this->logger, $this->dispatcher])
->getMock();
@@ -725,7 +724,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;
}
@@ -747,7 +746,7 @@ class SessionTest extends \Test\TestCase {
//keep following methods intact in order to ensure hooks are working
$mockedManagerMethods = array_diff($managerMethods, ['__construct', 'emit', 'listen']);
$manager = $this->getMockBuilder(Manager::class)
- ->setMethods($mockedManagerMethods)
+ ->onlyMethods($mockedManagerMethods)
->setConstructorArgs([
$this->config,
$this->createMock(ICacheFactory::class),
@@ -757,7 +756,7 @@ class SessionTest extends \Test\TestCase {
->getMock();
$userSession = $this->getMockBuilder(Session::class)
//override, otherwise tests will fail because of setcookie()
- ->setMethods(['setMagicInCookie'])
+ ->onlyMethods(['setMagicInCookie'])
->setConstructorArgs([$manager, $session, $this->timeFactory, $this->tokenProvider, $this->config, $this->random, $this->lockdownManager, $this->logger, $this->dispatcher])
->getMock();
@@ -788,7 +787,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')
@@ -812,7 +811,7 @@ class SessionTest extends \Test\TestCase {
//keep following methods intact in order to ensure hooks are working
$mockedManagerMethods = array_diff($managerMethods, ['__construct', 'emit', 'listen']);
$manager = $this->getMockBuilder(Manager::class)
- ->setMethods($mockedManagerMethods)
+ ->onlyMethods($mockedManagerMethods)
->setConstructorArgs([
$this->config,
$this->createMock(ICacheFactory::class),
@@ -822,7 +821,7 @@ class SessionTest extends \Test\TestCase {
->getMock();
$userSession = $this->getMockBuilder(Session::class)
//override, otherwise tests will fail because of setcookie()
- ->setMethods(['setMagicInCookie'])
+ ->onlyMethods(['setMagicInCookie'])
->setConstructorArgs([$manager, $session, $this->timeFactory, $this->tokenProvider, $this->config, $this->random, $this->lockdownManager, $this->logger, $this->dispatcher])
->getMock();
@@ -865,7 +864,7 @@ class SessionTest extends \Test\TestCase {
//keep following methods intact in order to ensure hooks are working
$mockedManagerMethods = array_diff($managerMethods, ['__construct', 'emit', 'listen']);
$manager = $this->getMockBuilder(Manager::class)
- ->setMethods($mockedManagerMethods)
+ ->onlyMethods($mockedManagerMethods)
->setConstructorArgs([
$this->config,
$this->createMock(ICacheFactory::class),
@@ -875,7 +874,7 @@ class SessionTest extends \Test\TestCase {
->getMock();
$userSession = $this->getMockBuilder(Session::class)
//override, otherwise tests will fail because of setcookie()
- ->setMethods(['setMagicInCookie'])
+ ->onlyMethods(['setMagicInCookie'])
->setConstructorArgs([$manager, $session, $this->timeFactory, $this->tokenProvider, $this->config, $this->random, $this->lockdownManager, $this->logger, $this->dispatcher])
->getMock();
$token = 'goodToken';
@@ -925,7 +924,7 @@ class SessionTest extends \Test\TestCase {
$session->set('user_id', 'foo');
$userSession = $this->getMockBuilder(Session::class)
->setConstructorArgs([$manager, $session, $this->timeFactory, $this->tokenProvider, $this->config, $this->random, $this->lockdownManager, $this->logger, $this->dispatcher])
- ->setMethods([
+ ->onlyMethods([
'validateSession'
])
->getMock();
@@ -972,7 +971,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 +1012,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 +1129,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;
@@ -1155,7 +1154,7 @@ class SessionTest extends \Test\TestCase {
$this->logger,
$this->dispatcher
])
- ->setMethods([
+ ->onlyMethods([
'logClientIn',
'getUser',
])
@@ -1207,7 +1206,7 @@ class SessionTest extends \Test\TestCase {
$this->logger,
$this->dispatcher
])
- ->setMethods([
+ ->onlyMethods([
'logClientIn',
])
->getMock();
@@ -1235,7 +1234,7 @@ class SessionTest extends \Test\TestCase {
/** @var Session $userSession */
$userSession = $this->getMockBuilder(Session::class)
->setConstructorArgs([$manager, $session, $this->timeFactory, $this->tokenProvider, $this->config, $this->random, $this->lockdownManager, $this->logger, $this->dispatcher])
- ->setMethods(['isTokenPassword', 'login', 'supportsCookies', 'createSessionToken', 'getUser'])
+ ->onlyMethods(['isTokenPassword', 'login', 'supportsCookies', 'createSessionToken', 'getUser'])
->getMock();
$userSession->expects($this->once())
@@ -1281,7 +1280,7 @@ class SessionTest extends \Test\TestCase {
/** @var Session $userSession */
$userSession = $this->getMockBuilder(Session::class)
->setConstructorArgs([$manager, $session, $this->timeFactory, $this->tokenProvider, $this->config, $this->random, $this->lockdownManager, $this->logger, $this->dispatcher])
- ->setMethods(['isTokenPassword', 'login', 'supportsCookies', 'createSessionToken', 'getUser'])
+ ->onlyMethods(['isTokenPassword', 'login', 'supportsCookies', 'createSessionToken', 'getUser'])
->getMock();
$userSession->expects($this->once())
diff --git a/tests/lib/User/UserTest.php b/tests/lib/User/UserTest.php
index 44d28481ed5..05056c92193 100644
--- a/tests/lib/User/UserTest.php
+++ b/tests/lib/User/UserTest.php
@@ -11,9 +11,11 @@ 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;
+use OCP\Files\FileInfo;
use OCP\Files\Storage\IStorageFactory;
use OCP\IConfig;
use OCP\IURLGenerator;
@@ -217,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');
@@ -283,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());
}
@@ -391,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')
@@ -420,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')
@@ -441,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')
@@ -470,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);
@@ -496,7 +498,7 @@ class UserTest extends TestCase {
$this->assertEquals(2, $hooksCalled);
}
- public function dataDeleteHooks() {
+ public static function dataDeleteHooks(): array {
return [
[true, 2],
[false, 1],
@@ -504,10 +506,10 @@ class UserTest extends TestCase {
}
/**
- * @dataProvider dataDeleteHooks
* @param bool $result
* @param int $expectedHooks
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataDeleteHooks')]
public function testDeleteHooks($result, $expectedHooks): void {
$hooksCalled = 0;
$test = $this;
@@ -536,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());
};
@@ -585,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);
}
@@ -616,7 +618,7 @@ class UserTest extends TestCase {
$userConfig = [];
$config->expects(self::atLeast(2))
->method('setUserValue')
- ->willReturnCallback(function () {
+ ->willReturnCallback(function (): void {
$userConfig[] = func_get_args();
});
@@ -625,14 +627,14 @@ 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)
->onlyMethods(['getHome'])
->setConstructorArgs(['foo', $backend, $this->dispatcher, null, $config])
->getMock();
-
+
$user->expects(self::atLeastOnce())
->method('getHome')
->willReturn('/home/path');
@@ -647,19 +649,17 @@ class UserTest extends TestCase {
$userConfig,
);
- $this->restoreService(\OCP\Comments\ICommentsManager::class);
+ $this->restoreService(ICommentsManager::class);
}
- public function dataGetCloudId(): array {
+ public static function dataGetCloudId(): array {
return [
['https://localhost:8888/nextcloud', 'foo@localhost:8888/nextcloud'],
['http://localhost:8888/nextcloud', 'foo@http://localhost:8888/nextcloud'],
];
}
- /**
- * @dataProvider dataGetCloudId
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataGetCloudId')]
public function testGetCloudId(string $absoluteUrl, string $cloudId): void {
/** @var Backend|MockObject $backend */
$backend = $this->createMock(\Test\Util\User\Dummy::class);
@@ -685,7 +685,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);
@@ -721,7 +721,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);
@@ -784,7 +784,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);
@@ -830,12 +830,12 @@ 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);
- $quota = $user->getQuota();
- $this->assertEquals('none', $quota);
+ $this->assertEquals('none', $user->getQuota());
+ $this->assertEquals(FileInfo::SPACE_UNLIMITED, $user->getQuotaBytes());
}
public function testGetDefaultUnlimitedQuotaForbidden(): void {
@@ -864,12 +864,12 @@ 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);
- $quota = $user->getQuota();
- $this->assertEquals('1 GB', $quota);
+ $this->assertEquals('1 GB', $user->getQuota());
+ $this->assertEquals(1024 * 1024 * 1024, $user->getQuotaBytes());
}
public function testSetQuotaAddressNoChange(): void {
@@ -964,7 +964,7 @@ class UserTest extends TestCase {
null,
$config,
])
- ->setMethods(['isEnabled', 'triggerChange'])
+ ->onlyMethods(['isEnabled', 'triggerChange'])
->getMock();
$user->expects($this->once())
@@ -998,7 +998,7 @@ class UserTest extends TestCase {
null,
$config,
])
- ->setMethods(['isEnabled', 'triggerChange'])
+ ->onlyMethods(['isEnabled', 'triggerChange'])
->getMock();
$user->expects($this->once())
diff --git a/tests/lib/Util/Group/Dummy.php b/tests/lib/Util/Group/Dummy.php
index 50edc15c845..fab94cdc645 100644
--- a/tests/lib/Util/Group/Dummy.php
+++ b/tests/lib/Util/Group/Dummy.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
diff --git a/tests/lib/Util/User/Dummy.php b/tests/lib/Util/User/Dummy.php
index d44b9d85d72..6ecd378c1de 100644
--- a/tests/lib/Util/User/Dummy.php
+++ b/tests/lib/Util/User/Dummy.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -8,11 +9,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..087c67120a3 100644
--- a/tests/lib/UtilCheckServerTest.php
+++ b/tests/lib/UtilCheckServerTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -7,6 +8,12 @@
namespace Test;
+use OC\SystemConfig;
+use OCP\ISession;
+use OCP\ITempManager;
+use OCP\Server;
+use OCP\Util;
+
/**
* Tests for server check functions
*
@@ -17,7 +24,7 @@ class UtilCheckServerTest extends \Test\TestCase {
/**
* @param array $systemOptions
- * @return \OC\SystemConfig | \PHPUnit\Framework\MockObject\MockObject
+ * @return SystemConfig|\PHPUnit\Framework\MockObject\MockObject
*/
protected function getConfig($systemOptions) {
$systemOptions['datadirectory'] = $this->datadir;
@@ -37,10 +44,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 +92,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 +130,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 +141,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 +155,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 +167,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 0063a991e48..6d995be2434 100644
--- a/tests/lib/UtilTest.php
+++ b/tests/lib/UtilTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -8,6 +9,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 +101,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 +109,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 +117,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 +127,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 +138,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);
@@ -334,4 +340,80 @@ class UtilTest extends \Test\TestCase {
// each of the characters is 12 bytes
$this->assertEquals('🙈', Util::shortenMultibyteString('🙈🙊🙉', 16, 2));
}
+
+ #[\PHPUnit\Framework\Attributes\DataProvider('humanFileSizeProvider')]
+ public function testHumanFileSize($expected, $input): void {
+ $result = Util::humanFileSize($input);
+ $this->assertEquals($expected, $result);
+ }
+
+ public static function humanFileSizeProvider(): array {
+ return [
+ ['0 B', 0],
+ ['1 KB', 1024],
+ ['9.5 MB', 10000000],
+ ['1.3 GB', 1395864371],
+ ['465.7 GB', 500000000000],
+ ['454.7 TB', 500000000000000],
+ ['444.1 PB', 500000000000000000],
+ ];
+ }
+
+ #[\PHPUnit\Framework\Attributes\DataProvider('providesComputerFileSize')]
+ public function testComputerFileSize($expected, $input): void {
+ $result = Util::computerFileSize($input);
+ $this->assertEquals($expected, $result);
+ }
+
+ public static function providesComputerFileSize(): array {
+ return [
+ [0.0, '0 B'],
+ [1024.0, '1 KB'],
+ [1395864371.0, '1.3 GB'],
+ [9961472.0, '9.5 MB'],
+ [500041567437.0, '465.7 GB'],
+ [false, '12 GB etfrhzui']
+ ];
+ }
+
+ public function testMb_array_change_key_case(): void {
+ $arrayStart = [
+ 'Foo' => 'bar',
+ 'Bar' => 'foo',
+ ];
+ $arrayResult = [
+ 'foo' => 'bar',
+ 'bar' => 'foo',
+ ];
+ $result = Util::mb_array_change_key_case($arrayStart);
+ $expected = $arrayResult;
+ $this->assertEquals($result, $expected);
+
+ $arrayStart = [
+ 'foo' => 'bar',
+ 'bar' => 'foo',
+ ];
+ $arrayResult = [
+ 'FOO' => 'bar',
+ 'BAR' => 'foo',
+ ];
+ $result = Util::mb_array_change_key_case($arrayStart, MB_CASE_UPPER);
+ $expected = $arrayResult;
+ $this->assertEquals($result, $expected);
+ }
+
+ public function testRecursiveArraySearch(): void {
+ $haystack = [
+ 'Foo' => 'own',
+ 'Bar' => 'Cloud',
+ ];
+
+ $result = Util::recursiveArraySearch($haystack, 'own');
+ $expected = 'Foo';
+ $this->assertEquals($result, $expected);
+
+ $result = Util::recursiveArraySearch($haystack, 'NotFound');
+ $this->assertFalse($result);
+ }
+
}